SemaExprCXX.cpp revision 60d62c29d260596454aaf4cb50cbc756ac08875e
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "SemaInherit.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/Parse/DeclSpec.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Basic/Diagnostic.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/Support/Debug.h"
23using namespace clang;
24
25/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
26Action::ExprResult
27Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
28                        SourceLocation LAngleBracketLoc, TypeTy *Ty,
29                        SourceLocation RAngleBracketLoc,
30                        SourceLocation LParenLoc, ExprTy *E,
31                        SourceLocation RParenLoc) {
32  Expr *Ex = (Expr*)E;
33  QualType DestType = QualType::getFromOpaquePtr(Ty);
34
35  switch (Kind) {
36  default: assert(0 && "Unknown C++ cast!");
37
38  case tok::kw_const_cast:
39    CheckConstCast(OpLoc, Ex, DestType);
40    return new CXXConstCastExpr(DestType.getNonReferenceType(), Ex,
41                                DestType, OpLoc);
42
43  case tok::kw_dynamic_cast:
44    CheckDynamicCast(OpLoc, Ex, DestType,
45      SourceRange(LAngleBracketLoc, RAngleBracketLoc));
46    return new CXXDynamicCastExpr(DestType.getNonReferenceType(), Ex,
47                                  DestType, OpLoc);
48
49  case tok::kw_reinterpret_cast:
50    CheckReinterpretCast(OpLoc, Ex, DestType);
51    return new CXXReinterpretCastExpr(DestType.getNonReferenceType(), Ex,
52                                      DestType, OpLoc);
53
54  case tok::kw_static_cast:
55    CheckStaticCast(OpLoc, Ex, DestType);
56    return new CXXStaticCastExpr(DestType.getNonReferenceType(), Ex,
57                                 DestType, OpLoc);
58  }
59
60  return true;
61}
62
63/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
64/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
65/// like this:
66/// const char *str = "literal";
67/// legacy_function(const_cast\<char*\>(str));
68void
69Sema::CheckConstCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType)
70{
71  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
72
73  DestType = Context.getCanonicalType(DestType);
74  QualType SrcType = SrcExpr->getType();
75  if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
76    if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
77      // Cannot cast non-lvalue to reference type.
78      Diag(OpLoc, diag::err_bad_cxx_cast_rvalue,
79        "const_cast", OrigDestType.getAsString());
80      return;
81    }
82
83    // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
84    //   [...] if a pointer to T1 can be [cast] to the type pointer to T2.
85    DestType = Context.getPointerType(DestTypeTmp->getPointeeType());
86    SrcType = Context.getPointerType(SrcType);
87  } else {
88    // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
89    //   lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
90    //   conversions are performed on the expression.
91    DefaultFunctionArrayConversion(SrcExpr);
92    SrcType = SrcExpr->getType();
93  }
94
95  if (!DestType->isPointerType()) {
96    // Cannot cast to non-pointer, non-reference type. Note that, if DestType
97    // was a reference type, we converted it to a pointer above.
98    // C++ 5.2.11p3: For two pointer types [...]
99    Diag(OpLoc, diag::err_bad_const_cast_dest, OrigDestType.getAsString());
100    return;
101  }
102  if (DestType->isFunctionPointerType()) {
103    // Cannot cast direct function pointers.
104    // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
105    // T is the ultimate pointee of source and target type.
106    Diag(OpLoc, diag::err_bad_const_cast_dest, OrigDestType.getAsString());
107    return;
108  }
109  SrcType = Context.getCanonicalType(SrcType);
110
111  // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
112  // completely equal.
113  // FIXME: const_cast should probably not be able to convert between pointers
114  // to different address spaces.
115  // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
116  // in multi-level pointers may change, but the level count must be the same,
117  // as must be the final pointee type.
118  while (SrcType != DestType && UnwrapSimilarPointerTypes(SrcType, DestType)) {
119    SrcType = SrcType.getUnqualifiedType();
120    DestType = DestType.getUnqualifiedType();
121  }
122
123  // Doug Gregor said to disallow this until users complain.
124#if 0
125  // If we end up with constant arrays of equal size, unwrap those too. A cast
126  // from const int [N] to int (&)[N] is invalid by my reading of the
127  // standard, but g++ accepts it even with -ansi -pedantic.
128  // No more than one level, though, so don't embed this in the unwrap loop
129  // above.
130  const ConstantArrayType *SrcTypeArr, *DestTypeArr;
131  if ((SrcTypeArr = Context.getAsConstantArrayType(SrcType)) &&
132     (DestTypeArr = Context.getAsConstantArrayType(DestType)))
133  {
134    if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
135      // Different array sizes.
136      Diag(OpLoc, diag::err_bad_cxx_cast_generic, "const_cast",
137        OrigDestType.getAsString(), OrigSrcType.getAsString());
138      return;
139    }
140    SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
141    DestType = DestTypeArr->getElementType().getUnqualifiedType();
142  }
143#endif
144
145  // Since we're dealing in canonical types, the remainder must be the same.
146  if (SrcType != DestType) {
147    // Cast between unrelated types.
148    Diag(OpLoc, diag::err_bad_cxx_cast_generic, "const_cast",
149      OrigDestType.getAsString(), OrigSrcType.getAsString());
150    return;
151  }
152}
153
154/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
155/// valid.
156/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
157/// like this:
158/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
159void
160Sema::CheckReinterpretCast(SourceLocation OpLoc, Expr *&SrcExpr,
161                           QualType DestType)
162{
163  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
164
165  DestType = Context.getCanonicalType(DestType);
166  QualType SrcType = SrcExpr->getType();
167  if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
168    if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
169      // Cannot cast non-lvalue to reference type.
170      Diag(OpLoc, diag::err_bad_cxx_cast_rvalue,
171        "reinterpret_cast", OrigDestType.getAsString());
172      return;
173    }
174
175    // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
176    //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
177    //   built-in & and * operators.
178    // This code does this transformation for the checked types.
179    DestType = Context.getPointerType(DestTypeTmp->getPointeeType());
180    SrcType = Context.getPointerType(SrcType);
181  } else {
182    // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
183    //   function-to-pointer standard conversions are performed on the
184    //   expression v.
185    DefaultFunctionArrayConversion(SrcExpr);
186    SrcType = SrcExpr->getType();
187  }
188
189  // Canonicalize source for comparison.
190  SrcType = Context.getCanonicalType(SrcType);
191
192  bool destIsPtr = DestType->isPointerType();
193  bool srcIsPtr = SrcType->isPointerType();
194  if (!destIsPtr && !srcIsPtr) {
195    // Except for std::nullptr_t->integer, which is not supported yet, and
196    // lvalue->reference, which is handled above, at least one of the two
197    // arguments must be a pointer.
198    Diag(OpLoc, diag::err_bad_cxx_cast_generic, "reinterpret_cast",
199      OrigDestType.getAsString(), OrigSrcType.getAsString());
200    return;
201  }
202
203  if (SrcType == DestType) {
204    // C++ 5.2.10p2 has a note that mentions that, subject to all other
205    // restrictions, a cast to the same type is allowed. The intent is not
206    // entirely clear here, since all other paragraphs explicitly forbid casts
207    // to the same type. However, the behavior of compilers is pretty consistent
208    // on this point: allow same-type conversion if the involved are pointers,
209    // disallow otherwise.
210    return;
211  }
212
213  // Note: Clang treats enumeration types as integral types. If this is ever
214  // changed for C++, the additional check here will be redundant.
215  if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
216    assert(srcIsPtr);
217    // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
218    //   type large enough to hold it.
219    if (Context.getTypeSize(SrcType) > Context.getTypeSize(DestType)) {
220      Diag(OpLoc, diag::err_bad_reinterpret_cast_small_int,
221        OrigDestType.getAsString());
222    }
223    return;
224  }
225
226  if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
227    assert(destIsPtr);
228    // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
229    //   converted to a pointer.
230    return;
231  }
232
233  if (!destIsPtr || !srcIsPtr) {
234    // With the valid non-pointer conversions out of the way, we can be even
235    // more stringent.
236    Diag(OpLoc, diag::err_bad_cxx_cast_generic, "reinterpret_cast",
237      OrigDestType.getAsString(), OrigSrcType.getAsString());
238    return;
239  }
240
241  // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
242  if (CastsAwayConstness(SrcType, DestType)) {
243    Diag(OpLoc, diag::err_bad_cxx_cast_const_away, "reinterpret_cast",
244      OrigDestType.getAsString(), OrigSrcType.getAsString());
245    return;
246  }
247
248  // Not casting away constness, so the only remaining check is for compatible
249  // pointer categories.
250
251  if (SrcType->isFunctionPointerType()) {
252    if (DestType->isFunctionPointerType()) {
253      // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
254      // a pointer to a function of a different type.
255      return;
256    }
257
258    // FIXME: Handle member pointers.
259
260    // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
261    //   an object type or vice versa is conditionally-supported.
262    // Compilers support it in C++03 too, though, because it's necessary for
263    // casting the return value of dlsym() and GetProcAddress().
264    // FIXME: Conditionally-supported behavior should be configurable in the
265    // TargetInfo or similar.
266    if (!getLangOptions().CPlusPlus0x) {
267      Diag(OpLoc, diag::ext_reinterpret_cast_fn_obj);
268    }
269    return;
270  }
271
272  // FIXME: Handle member pointers.
273
274  if (DestType->isFunctionPointerType()) {
275    // See above.
276    if (!getLangOptions().CPlusPlus0x) {
277      Diag(OpLoc, diag::ext_reinterpret_cast_fn_obj);
278    }
279    return;
280  }
281
282  // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
283  //   a pointer to an object of different type.
284  // Void pointers are not specified, but supported by every compiler out there.
285  // So we finish by allowing everything that remains - it's got to be two
286  // object pointers.
287}
288
289/// CastsAwayConstness - Check if the pointer conversion from SrcType
290/// to DestType casts away constness as defined in C++
291/// 5.2.11p8ff. This is used by the cast checkers.  Both arguments
292/// must denote pointer types.
293bool
294Sema::CastsAwayConstness(QualType SrcType, QualType DestType)
295{
296 // Casting away constness is defined in C++ 5.2.11p8 with reference to
297  // C++ 4.4.
298  // We piggyback on Sema::IsQualificationConversion for this, since the rules
299  // are non-trivial. So first we construct Tcv *...cv* as described in
300  // C++ 5.2.11p8.
301  SrcType  = Context.getCanonicalType(SrcType);
302  DestType = Context.getCanonicalType(DestType);
303
304  QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
305  llvm::SmallVector<unsigned, 8> cv1, cv2;
306
307  // Find the qualifications.
308  while (UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
309    cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
310    cv2.push_back(UnwrappedDestType.getCVRQualifiers());
311  }
312  assert(cv1.size() > 0 && "Must have at least one pointer level.");
313
314  // Construct void pointers with those qualifiers (in reverse order of
315  // unwrapping, of course).
316  QualType SrcConstruct = Context.VoidTy;
317  QualType DestConstruct = Context.VoidTy;
318  for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
319                                                        i2 = cv2.rbegin();
320       i1 != cv1.rend(); ++i1, ++i2)
321  {
322    SrcConstruct = Context.getPointerType(SrcConstruct.getQualifiedType(*i1));
323    DestConstruct = Context.getPointerType(DestConstruct.getQualifiedType(*i2));
324  }
325
326  // Test if they're compatible.
327  return SrcConstruct != DestConstruct &&
328    !IsQualificationConversion(SrcConstruct, DestConstruct);
329}
330
331/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
332/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
333/// implicit conversions explicit and getting rid of data loss warnings.
334void
335Sema::CheckStaticCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType)
336{
337  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
338
339  // Conversions are tried roughly in the order the standard specifies them.
340  // This is necessary because there are some conversions that can be
341  // interpreted in more than one way, and the order disambiguates.
342  // DR 427 specifies that paragraph 5 is to be applied before paragraph 2.
343
344  // This option is unambiguous and simple, so put it here.
345  // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
346  if (DestType->isVoidType()) {
347    return;
348  }
349
350  DestType = Context.getCanonicalType(DestType);
351
352  // C++ 5.2.9p5, reference downcast.
353  // See the function for details.
354  if (IsStaticReferenceDowncast(SrcExpr, DestType)) {
355    return;
356  }
357
358  // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
359  //   [...] if the declaration "T t(e);" is well-formed, [...].
360  ImplicitConversionSequence ICS = TryDirectInitialization(SrcExpr, DestType);
361  if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
362    if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
363        ICS.Standard.First != ICK_Identity)
364    {
365      DefaultFunctionArrayConversion(SrcExpr);
366    }
367    return;
368  }
369  // FIXME: Missing the validation of the conversion, e.g. for an accessible
370  // base.
371
372  // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
373  // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
374  // conversions, subject to further restrictions.
375  // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
376  // of qualification conversions impossible.
377
378  // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
379  // are applied to the expression.
380  DefaultFunctionArrayConversion(SrcExpr);
381
382  QualType SrcType = Context.getCanonicalType(SrcExpr->getType());
383
384  // Reverse integral promotion/conversion. All such conversions are themselves
385  // again integral promotions or conversions and are thus already handled by
386  // p2 (TryDirectInitialization above).
387  // (Note: any data loss warnings should be suppressed.)
388  // The exception is the reverse of enum->integer, i.e. integer->enum (and
389  // enum->enum). See also C++ 5.2.9p7.
390  // The same goes for reverse floating point promotion/conversion and
391  // floating-integral conversions. Again, only floating->enum is relevant.
392  if (DestType->isEnumeralType()) {
393    if (SrcType->isComplexType() || SrcType->isVectorType()) {
394      // Fall through - these cannot be converted.
395    } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
396      return;
397    }
398  }
399
400  // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
401  // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
402  if (IsStaticPointerDowncast(SrcType, DestType)) {
403    return;
404  }
405
406  // Reverse member pointer conversion. C++ 5.11 specifies member pointer
407  // conversion. C++ 5.2.9p9 has additional information.
408  // DR54's access restrictions apply here also.
409  // FIXME: Don't have member pointers yet.
410
411  // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
412  // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
413  // just the usual constness stuff.
414  if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
415    QualType SrcPointee = SrcPointer->getPointeeType();
416    if (SrcPointee->isVoidType()) {
417      if (const PointerType *DestPointer = DestType->getAsPointerType()) {
418        QualType DestPointee = DestPointer->getPointeeType();
419        if (DestPointee->isObjectType() &&
420            DestPointee.isAtLeastAsQualifiedAs(SrcPointee))
421        {
422          return;
423        }
424      }
425    }
426  }
427
428  // We tried everything. Everything! Nothing works! :-(
429  // FIXME: Error reporting could be a lot better. Should store the reason
430  // why every substep failed and, at the end, select the most specific and
431  // report that.
432  Diag(OpLoc, diag::err_bad_cxx_cast_generic, "static_cast",
433    OrigDestType.getAsString(), OrigSrcType.getAsString());
434}
435
436/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
437bool
438Sema::IsStaticReferenceDowncast(Expr *SrcExpr, QualType DestType)
439{
440  // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
441  //   cast to type "reference to cv2 D", where D is a class derived from B,
442  //   if a valid standard conversion from "pointer to D" to "pointer to B"
443  //   exists, cv2 >= cv1, and B is not a virtual base class of D.
444  // In addition, DR54 clarifies that the base must be accessible in the
445  // current context. Although the wording of DR54 only applies to the pointer
446  // variant of this rule, the intent is clearly for it to apply to the this
447  // conversion as well.
448
449  if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
450    return false;
451  }
452
453  DestType = Context.getCanonicalType(DestType);
454  const ReferenceType *DestReference = DestType->getAsReferenceType();
455  if (!DestReference) {
456    return false;
457  }
458  QualType DestPointee = DestReference->getPointeeType();
459
460  QualType SrcType = Context.getCanonicalType(SrcExpr->getType());
461
462  return IsStaticDowncast(SrcType, DestPointee);
463}
464
465/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
466bool
467Sema::IsStaticPointerDowncast(QualType SrcType, QualType DestType)
468{
469  // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
470  //   type, can be converted to an rvalue of type "pointer to cv2 D", where D
471  //   is a class derived from B, if a valid standard conversion from "pointer
472  //   to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
473  //   class of D.
474  // In addition, DR54 clarifies that the base must be accessible in the
475  // current context.
476
477  SrcType = Context.getCanonicalType(SrcType);
478  const PointerType *SrcPointer = SrcType->getAsPointerType();
479  if (!SrcPointer) {
480    return false;
481  }
482
483  DestType = Context.getCanonicalType(DestType);
484  const PointerType *DestPointer = DestType->getAsPointerType();
485  if (!DestPointer) {
486    return false;
487  }
488
489  return IsStaticDowncast(SrcPointer->getPointeeType(),
490                          DestPointer->getPointeeType());
491}
492
493/// IsStaticDowncast - Common functionality of IsStaticReferenceDowncast and
494/// IsStaticPointerDowncast. Tests whether a static downcast from SrcType to
495/// DestType, both of which must be canonical, is possible and allowed.
496bool
497Sema::IsStaticDowncast(QualType SrcType, QualType DestType)
498{
499  assert(SrcType->isCanonical());
500  assert(DestType->isCanonical());
501
502  if (!DestType->isRecordType()) {
503    return false;
504  }
505
506  if (!SrcType->isRecordType()) {
507    return false;
508  }
509
510  // Comparing cv is cheaper, so do it first.
511  if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
512    return false;
513  }
514
515  BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
516                  /*DetectVirtual=*/true);
517  if (!IsDerivedFrom(DestType, SrcType, Paths)) {
518    return false;
519  }
520
521  if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
522    return false;
523  }
524
525  if (Paths.getDetectedVirtual() != 0) {
526    return false;
527  }
528
529  // FIXME: Test accessibility.
530
531  return true;
532}
533
534/// TryDirectInitialization - Attempt to direct-initialize a value of the
535/// given type (DestType) from the given expression (SrcExpr), as one would
536/// do when creating an object with new with parameters. This function returns
537/// an implicit conversion sequence that can be used to perform the
538/// initialization.
539/// This routine is very similar to TryCopyInitialization; the differences
540/// between the two (C++ 8.5p12 and C++ 8.5p14) are:
541/// 1) In direct-initialization, all constructors of the target type are
542///    considered, including those marked as explicit.
543/// 2) In direct-initialization, overload resolution is performed over the
544///    constructors of the target type. In copy-initialization, overload
545///    resolution is performed over all conversion functions that result in
546///    the target type. This can lead to different functions used.
547ImplicitConversionSequence
548Sema::TryDirectInitialization(Expr *SrcExpr, QualType DestType)
549{
550  if (!DestType->isRecordType()) {
551    // For non-class types, copy and direct initialization are identical.
552    // C++ 8.5p11
553    // FIXME: Those parts should be in a common function, actually.
554    return TryCopyInitialization(SrcExpr, DestType);
555  }
556
557  // Not enough support for the rest yet, actually.
558  ImplicitConversionSequence ICS;
559  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
560  return ICS;
561}
562
563/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
564/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
565/// checked downcasts in class hierarchies.
566void
567Sema::CheckDynamicCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType,
568  const SourceRange &DestRange)
569{
570  QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
571  DestType = Context.getCanonicalType(DestType);
572
573  // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
574  //   or "pointer to cv void".
575
576  QualType DestPointee;
577  const PointerType *DestPointer = DestType->getAsPointerType();
578  const ReferenceType *DestReference = DestType->getAsReferenceType();
579  if (DestPointer) {
580    DestPointee = DestPointer->getPointeeType();
581  } else if (DestReference) {
582    DestPointee = DestReference->getPointeeType();
583  } else {
584    Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
585      OrigDestType.getAsString(), "not a reference or pointer", DestRange);
586    return;
587  }
588
589  const RecordType *DestRecord = DestPointee->getAsRecordType();
590  if (DestPointee->isVoidType()) {
591    assert(DestPointer && "Reference to void is not possible");
592  } else if (DestRecord) {
593    if (!DestRecord->getDecl()->isDefinition()) {
594      Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
595        DestPointee.getUnqualifiedType().getAsString(),
596        "incomplete", DestRange);
597      return;
598    }
599  } else {
600    Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
601      DestPointee.getUnqualifiedType().getAsString(),
602      "not a class", DestRange);
603    return;
604  }
605
606  // C++ 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
607  //   complete class type, [...]. If T is a reference type, v shall be an
608  //   lvalue of a complete class type, [...].
609
610  QualType SrcType = Context.getCanonicalType(OrigSrcType);
611  QualType SrcPointee;
612  if (DestPointer) {
613    if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
614      SrcPointee = SrcPointer->getPointeeType();
615    } else {
616      Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
617        OrigSrcType.getAsString(), "not a pointer", SrcExpr->getSourceRange());
618      return;
619    }
620  } else {
621    if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
622      Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
623        OrigDestType.getAsString(), "not an lvalue", SrcExpr->getSourceRange());
624    }
625    SrcPointee = SrcType;
626  }
627
628  const RecordType *SrcRecord = SrcPointee->getAsRecordType();
629  if (SrcRecord) {
630    if (!SrcRecord->getDecl()->isDefinition()) {
631      Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
632        SrcPointee.getUnqualifiedType().getAsString(), "incomplete",
633        SrcExpr->getSourceRange());
634      return;
635    }
636  } else {
637    Diag(OpLoc, diag::err_bad_dynamic_cast_operand,
638      SrcPointee.getUnqualifiedType().getAsString(), "not a class",
639      SrcExpr->getSourceRange());
640    return;
641  }
642
643  // Assumptions to this point.
644  assert(DestPointer || DestReference);
645  assert(DestRecord || DestPointee->isVoidType());
646  assert(SrcRecord);
647
648  // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
649  if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
650    Diag(OpLoc, diag::err_bad_cxx_cast_const_away, "dynamic_cast",
651      OrigDestType.getAsString(), OrigSrcType.getAsString());
652    return;
653  }
654
655  // C++ 5.2.7p3: If the type of v is the same as the required result type,
656  //   [except for cv].
657  if (DestRecord == SrcRecord) {
658    return;
659  }
660
661  // C++ 5.2.7p5
662  // Upcasts are resolved statically.
663  if (DestRecord && IsDerivedFrom(SrcPointee, DestPointee)) {
664    CheckDerivedToBaseConversion(SrcPointee, DestPointee, OpLoc, SourceRange());
665    // Diagnostic already emitted on error.
666    return;
667  }
668
669  // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
670  // FIXME: Information not yet available.
671
672  // Done. Everything else is run-time checks.
673}
674
675/// ActOnCXXBoolLiteral - Parse {true,false} literals.
676Action::ExprResult
677Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
678  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
679         "Unknown C++ Boolean value!");
680  return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
681}
682
683/// ActOnCXXThrow - Parse throw expressions.
684Action::ExprResult
685Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
686  return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
687}
688
689Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
690  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
691  /// is a non-lvalue expression whose value is the address of the object for
692  /// which the function is called.
693
694  if (!isa<FunctionDecl>(CurContext)) {
695    Diag(ThisLoc, diag::err_invalid_this_use);
696    return ExprResult(true);
697  }
698
699  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
700    if (MD->isInstance())
701      return new PredefinedExpr(ThisLoc, MD->getThisType(Context),
702                                PredefinedExpr::CXXThis);
703
704  return Diag(ThisLoc, diag::err_invalid_this_use);
705}
706
707/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
708/// Can be interpreted either as function-style casting ("int(x)")
709/// or class type construction ("ClassType(x,y,z)")
710/// or creation of a value-initialized type ("int()").
711Action::ExprResult
712Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
713                                SourceLocation LParenLoc,
714                                ExprTy **ExprTys, unsigned NumExprs,
715                                SourceLocation *CommaLocs,
716                                SourceLocation RParenLoc) {
717  assert(TypeRep && "Missing type!");
718  QualType Ty = QualType::getFromOpaquePtr(TypeRep);
719  Expr **Exprs = (Expr**)ExprTys;
720  SourceLocation TyBeginLoc = TypeRange.getBegin();
721  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
722
723  if (const RecordType *RT = Ty->getAsRecordType()) {
724    // C++ 5.2.3p1:
725    // If the simple-type-specifier specifies a class type, the class type shall
726    // be complete.
727    //
728    if (!RT->getDecl()->isDefinition())
729      return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
730                  Ty.getAsString(), FullRange);
731
732    unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
733                                    "class constructors are not supported yet");
734    return Diag(TyBeginLoc, DiagID);
735  }
736
737  // C++ 5.2.3p1:
738  // If the expression list is a single expression, the type conversion
739  // expression is equivalent (in definedness, and if defined in meaning) to the
740  // corresponding cast expression.
741  //
742  if (NumExprs == 1) {
743    if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
744      return true;
745    return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
746                                     Exprs[0], RParenLoc);
747  }
748
749  // C++ 5.2.3p1:
750  // If the expression list specifies more than a single value, the type shall
751  // be a class with a suitably declared constructor.
752  //
753  if (NumExprs > 1)
754    return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg,
755                FullRange);
756
757  assert(NumExprs == 0 && "Expected 0 expressions");
758
759  // C++ 5.2.3p2:
760  // The expression T(), where T is a simple-type-specifier for a non-array
761  // complete object type or the (possibly cv-qualified) void type, creates an
762  // rvalue of the specified type, which is value-initialized.
763  //
764  if (Ty->isArrayType())
765    return Diag(TyBeginLoc, diag::err_value_init_for_array_type, FullRange);
766  if (Ty->isIncompleteType() && !Ty->isVoidType())
767    return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
768                Ty.getAsString(), FullRange);
769
770  return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
771}
772
773
774/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
775/// C++ if/switch/while/for statement.
776/// e.g: "if (int x = f()) {...}"
777Action::ExprResult
778Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
779                                       Declarator &D,
780                                       SourceLocation EqualLoc,
781                                       ExprTy *AssignExprVal) {
782  assert(AssignExprVal && "Null assignment expression");
783
784  // C++ 6.4p2:
785  // The declarator shall not specify a function or an array.
786  // The type-specifier-seq shall not contain typedef and shall not declare a
787  // new class or enumeration.
788
789  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
790         "Parser allowed 'typedef' as storage class of condition decl.");
791
792  QualType Ty = GetTypeForDeclarator(D, S);
793
794  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
795    // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
796    // would be created and CXXConditionDeclExpr wants a VarDecl.
797    return Diag(StartLoc, diag::err_invalid_use_of_function_type,
798                SourceRange(StartLoc, EqualLoc));
799  } else if (Ty->isArrayType()) { // ...or an array.
800    Diag(StartLoc, diag::err_invalid_use_of_array_type,
801         SourceRange(StartLoc, EqualLoc));
802  } else if (const RecordType *RT = Ty->getAsRecordType()) {
803    RecordDecl *RD = RT->getDecl();
804    // The type-specifier-seq shall not declare a new class...
805    if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
806      Diag(RD->getLocation(), diag::err_type_defined_in_condition);
807  } else if (const EnumType *ET = Ty->getAsEnumType()) {
808    EnumDecl *ED = ET->getDecl();
809    // ...or enumeration.
810    if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
811      Diag(ED->getLocation(), diag::err_type_defined_in_condition);
812  }
813
814  DeclTy *Dcl = ActOnDeclarator(S, D, 0);
815  if (!Dcl)
816    return true;
817  AddInitializerToDecl(Dcl, AssignExprVal);
818
819  return new CXXConditionDeclExpr(StartLoc, EqualLoc,
820                                       cast<VarDecl>(static_cast<Decl *>(Dcl)));
821}
822
823/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
824bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
825  // C++ 6.4p4:
826  // The value of a condition that is an initialized declaration in a statement
827  // other than a switch statement is the value of the declared variable
828  // implicitly converted to type bool. If that conversion is ill-formed, the
829  // program is ill-formed.
830  // The value of a condition that is an expression is the value of the
831  // expression, implicitly converted to bool.
832  //
833  QualType Ty = CondExpr->getType(); // Save the type.
834  AssignConvertType
835    ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
836  if (ConvTy == Incompatible)
837    return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition,
838                Ty.getAsString(), CondExpr->getSourceRange());
839  return false;
840}
841
842/// Helper function to determine whether this is the (deprecated) C++
843/// conversion from a string literal to a pointer to non-const char or
844/// non-const wchar_t (for narrow and wide string literals,
845/// respectively).
846bool
847Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
848  // Look inside the implicit cast, if it exists.
849  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
850    From = Cast->getSubExpr();
851
852  // A string literal (2.13.4) that is not a wide string literal can
853  // be converted to an rvalue of type "pointer to char"; a wide
854  // string literal can be converted to an rvalue of type "pointer
855  // to wchar_t" (C++ 4.2p2).
856  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
857    if (const PointerType *ToPtrType = ToType->getAsPointerType())
858      if (const BuiltinType *ToPointeeType
859          = ToPtrType->getPointeeType()->getAsBuiltinType()) {
860        // This conversion is considered only when there is an
861        // explicit appropriate pointer target type (C++ 4.2p2).
862        if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
863            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
864             (!StrLit->isWide() &&
865              (ToPointeeType->getKind() == BuiltinType::Char_U ||
866               ToPointeeType->getKind() == BuiltinType::Char_S))))
867          return true;
868      }
869
870  return false;
871}
872
873/// PerformImplicitConversion - Perform an implicit conversion of the
874/// expression From to the type ToType. Returns true if there was an
875/// error, false otherwise. The expression From is replaced with the
876/// converted expression.
877bool
878Sema::PerformImplicitConversion(Expr *&From, QualType ToType)
879{
880  ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType);
881  switch (ICS.ConversionKind) {
882  case ImplicitConversionSequence::StandardConversion:
883    if (PerformImplicitConversion(From, ToType, ICS.Standard))
884      return true;
885    break;
886
887  case ImplicitConversionSequence::UserDefinedConversion:
888    // FIXME: This is, of course, wrong. We'll need to actually call
889    // the constructor or conversion operator, and then cope with the
890    // standard conversions.
891    ImpCastExprToType(From, ToType);
892    return false;
893
894  case ImplicitConversionSequence::EllipsisConversion:
895    assert(false && "Cannot perform an ellipsis conversion");
896    return false;
897
898  case ImplicitConversionSequence::BadConversion:
899    return true;
900  }
901
902  // Everything went well.
903  return false;
904}
905
906/// PerformImplicitConversion - Perform an implicit conversion of the
907/// expression From to the type ToType by following the standard
908/// conversion sequence SCS. Returns true if there was an error, false
909/// otherwise. The expression From is replaced with the converted
910/// expression.
911bool
912Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
913                                const StandardConversionSequence& SCS)
914{
915  // Overall FIXME: we are recomputing too many types here and doing
916  // far too much extra work. What this means is that we need to keep
917  // track of more information that is computed when we try the
918  // implicit conversion initially, so that we don't need to recompute
919  // anything here.
920  QualType FromType = From->getType();
921
922  // Perform the first implicit conversion.
923  switch (SCS.First) {
924  case ICK_Identity:
925  case ICK_Lvalue_To_Rvalue:
926    // Nothing to do.
927    break;
928
929  case ICK_Array_To_Pointer:
930    FromType = Context.getArrayDecayedType(FromType);
931    ImpCastExprToType(From, FromType);
932    break;
933
934  case ICK_Function_To_Pointer:
935    FromType = Context.getPointerType(FromType);
936    ImpCastExprToType(From, FromType);
937    break;
938
939  default:
940    assert(false && "Improper first standard conversion");
941    break;
942  }
943
944  // Perform the second implicit conversion
945  switch (SCS.Second) {
946  case ICK_Identity:
947    // Nothing to do.
948    break;
949
950  case ICK_Integral_Promotion:
951  case ICK_Floating_Promotion:
952  case ICK_Integral_Conversion:
953  case ICK_Floating_Conversion:
954  case ICK_Floating_Integral:
955    FromType = ToType.getUnqualifiedType();
956    ImpCastExprToType(From, FromType);
957    break;
958
959  case ICK_Pointer_Conversion:
960    if (CheckPointerConversion(From, ToType))
961      return true;
962    ImpCastExprToType(From, ToType);
963    break;
964
965  case ICK_Pointer_Member:
966    // FIXME: Implement pointer-to-member conversions.
967    assert(false && "Pointer-to-member conversions are unsupported");
968    break;
969
970  case ICK_Boolean_Conversion:
971    FromType = Context.BoolTy;
972    ImpCastExprToType(From, FromType);
973    break;
974
975  default:
976    assert(false && "Improper second standard conversion");
977    break;
978  }
979
980  switch (SCS.Third) {
981  case ICK_Identity:
982    // Nothing to do.
983    break;
984
985  case ICK_Qualification:
986    ImpCastExprToType(From, ToType);
987    break;
988
989  default:
990    assert(false && "Improper second standard conversion");
991    break;
992  }
993
994  return false;
995}
996
997