SemaExprCXX.cpp revision aaf147be3cc7403d8f7889d363421bb291ef23f2
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 "clang/Sema/SemaInternal.h"
15#include "clang/Sema/DeclSpec.h"
16#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
18#include "clang/Sema/ParsedTemplate.h"
19#include "clang/Sema/ScopeInfo.h"
20#include "clang/Sema/TemplateDeduction.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/CXXInheritance.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/Preprocessor.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/Support/ErrorHandling.h"
32using namespace clang;
33using namespace sema;
34
35ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
36                                   IdentifierInfo &II,
37                                   SourceLocation NameLoc,
38                                   Scope *S, CXXScopeSpec &SS,
39                                   ParsedType ObjectTypePtr,
40                                   bool EnteringContext) {
41  // Determine where to perform name lookup.
42
43  // FIXME: This area of the standard is very messy, and the current
44  // wording is rather unclear about which scopes we search for the
45  // destructor name; see core issues 399 and 555. Issue 399 in
46  // particular shows where the current description of destructor name
47  // lookup is completely out of line with existing practice, e.g.,
48  // this appears to be ill-formed:
49  //
50  //   namespace N {
51  //     template <typename T> struct S {
52  //       ~S();
53  //     };
54  //   }
55  //
56  //   void f(N::S<int>* s) {
57  //     s->N::S<int>::~S();
58  //   }
59  //
60  // See also PR6358 and PR6359.
61  // For this reason, we're currently only doing the C++03 version of this
62  // code; the C++0x version has to wait until we get a proper spec.
63  QualType SearchType;
64  DeclContext *LookupCtx = 0;
65  bool isDependent = false;
66  bool LookInScope = false;
67
68  // If we have an object type, it's because we are in a
69  // pseudo-destructor-expression or a member access expression, and
70  // we know what type we're looking for.
71  if (ObjectTypePtr)
72    SearchType = GetTypeFromParser(ObjectTypePtr);
73
74  if (SS.isSet()) {
75    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
76
77    bool AlreadySearched = false;
78    bool LookAtPrefix = true;
79    // C++ [basic.lookup.qual]p6:
80    //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
81    //   the type-names are looked up as types in the scope designated by the
82    //   nested-name-specifier. In a qualified-id of the form:
83    //
84    //     ::[opt] nested-name-specifier  ~ class-name
85    //
86    //   where the nested-name-specifier designates a namespace scope, and in
87    //   a qualified-id of the form:
88    //
89    //     ::opt nested-name-specifier class-name ::  ~ class-name
90    //
91    //   the class-names are looked up as types in the scope designated by
92    //   the nested-name-specifier.
93    //
94    // Here, we check the first case (completely) and determine whether the
95    // code below is permitted to look at the prefix of the
96    // nested-name-specifier.
97    DeclContext *DC = computeDeclContext(SS, EnteringContext);
98    if (DC && DC->isFileContext()) {
99      AlreadySearched = true;
100      LookupCtx = DC;
101      isDependent = false;
102    } else if (DC && isa<CXXRecordDecl>(DC))
103      LookAtPrefix = false;
104
105    // The second case from the C++03 rules quoted further above.
106    NestedNameSpecifier *Prefix = 0;
107    if (AlreadySearched) {
108      // Nothing left to do.
109    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
110      CXXScopeSpec PrefixSS;
111      PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
112      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
113      isDependent = isDependentScopeSpecifier(PrefixSS);
114    } else if (ObjectTypePtr) {
115      LookupCtx = computeDeclContext(SearchType);
116      isDependent = SearchType->isDependentType();
117    } else {
118      LookupCtx = computeDeclContext(SS, EnteringContext);
119      isDependent = LookupCtx && LookupCtx->isDependentContext();
120    }
121
122    LookInScope = false;
123  } else if (ObjectTypePtr) {
124    // C++ [basic.lookup.classref]p3:
125    //   If the unqualified-id is ~type-name, the type-name is looked up
126    //   in the context of the entire postfix-expression. If the type T
127    //   of the object expression is of a class type C, the type-name is
128    //   also looked up in the scope of class C. At least one of the
129    //   lookups shall find a name that refers to (possibly
130    //   cv-qualified) T.
131    LookupCtx = computeDeclContext(SearchType);
132    isDependent = SearchType->isDependentType();
133    assert((isDependent || !SearchType->isIncompleteType()) &&
134           "Caller should have completed object type");
135
136    LookInScope = true;
137  } else {
138    // Perform lookup into the current scope (only).
139    LookInScope = true;
140  }
141
142  TypeDecl *NonMatchingTypeDecl = 0;
143  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
144  for (unsigned Step = 0; Step != 2; ++Step) {
145    // Look for the name first in the computed lookup context (if we
146    // have one) and, if that fails to find a match, in the scope (if
147    // we're allowed to look there).
148    Found.clear();
149    if (Step == 0 && LookupCtx)
150      LookupQualifiedName(Found, LookupCtx);
151    else if (Step == 1 && LookInScope && S)
152      LookupName(Found, S);
153    else
154      continue;
155
156    // FIXME: Should we be suppressing ambiguities here?
157    if (Found.isAmbiguous())
158      return ParsedType();
159
160    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
161      QualType T = Context.getTypeDeclType(Type);
162
163      if (SearchType.isNull() || SearchType->isDependentType() ||
164          Context.hasSameUnqualifiedType(T, SearchType)) {
165        // We found our type!
166
167        return ParsedType::make(T);
168      }
169
170      if (!SearchType.isNull())
171        NonMatchingTypeDecl = Type;
172    }
173
174    // If the name that we found is a class template name, and it is
175    // the same name as the template name in the last part of the
176    // nested-name-specifier (if present) or the object type, then
177    // this is the destructor for that class.
178    // FIXME: This is a workaround until we get real drafting for core
179    // issue 399, for which there isn't even an obvious direction.
180    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
181      QualType MemberOfType;
182      if (SS.isSet()) {
183        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
184          // Figure out the type of the context, if it has one.
185          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
186            MemberOfType = Context.getTypeDeclType(Record);
187        }
188      }
189      if (MemberOfType.isNull())
190        MemberOfType = SearchType;
191
192      if (MemberOfType.isNull())
193        continue;
194
195      // We're referring into a class template specialization. If the
196      // class template we found is the same as the template being
197      // specialized, we found what we are looking for.
198      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
199        if (ClassTemplateSpecializationDecl *Spec
200              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
201          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
202                Template->getCanonicalDecl())
203            return ParsedType::make(MemberOfType);
204        }
205
206        continue;
207      }
208
209      // We're referring to an unresolved class template
210      // specialization. Determine whether we class template we found
211      // is the same as the template being specialized or, if we don't
212      // know which template is being specialized, that it at least
213      // has the same name.
214      if (const TemplateSpecializationType *SpecType
215            = MemberOfType->getAs<TemplateSpecializationType>()) {
216        TemplateName SpecName = SpecType->getTemplateName();
217
218        // The class template we found is the same template being
219        // specialized.
220        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
221          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
222            return ParsedType::make(MemberOfType);
223
224          continue;
225        }
226
227        // The class template we found has the same name as the
228        // (dependent) template name being specialized.
229        if (DependentTemplateName *DepTemplate
230                                    = SpecName.getAsDependentTemplateName()) {
231          if (DepTemplate->isIdentifier() &&
232              DepTemplate->getIdentifier() == Template->getIdentifier())
233            return ParsedType::make(MemberOfType);
234
235          continue;
236        }
237      }
238    }
239  }
240
241  if (isDependent) {
242    // We didn't find our type, but that's okay: it's dependent
243    // anyway.
244
245    // FIXME: What if we have no nested-name-specifier?
246    QualType T = CheckTypenameType(ETK_None, SourceLocation(),
247                                   SS.getWithLocInContext(Context),
248                                   II, NameLoc);
249    return ParsedType::make(T);
250  }
251
252  if (NonMatchingTypeDecl) {
253    QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
254    Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
255      << T << SearchType;
256    Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
257      << T;
258  } else if (ObjectTypePtr)
259    Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
260      << &II;
261  else
262    Diag(NameLoc, diag::err_destructor_class_name);
263
264  return ParsedType();
265}
266
267/// \brief Build a C++ typeid expression with a type operand.
268ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
269                                SourceLocation TypeidLoc,
270                                TypeSourceInfo *Operand,
271                                SourceLocation RParenLoc) {
272  // C++ [expr.typeid]p4:
273  //   The top-level cv-qualifiers of the lvalue expression or the type-id
274  //   that is the operand of typeid are always ignored.
275  //   If the type of the type-id is a class type or a reference to a class
276  //   type, the class shall be completely-defined.
277  Qualifiers Quals;
278  QualType T
279    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
280                                      Quals);
281  if (T->getAs<RecordType>() &&
282      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
283    return ExprError();
284
285  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
286                                           Operand,
287                                           SourceRange(TypeidLoc, RParenLoc)));
288}
289
290/// \brief Build a C++ typeid expression with an expression operand.
291ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
292                                SourceLocation TypeidLoc,
293                                Expr *E,
294                                SourceLocation RParenLoc) {
295  bool isUnevaluatedOperand = true;
296  if (E && !E->isTypeDependent()) {
297    QualType T = E->getType();
298    if (const RecordType *RecordT = T->getAs<RecordType>()) {
299      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
300      // C++ [expr.typeid]p3:
301      //   [...] If the type of the expression is a class type, the class
302      //   shall be completely-defined.
303      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
304        return ExprError();
305
306      // C++ [expr.typeid]p3:
307      //   When typeid is applied to an expression other than an glvalue of a
308      //   polymorphic class type [...] [the] expression is an unevaluated
309      //   operand. [...]
310      if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
311        isUnevaluatedOperand = false;
312
313        // We require a vtable to query the type at run time.
314        MarkVTableUsed(TypeidLoc, RecordD);
315      }
316    }
317
318    // C++ [expr.typeid]p4:
319    //   [...] If the type of the type-id is a reference to a possibly
320    //   cv-qualified type, the result of the typeid expression refers to a
321    //   std::type_info object representing the cv-unqualified referenced
322    //   type.
323    Qualifiers Quals;
324    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
325    if (!Context.hasSameType(T, UnqualT)) {
326      T = UnqualT;
327      E = ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)).take();
328    }
329  }
330
331  // If this is an unevaluated operand, clear out the set of
332  // declaration references we have been computing and eliminate any
333  // temporaries introduced in its computation.
334  if (isUnevaluatedOperand)
335    ExprEvalContexts.back().Context = Unevaluated;
336
337  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
338                                           E,
339                                           SourceRange(TypeidLoc, RParenLoc)));
340}
341
342/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
343ExprResult
344Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
345                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
346  // Find the std::type_info type.
347  if (!getStdNamespace())
348    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
349
350  if (!CXXTypeInfoDecl) {
351    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
352    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
353    LookupQualifiedName(R, getStdNamespace());
354    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
355    if (!CXXTypeInfoDecl)
356      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
357  }
358
359  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
360
361  if (isType) {
362    // The operand is a type; handle it as such.
363    TypeSourceInfo *TInfo = 0;
364    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
365                                   &TInfo);
366    if (T.isNull())
367      return ExprError();
368
369    if (!TInfo)
370      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
371
372    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
373  }
374
375  // The operand is an expression.
376  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
377}
378
379/// Retrieve the UuidAttr associated with QT.
380static UuidAttr *GetUuidAttrOfType(QualType QT) {
381  // Optionally remove one level of pointer, reference or array indirection.
382  const Type *Ty = QT.getTypePtr();;
383  if (QT->isPointerType() || QT->isReferenceType())
384    Ty = QT->getPointeeType().getTypePtr();
385  else if (QT->isArrayType())
386    Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
387
388  // Loop all class definition and declaration looking for an uuid attribute.
389  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
390  while (RD) {
391    if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
392      return Uuid;
393    RD = RD->getPreviousDeclaration();
394  }
395  return 0;
396}
397
398/// \brief Build a Microsoft __uuidof expression with a type operand.
399ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
400                                SourceLocation TypeidLoc,
401                                TypeSourceInfo *Operand,
402                                SourceLocation RParenLoc) {
403  if (!Operand->getType()->isDependentType()) {
404    if (!GetUuidAttrOfType(Operand->getType()))
405      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
406  }
407
408  // FIXME: add __uuidof semantic analysis for type operand.
409  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
410                                           Operand,
411                                           SourceRange(TypeidLoc, RParenLoc)));
412}
413
414/// \brief Build a Microsoft __uuidof expression with an expression operand.
415ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
416                                SourceLocation TypeidLoc,
417                                Expr *E,
418                                SourceLocation RParenLoc) {
419  if (!E->getType()->isDependentType()) {
420    if (!GetUuidAttrOfType(E->getType()) &&
421        !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
422      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
423  }
424  // FIXME: add __uuidof semantic analysis for type operand.
425  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
426                                           E,
427                                           SourceRange(TypeidLoc, RParenLoc)));
428}
429
430/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
431ExprResult
432Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
433                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
434  // If MSVCGuidDecl has not been cached, do the lookup.
435  if (!MSVCGuidDecl) {
436    IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
437    LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
438    LookupQualifiedName(R, Context.getTranslationUnitDecl());
439    MSVCGuidDecl = R.getAsSingle<RecordDecl>();
440    if (!MSVCGuidDecl)
441      return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
442  }
443
444  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
445
446  if (isType) {
447    // The operand is a type; handle it as such.
448    TypeSourceInfo *TInfo = 0;
449    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
450                                   &TInfo);
451    if (T.isNull())
452      return ExprError();
453
454    if (!TInfo)
455      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
456
457    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
458  }
459
460  // The operand is an expression.
461  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
462}
463
464/// ActOnCXXBoolLiteral - Parse {true,false} literals.
465ExprResult
466Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
467  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
468         "Unknown C++ Boolean value!");
469  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
470                                                Context.BoolTy, OpLoc));
471}
472
473/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
474ExprResult
475Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
476  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
477}
478
479/// ActOnCXXThrow - Parse throw expressions.
480ExprResult
481Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
482  // Don't report an error if 'throw' is used in system headers.
483  if (!getLangOptions().CXXExceptions &&
484      !getSourceManager().isInSystemHeader(OpLoc))
485    Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
486
487  if (Ex && !Ex->isTypeDependent()) {
488    ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex);
489    if (ExRes.isInvalid())
490      return ExprError();
491    Ex = ExRes.take();
492  }
493  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
494}
495
496/// CheckCXXThrowOperand - Validate the operand of a throw.
497ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E) {
498  // C++ [except.throw]p3:
499  //   A throw-expression initializes a temporary object, called the exception
500  //   object, the type of which is determined by removing any top-level
501  //   cv-qualifiers from the static type of the operand of throw and adjusting
502  //   the type from "array of T" or "function returning T" to "pointer to T"
503  //   or "pointer to function returning T", [...]
504  if (E->getType().hasQualifiers())
505    E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
506                      CastCategory(E)).take();
507
508  ExprResult Res = DefaultFunctionArrayConversion(E);
509  if (Res.isInvalid())
510    return ExprError();
511  E = Res.take();
512
513  //   If the type of the exception would be an incomplete type or a pointer
514  //   to an incomplete type other than (cv) void the program is ill-formed.
515  QualType Ty = E->getType();
516  bool isPointer = false;
517  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
518    Ty = Ptr->getPointeeType();
519    isPointer = true;
520  }
521  if (!isPointer || !Ty->isVoidType()) {
522    if (RequireCompleteType(ThrowLoc, Ty,
523                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
524                                            : diag::err_throw_incomplete)
525                              << E->getSourceRange()))
526      return ExprError();
527
528    if (RequireNonAbstractType(ThrowLoc, E->getType(),
529                               PDiag(diag::err_throw_abstract_type)
530                                 << E->getSourceRange()))
531      return ExprError();
532  }
533
534  // Initialize the exception result.  This implicitly weeds out
535  // abstract types or types with inaccessible copy constructors.
536  const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
537
538  // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
539  InitializedEntity Entity =
540      InitializedEntity::InitializeException(ThrowLoc, E->getType(),
541                                             /*NRVO=*/false);
542  Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
543                                        QualType(), E);
544  if (Res.isInvalid())
545    return ExprError();
546  E = Res.take();
547
548  // If the exception has class type, we need additional handling.
549  const RecordType *RecordTy = Ty->getAs<RecordType>();
550  if (!RecordTy)
551    return Owned(E);
552  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
553
554  // If we are throwing a polymorphic class type or pointer thereof,
555  // exception handling will make use of the vtable.
556  MarkVTableUsed(ThrowLoc, RD);
557
558  // If a pointer is thrown, the referenced object will not be destroyed.
559  if (isPointer)
560    return Owned(E);
561
562  // If the class has a non-trivial destructor, we must be able to call it.
563  if (RD->hasTrivialDestructor())
564    return Owned(E);
565
566  CXXDestructorDecl *Destructor
567    = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
568  if (!Destructor)
569    return Owned(E);
570
571  MarkDeclarationReferenced(E->getExprLoc(), Destructor);
572  CheckDestructorAccess(E->getExprLoc(), Destructor,
573                        PDiag(diag::err_access_dtor_exception) << Ty);
574  return Owned(E);
575}
576
577CXXMethodDecl *Sema::tryCaptureCXXThis() {
578  // Ignore block scopes: we can capture through them.
579  // Ignore nested enum scopes: we'll diagnose non-constant expressions
580  // where they're invalid, and other uses are legitimate.
581  // Don't ignore nested class scopes: you can't use 'this' in a local class.
582  DeclContext *DC = CurContext;
583  while (true) {
584    if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
585    else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
586    else break;
587  }
588
589  // If we're not in an instance method, error out.
590  CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
591  if (!method || !method->isInstance())
592    return 0;
593
594  // Mark that we're closing on 'this' in all the block scopes, if applicable.
595  for (unsigned idx = FunctionScopes.size() - 1;
596       isa<BlockScopeInfo>(FunctionScopes[idx]);
597       --idx)
598    cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
599
600  return method;
601}
602
603ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
604  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
605  /// is a non-lvalue expression whose value is the address of the object for
606  /// which the function is called.
607
608  CXXMethodDecl *method = tryCaptureCXXThis();
609  if (!method) return Diag(loc, diag::err_invalid_this_use);
610
611  return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
612                                         /*isImplicit=*/false));
613}
614
615ExprResult
616Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
617                                SourceLocation LParenLoc,
618                                MultiExprArg exprs,
619                                SourceLocation RParenLoc) {
620  if (!TypeRep)
621    return ExprError();
622
623  TypeSourceInfo *TInfo;
624  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
625  if (!TInfo)
626    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
627
628  return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
629}
630
631/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
632/// Can be interpreted either as function-style casting ("int(x)")
633/// or class type construction ("ClassType(x,y,z)")
634/// or creation of a value-initialized type ("int()").
635ExprResult
636Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
637                                SourceLocation LParenLoc,
638                                MultiExprArg exprs,
639                                SourceLocation RParenLoc) {
640  QualType Ty = TInfo->getType();
641  unsigned NumExprs = exprs.size();
642  Expr **Exprs = (Expr**)exprs.get();
643  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
644  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
645
646  if (Ty->isDependentType() ||
647      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
648    exprs.release();
649
650    return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
651                                                    LParenLoc,
652                                                    Exprs, NumExprs,
653                                                    RParenLoc));
654  }
655
656  if (Ty->isArrayType())
657    return ExprError(Diag(TyBeginLoc,
658                          diag::err_value_init_for_array_type) << FullRange);
659  if (!Ty->isVoidType() &&
660      RequireCompleteType(TyBeginLoc, Ty,
661                          PDiag(diag::err_invalid_incomplete_type_use)
662                            << FullRange))
663    return ExprError();
664
665  if (RequireNonAbstractType(TyBeginLoc, Ty,
666                             diag::err_allocation_of_abstract_type))
667    return ExprError();
668
669
670  // C++ [expr.type.conv]p1:
671  // If the expression list is a single expression, the type conversion
672  // expression is equivalent (in definedness, and if defined in meaning) to the
673  // corresponding cast expression.
674  //
675  if (NumExprs == 1) {
676    CastKind Kind = CK_Invalid;
677    ExprValueKind VK = VK_RValue;
678    CXXCastPath BasePath;
679    ExprResult CastExpr =
680      CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
681                     Kind, VK, BasePath,
682                     /*FunctionalStyle=*/true);
683    if (CastExpr.isInvalid())
684      return ExprError();
685    Exprs[0] = CastExpr.take();
686
687    exprs.release();
688
689    return Owned(CXXFunctionalCastExpr::Create(Context,
690                                               Ty.getNonLValueExprType(Context),
691                                               VK, TInfo, TyBeginLoc, Kind,
692                                               Exprs[0], &BasePath,
693                                               RParenLoc));
694  }
695
696  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
697  InitializationKind Kind
698    = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
699                                                  LParenLoc, RParenLoc)
700               : InitializationKind::CreateValue(TyBeginLoc,
701                                                 LParenLoc, RParenLoc);
702  InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
703  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
704
705  // FIXME: Improve AST representation?
706  return move(Result);
707}
708
709/// doesUsualArrayDeleteWantSize - Answers whether the usual
710/// operator delete[] for the given type has a size_t parameter.
711static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
712                                         QualType allocType) {
713  const RecordType *record =
714    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
715  if (!record) return false;
716
717  // Try to find an operator delete[] in class scope.
718
719  DeclarationName deleteName =
720    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
721  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
722  S.LookupQualifiedName(ops, record->getDecl());
723
724  // We're just doing this for information.
725  ops.suppressDiagnostics();
726
727  // Very likely: there's no operator delete[].
728  if (ops.empty()) return false;
729
730  // If it's ambiguous, it should be illegal to call operator delete[]
731  // on this thing, so it doesn't matter if we allocate extra space or not.
732  if (ops.isAmbiguous()) return false;
733
734  LookupResult::Filter filter = ops.makeFilter();
735  while (filter.hasNext()) {
736    NamedDecl *del = filter.next()->getUnderlyingDecl();
737
738    // C++0x [basic.stc.dynamic.deallocation]p2:
739    //   A template instance is never a usual deallocation function,
740    //   regardless of its signature.
741    if (isa<FunctionTemplateDecl>(del)) {
742      filter.erase();
743      continue;
744    }
745
746    // C++0x [basic.stc.dynamic.deallocation]p2:
747    //   If class T does not declare [an operator delete[] with one
748    //   parameter] but does declare a member deallocation function
749    //   named operator delete[] with exactly two parameters, the
750    //   second of which has type std::size_t, then this function
751    //   is a usual deallocation function.
752    if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
753      filter.erase();
754      continue;
755    }
756  }
757  filter.done();
758
759  if (!ops.isSingleResult()) return false;
760
761  const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
762  return (del->getNumParams() == 2);
763}
764
765/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
766/// @code new (memory) int[size][4] @endcode
767/// or
768/// @code ::new Foo(23, "hello") @endcode
769/// For the interpretation of this heap of arguments, consult the base version.
770ExprResult
771Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
772                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
773                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
774                  Declarator &D, SourceLocation ConstructorLParen,
775                  MultiExprArg ConstructorArgs,
776                  SourceLocation ConstructorRParen) {
777  bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
778
779  Expr *ArraySize = 0;
780  // If the specified type is an array, unwrap it and save the expression.
781  if (D.getNumTypeObjects() > 0 &&
782      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
783    DeclaratorChunk &Chunk = D.getTypeObject(0);
784    if (TypeContainsAuto)
785      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
786        << D.getSourceRange());
787    if (Chunk.Arr.hasStatic)
788      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
789        << D.getSourceRange());
790    if (!Chunk.Arr.NumElts)
791      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
792        << D.getSourceRange());
793
794    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
795    D.DropFirstTypeObject();
796  }
797
798  // Every dimension shall be of constant size.
799  if (ArraySize) {
800    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
801      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
802        break;
803
804      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
805      if (Expr *NumElts = (Expr *)Array.NumElts) {
806        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
807            !NumElts->isIntegerConstantExpr(Context)) {
808          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
809            << NumElts->getSourceRange();
810          return ExprError();
811        }
812      }
813    }
814  }
815
816  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
817                                               /*AllowAuto=*/true);
818  QualType AllocType = TInfo->getType();
819  if (D.isInvalidType())
820    return ExprError();
821
822  return BuildCXXNew(StartLoc, UseGlobal,
823                     PlacementLParen,
824                     move(PlacementArgs),
825                     PlacementRParen,
826                     TypeIdParens,
827                     AllocType,
828                     TInfo,
829                     ArraySize,
830                     ConstructorLParen,
831                     move(ConstructorArgs),
832                     ConstructorRParen,
833                     TypeContainsAuto);
834}
835
836ExprResult
837Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
838                  SourceLocation PlacementLParen,
839                  MultiExprArg PlacementArgs,
840                  SourceLocation PlacementRParen,
841                  SourceRange TypeIdParens,
842                  QualType AllocType,
843                  TypeSourceInfo *AllocTypeInfo,
844                  Expr *ArraySize,
845                  SourceLocation ConstructorLParen,
846                  MultiExprArg ConstructorArgs,
847                  SourceLocation ConstructorRParen,
848                  bool TypeMayContainAuto) {
849  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
850
851  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
852  if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
853    if (ConstructorArgs.size() == 0)
854      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
855                       << AllocType << TypeRange);
856    if (ConstructorArgs.size() != 1) {
857      Expr *FirstBad = ConstructorArgs.get()[1];
858      return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
859                            diag::err_auto_new_ctor_multiple_expressions)
860                       << AllocType << TypeRange);
861    }
862    TypeSourceInfo *DeducedType = 0;
863    if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
864      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
865                       << AllocType
866                       << ConstructorArgs.get()[0]->getType()
867                       << TypeRange
868                       << ConstructorArgs.get()[0]->getSourceRange());
869    if (!DeducedType)
870      return ExprError();
871
872    AllocTypeInfo = DeducedType;
873    AllocType = AllocTypeInfo->getType();
874  }
875
876  // Per C++0x [expr.new]p5, the type being constructed may be a
877  // typedef of an array type.
878  if (!ArraySize) {
879    if (const ConstantArrayType *Array
880                              = Context.getAsConstantArrayType(AllocType)) {
881      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
882                                         Context.getSizeType(),
883                                         TypeRange.getEnd());
884      AllocType = Array->getElementType();
885    }
886  }
887
888  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
889    return ExprError();
890
891  QualType ResultType = Context.getPointerType(AllocType);
892
893  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
894  //   or enumeration type with a non-negative value."
895  if (ArraySize && !ArraySize->isTypeDependent()) {
896
897    QualType SizeType = ArraySize->getType();
898
899    ExprResult ConvertedSize
900      = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
901                                       PDiag(diag::err_array_size_not_integral),
902                                     PDiag(diag::err_array_size_incomplete_type)
903                                       << ArraySize->getSourceRange(),
904                               PDiag(diag::err_array_size_explicit_conversion),
905                                       PDiag(diag::note_array_size_conversion),
906                               PDiag(diag::err_array_size_ambiguous_conversion),
907                                       PDiag(diag::note_array_size_conversion),
908                          PDiag(getLangOptions().CPlusPlus0x? 0
909                                            : diag::ext_array_size_conversion));
910    if (ConvertedSize.isInvalid())
911      return ExprError();
912
913    ArraySize = ConvertedSize.take();
914    SizeType = ArraySize->getType();
915    if (!SizeType->isIntegralOrUnscopedEnumerationType())
916      return ExprError();
917
918    // Let's see if this is a constant < 0. If so, we reject it out of hand.
919    // We don't care about special rules, so we tell the machinery it's not
920    // evaluated - it gives us a result in more cases.
921    if (!ArraySize->isValueDependent()) {
922      llvm::APSInt Value;
923      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
924        if (Value < llvm::APSInt(
925                        llvm::APInt::getNullValue(Value.getBitWidth()),
926                                 Value.isUnsigned()))
927          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
928                                diag::err_typecheck_negative_array_size)
929            << ArraySize->getSourceRange());
930
931        if (!AllocType->isDependentType()) {
932          unsigned ActiveSizeBits
933            = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
934          if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
935            Diag(ArraySize->getSourceRange().getBegin(),
936                 diag::err_array_too_large)
937              << Value.toString(10)
938              << ArraySize->getSourceRange();
939            return ExprError();
940          }
941        }
942      } else if (TypeIdParens.isValid()) {
943        // Can't have dynamic array size when the type-id is in parentheses.
944        Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
945          << ArraySize->getSourceRange()
946          << FixItHint::CreateRemoval(TypeIdParens.getBegin())
947          << FixItHint::CreateRemoval(TypeIdParens.getEnd());
948
949        TypeIdParens = SourceRange();
950      }
951    }
952
953    ArraySize = ImpCastExprToType(ArraySize, Context.getSizeType(),
954                      CK_IntegralCast).take();
955  }
956
957  FunctionDecl *OperatorNew = 0;
958  FunctionDecl *OperatorDelete = 0;
959  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
960  unsigned NumPlaceArgs = PlacementArgs.size();
961
962  if (!AllocType->isDependentType() &&
963      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
964      FindAllocationFunctions(StartLoc,
965                              SourceRange(PlacementLParen, PlacementRParen),
966                              UseGlobal, AllocType, ArraySize, PlaceArgs,
967                              NumPlaceArgs, OperatorNew, OperatorDelete))
968    return ExprError();
969
970  // If this is an array allocation, compute whether the usual array
971  // deallocation function for the type has a size_t parameter.
972  bool UsualArrayDeleteWantsSize = false;
973  if (ArraySize && !AllocType->isDependentType())
974    UsualArrayDeleteWantsSize
975      = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
976
977  llvm::SmallVector<Expr *, 8> AllPlaceArgs;
978  if (OperatorNew) {
979    // Add default arguments, if any.
980    const FunctionProtoType *Proto =
981      OperatorNew->getType()->getAs<FunctionProtoType>();
982    VariadicCallType CallType =
983      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
984
985    if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
986                               Proto, 1, PlaceArgs, NumPlaceArgs,
987                               AllPlaceArgs, CallType))
988      return ExprError();
989
990    NumPlaceArgs = AllPlaceArgs.size();
991    if (NumPlaceArgs > 0)
992      PlaceArgs = &AllPlaceArgs[0];
993  }
994
995  bool Init = ConstructorLParen.isValid();
996  // --- Choosing a constructor ---
997  CXXConstructorDecl *Constructor = 0;
998  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
999  unsigned NumConsArgs = ConstructorArgs.size();
1000  ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
1001
1002  // Array 'new' can't have any initializers.
1003  if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
1004    SourceRange InitRange(ConsArgs[0]->getLocStart(),
1005                          ConsArgs[NumConsArgs - 1]->getLocEnd());
1006
1007    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1008    return ExprError();
1009  }
1010
1011  if (!AllocType->isDependentType() &&
1012      !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1013    // C++0x [expr.new]p15:
1014    //   A new-expression that creates an object of type T initializes that
1015    //   object as follows:
1016    InitializationKind Kind
1017    //     - If the new-initializer is omitted, the object is default-
1018    //       initialized (8.5); if no initialization is performed,
1019    //       the object has indeterminate value
1020      = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
1021    //     - Otherwise, the new-initializer is interpreted according to the
1022    //       initialization rules of 8.5 for direct-initialization.
1023             : InitializationKind::CreateDirect(TypeRange.getBegin(),
1024                                                ConstructorLParen,
1025                                                ConstructorRParen);
1026
1027    InitializedEntity Entity
1028      = InitializedEntity::InitializeNew(StartLoc, AllocType);
1029    InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
1030    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1031                                                move(ConstructorArgs));
1032    if (FullInit.isInvalid())
1033      return ExprError();
1034
1035    // FullInit is our initializer; walk through it to determine if it's a
1036    // constructor call, which CXXNewExpr handles directly.
1037    if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1038      if (CXXBindTemporaryExpr *Binder
1039            = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1040        FullInitExpr = Binder->getSubExpr();
1041      if (CXXConstructExpr *Construct
1042                    = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1043        Constructor = Construct->getConstructor();
1044        for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1045                                         AEnd = Construct->arg_end();
1046             A != AEnd; ++A)
1047          ConvertedConstructorArgs.push_back(*A);
1048      } else {
1049        // Take the converted initializer.
1050        ConvertedConstructorArgs.push_back(FullInit.release());
1051      }
1052    } else {
1053      // No initialization required.
1054    }
1055
1056    // Take the converted arguments and use them for the new expression.
1057    NumConsArgs = ConvertedConstructorArgs.size();
1058    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
1059  }
1060
1061  // Mark the new and delete operators as referenced.
1062  if (OperatorNew)
1063    MarkDeclarationReferenced(StartLoc, OperatorNew);
1064  if (OperatorDelete)
1065    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1066
1067  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
1068
1069  PlacementArgs.release();
1070  ConstructorArgs.release();
1071
1072  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1073                                        PlaceArgs, NumPlaceArgs, TypeIdParens,
1074                                        ArraySize, Constructor, Init,
1075                                        ConsArgs, NumConsArgs, OperatorDelete,
1076                                        UsualArrayDeleteWantsSize,
1077                                        ResultType, AllocTypeInfo,
1078                                        StartLoc,
1079                                        Init ? ConstructorRParen :
1080                                               TypeRange.getEnd(),
1081                                        ConstructorLParen, ConstructorRParen));
1082}
1083
1084/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1085/// in a new-expression.
1086/// dimension off and stores the size expression in ArraySize.
1087bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1088                              SourceRange R) {
1089  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1090  //   abstract class type or array thereof.
1091  if (AllocType->isFunctionType())
1092    return Diag(Loc, diag::err_bad_new_type)
1093      << AllocType << 0 << R;
1094  else if (AllocType->isReferenceType())
1095    return Diag(Loc, diag::err_bad_new_type)
1096      << AllocType << 1 << R;
1097  else if (!AllocType->isDependentType() &&
1098           RequireCompleteType(Loc, AllocType,
1099                               PDiag(diag::err_new_incomplete_type)
1100                                 << R))
1101    return true;
1102  else if (RequireNonAbstractType(Loc, AllocType,
1103                                  diag::err_allocation_of_abstract_type))
1104    return true;
1105  else if (AllocType->isVariablyModifiedType())
1106    return Diag(Loc, diag::err_variably_modified_new_type)
1107             << AllocType;
1108  else if (unsigned AddressSpace = AllocType.getAddressSpace())
1109    return Diag(Loc, diag::err_address_space_qualified_new)
1110      << AllocType.getUnqualifiedType() << AddressSpace;
1111
1112  return false;
1113}
1114
1115/// \brief Determine whether the given function is a non-placement
1116/// deallocation function.
1117static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1118  if (FD->isInvalidDecl())
1119    return false;
1120
1121  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1122    return Method->isUsualDeallocationFunction();
1123
1124  return ((FD->getOverloadedOperator() == OO_Delete ||
1125           FD->getOverloadedOperator() == OO_Array_Delete) &&
1126          FD->getNumParams() == 1);
1127}
1128
1129/// FindAllocationFunctions - Finds the overloads of operator new and delete
1130/// that are appropriate for the allocation.
1131bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1132                                   bool UseGlobal, QualType AllocType,
1133                                   bool IsArray, Expr **PlaceArgs,
1134                                   unsigned NumPlaceArgs,
1135                                   FunctionDecl *&OperatorNew,
1136                                   FunctionDecl *&OperatorDelete) {
1137  // --- Choosing an allocation function ---
1138  // C++ 5.3.4p8 - 14 & 18
1139  // 1) If UseGlobal is true, only look in the global scope. Else, also look
1140  //   in the scope of the allocated class.
1141  // 2) If an array size is given, look for operator new[], else look for
1142  //   operator new.
1143  // 3) The first argument is always size_t. Append the arguments from the
1144  //   placement form.
1145
1146  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1147  // We don't care about the actual value of this argument.
1148  // FIXME: Should the Sema create the expression and embed it in the syntax
1149  // tree? Or should the consumer just recalculate the value?
1150  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1151                      Context.Target.getPointerWidth(0)),
1152                      Context.getSizeType(),
1153                      SourceLocation());
1154  AllocArgs[0] = &Size;
1155  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1156
1157  // C++ [expr.new]p8:
1158  //   If the allocated type is a non-array type, the allocation
1159  //   function's name is operator new and the deallocation function's
1160  //   name is operator delete. If the allocated type is an array
1161  //   type, the allocation function's name is operator new[] and the
1162  //   deallocation function's name is operator delete[].
1163  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1164                                        IsArray ? OO_Array_New : OO_New);
1165  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1166                                        IsArray ? OO_Array_Delete : OO_Delete);
1167
1168  QualType AllocElemType = Context.getBaseElementType(AllocType);
1169
1170  if (AllocElemType->isRecordType() && !UseGlobal) {
1171    CXXRecordDecl *Record
1172      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1173    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1174                          AllocArgs.size(), Record, /*AllowMissing=*/true,
1175                          OperatorNew))
1176      return true;
1177  }
1178  if (!OperatorNew) {
1179    // Didn't find a member overload. Look for a global one.
1180    DeclareGlobalNewDelete();
1181    DeclContext *TUDecl = Context.getTranslationUnitDecl();
1182    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1183                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1184                          OperatorNew))
1185      return true;
1186  }
1187
1188  // We don't need an operator delete if we're running under
1189  // -fno-exceptions.
1190  if (!getLangOptions().Exceptions) {
1191    OperatorDelete = 0;
1192    return false;
1193  }
1194
1195  // FindAllocationOverload can change the passed in arguments, so we need to
1196  // copy them back.
1197  if (NumPlaceArgs > 0)
1198    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
1199
1200  // C++ [expr.new]p19:
1201  //
1202  //   If the new-expression begins with a unary :: operator, the
1203  //   deallocation function's name is looked up in the global
1204  //   scope. Otherwise, if the allocated type is a class type T or an
1205  //   array thereof, the deallocation function's name is looked up in
1206  //   the scope of T. If this lookup fails to find the name, or if
1207  //   the allocated type is not a class type or array thereof, the
1208  //   deallocation function's name is looked up in the global scope.
1209  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1210  if (AllocElemType->isRecordType() && !UseGlobal) {
1211    CXXRecordDecl *RD
1212      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1213    LookupQualifiedName(FoundDelete, RD);
1214  }
1215  if (FoundDelete.isAmbiguous())
1216    return true; // FIXME: clean up expressions?
1217
1218  if (FoundDelete.empty()) {
1219    DeclareGlobalNewDelete();
1220    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1221  }
1222
1223  FoundDelete.suppressDiagnostics();
1224
1225  llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1226
1227  // Whether we're looking for a placement operator delete is dictated
1228  // by whether we selected a placement operator new, not by whether
1229  // we had explicit placement arguments.  This matters for things like
1230  //   struct A { void *operator new(size_t, int = 0); ... };
1231  //   A *a = new A()
1232  bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1233
1234  if (isPlacementNew) {
1235    // C++ [expr.new]p20:
1236    //   A declaration of a placement deallocation function matches the
1237    //   declaration of a placement allocation function if it has the
1238    //   same number of parameters and, after parameter transformations
1239    //   (8.3.5), all parameter types except the first are
1240    //   identical. [...]
1241    //
1242    // To perform this comparison, we compute the function type that
1243    // the deallocation function should have, and use that type both
1244    // for template argument deduction and for comparison purposes.
1245    //
1246    // FIXME: this comparison should ignore CC and the like.
1247    QualType ExpectedFunctionType;
1248    {
1249      const FunctionProtoType *Proto
1250        = OperatorNew->getType()->getAs<FunctionProtoType>();
1251
1252      llvm::SmallVector<QualType, 4> ArgTypes;
1253      ArgTypes.push_back(Context.VoidPtrTy);
1254      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1255        ArgTypes.push_back(Proto->getArgType(I));
1256
1257      FunctionProtoType::ExtProtoInfo EPI;
1258      EPI.Variadic = Proto->isVariadic();
1259
1260      ExpectedFunctionType
1261        = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1262                                  ArgTypes.size(), EPI);
1263    }
1264
1265    for (LookupResult::iterator D = FoundDelete.begin(),
1266                             DEnd = FoundDelete.end();
1267         D != DEnd; ++D) {
1268      FunctionDecl *Fn = 0;
1269      if (FunctionTemplateDecl *FnTmpl
1270            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1271        // Perform template argument deduction to try to match the
1272        // expected function type.
1273        TemplateDeductionInfo Info(Context, StartLoc);
1274        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1275          continue;
1276      } else
1277        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1278
1279      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1280        Matches.push_back(std::make_pair(D.getPair(), Fn));
1281    }
1282  } else {
1283    // C++ [expr.new]p20:
1284    //   [...] Any non-placement deallocation function matches a
1285    //   non-placement allocation function. [...]
1286    for (LookupResult::iterator D = FoundDelete.begin(),
1287                             DEnd = FoundDelete.end();
1288         D != DEnd; ++D) {
1289      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1290        if (isNonPlacementDeallocationFunction(Fn))
1291          Matches.push_back(std::make_pair(D.getPair(), Fn));
1292    }
1293  }
1294
1295  // C++ [expr.new]p20:
1296  //   [...] If the lookup finds a single matching deallocation
1297  //   function, that function will be called; otherwise, no
1298  //   deallocation function will be called.
1299  if (Matches.size() == 1) {
1300    OperatorDelete = Matches[0].second;
1301
1302    // C++0x [expr.new]p20:
1303    //   If the lookup finds the two-parameter form of a usual
1304    //   deallocation function (3.7.4.2) and that function, considered
1305    //   as a placement deallocation function, would have been
1306    //   selected as a match for the allocation function, the program
1307    //   is ill-formed.
1308    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1309        isNonPlacementDeallocationFunction(OperatorDelete)) {
1310      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1311        << SourceRange(PlaceArgs[0]->getLocStart(),
1312                       PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1313      Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1314        << DeleteName;
1315    } else {
1316      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1317                            Matches[0].first);
1318    }
1319  }
1320
1321  return false;
1322}
1323
1324/// FindAllocationOverload - Find an fitting overload for the allocation
1325/// function in the specified scope.
1326bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1327                                  DeclarationName Name, Expr** Args,
1328                                  unsigned NumArgs, DeclContext *Ctx,
1329                                  bool AllowMissing, FunctionDecl *&Operator) {
1330  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1331  LookupQualifiedName(R, Ctx);
1332  if (R.empty()) {
1333    if (AllowMissing)
1334      return false;
1335    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1336      << Name << Range;
1337  }
1338
1339  if (R.isAmbiguous())
1340    return true;
1341
1342  R.suppressDiagnostics();
1343
1344  OverloadCandidateSet Candidates(StartLoc);
1345  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1346       Alloc != AllocEnd; ++Alloc) {
1347    // Even member operator new/delete are implicitly treated as
1348    // static, so don't use AddMemberCandidate.
1349    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1350
1351    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1352      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1353                                   /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1354                                   Candidates,
1355                                   /*SuppressUserConversions=*/false);
1356      continue;
1357    }
1358
1359    FunctionDecl *Fn = cast<FunctionDecl>(D);
1360    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1361                         /*SuppressUserConversions=*/false);
1362  }
1363
1364  // Do the resolution.
1365  OverloadCandidateSet::iterator Best;
1366  switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1367  case OR_Success: {
1368    // Got one!
1369    FunctionDecl *FnDecl = Best->Function;
1370    MarkDeclarationReferenced(StartLoc, FnDecl);
1371    // The first argument is size_t, and the first parameter must be size_t,
1372    // too. This is checked on declaration and can be assumed. (It can't be
1373    // asserted on, though, since invalid decls are left in there.)
1374    // Watch out for variadic allocator function.
1375    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1376    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1377      ExprResult Result
1378        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1379                                                       Context,
1380                                                       FnDecl->getParamDecl(i)),
1381                                    SourceLocation(),
1382                                    Owned(Args[i]));
1383      if (Result.isInvalid())
1384        return true;
1385
1386      Args[i] = Result.takeAs<Expr>();
1387    }
1388    Operator = FnDecl;
1389    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1390    return false;
1391  }
1392
1393  case OR_No_Viable_Function:
1394    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1395      << Name << Range;
1396    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1397    return true;
1398
1399  case OR_Ambiguous:
1400    Diag(StartLoc, diag::err_ovl_ambiguous_call)
1401      << Name << Range;
1402    Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1403    return true;
1404
1405  case OR_Deleted: {
1406    Diag(StartLoc, diag::err_ovl_deleted_call)
1407      << Best->Function->isDeleted()
1408      << Name
1409      << getDeletedOrUnavailableSuffix(Best->Function)
1410      << Range;
1411    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1412    return true;
1413  }
1414  }
1415  assert(false && "Unreachable, bad result from BestViableFunction");
1416  return true;
1417}
1418
1419
1420/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1421/// delete. These are:
1422/// @code
1423///   // C++03:
1424///   void* operator new(std::size_t) throw(std::bad_alloc);
1425///   void* operator new[](std::size_t) throw(std::bad_alloc);
1426///   void operator delete(void *) throw();
1427///   void operator delete[](void *) throw();
1428///   // C++0x:
1429///   void* operator new(std::size_t);
1430///   void* operator new[](std::size_t);
1431///   void operator delete(void *);
1432///   void operator delete[](void *);
1433/// @endcode
1434/// C++0x operator delete is implicitly noexcept.
1435/// Note that the placement and nothrow forms of new are *not* implicitly
1436/// declared. Their use requires including \<new\>.
1437void Sema::DeclareGlobalNewDelete() {
1438  if (GlobalNewDeleteDeclared)
1439    return;
1440
1441  // C++ [basic.std.dynamic]p2:
1442  //   [...] The following allocation and deallocation functions (18.4) are
1443  //   implicitly declared in global scope in each translation unit of a
1444  //   program
1445  //
1446  //     C++03:
1447  //     void* operator new(std::size_t) throw(std::bad_alloc);
1448  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1449  //     void  operator delete(void*) throw();
1450  //     void  operator delete[](void*) throw();
1451  //     C++0x:
1452  //     void* operator new(std::size_t);
1453  //     void* operator new[](std::size_t);
1454  //     void  operator delete(void*);
1455  //     void  operator delete[](void*);
1456  //
1457  //   These implicit declarations introduce only the function names operator
1458  //   new, operator new[], operator delete, operator delete[].
1459  //
1460  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1461  // "std" or "bad_alloc" as necessary to form the exception specification.
1462  // However, we do not make these implicit declarations visible to name
1463  // lookup.
1464  // Note that the C++0x versions of operator delete are deallocation functions,
1465  // and thus are implicitly noexcept.
1466  if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
1467    // The "std::bad_alloc" class has not yet been declared, so build it
1468    // implicitly.
1469    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1470                                        getOrCreateStdNamespace(),
1471                                        SourceLocation(), SourceLocation(),
1472                                      &PP.getIdentifierTable().get("bad_alloc"),
1473                                        0);
1474    getStdBadAlloc()->setImplicit(true);
1475  }
1476
1477  GlobalNewDeleteDeclared = true;
1478
1479  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1480  QualType SizeT = Context.getSizeType();
1481  bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1482
1483  DeclareGlobalAllocationFunction(
1484      Context.DeclarationNames.getCXXOperatorName(OO_New),
1485      VoidPtr, SizeT, AssumeSaneOperatorNew);
1486  DeclareGlobalAllocationFunction(
1487      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1488      VoidPtr, SizeT, AssumeSaneOperatorNew);
1489  DeclareGlobalAllocationFunction(
1490      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1491      Context.VoidTy, VoidPtr);
1492  DeclareGlobalAllocationFunction(
1493      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1494      Context.VoidTy, VoidPtr);
1495}
1496
1497/// DeclareGlobalAllocationFunction - Declares a single implicit global
1498/// allocation function if it doesn't already exist.
1499void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1500                                           QualType Return, QualType Argument,
1501                                           bool AddMallocAttr) {
1502  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1503
1504  // Check if this function is already declared.
1505  {
1506    DeclContext::lookup_iterator Alloc, AllocEnd;
1507    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1508         Alloc != AllocEnd; ++Alloc) {
1509      // Only look at non-template functions, as it is the predefined,
1510      // non-templated allocation function we are trying to declare here.
1511      if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1512        QualType InitialParamType =
1513          Context.getCanonicalType(
1514            Func->getParamDecl(0)->getType().getUnqualifiedType());
1515        // FIXME: Do we need to check for default arguments here?
1516        if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1517          if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1518            Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1519          return;
1520        }
1521      }
1522    }
1523  }
1524
1525  QualType BadAllocType;
1526  bool HasBadAllocExceptionSpec
1527    = (Name.getCXXOverloadedOperator() == OO_New ||
1528       Name.getCXXOverloadedOperator() == OO_Array_New);
1529  if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
1530    assert(StdBadAlloc && "Must have std::bad_alloc declared");
1531    BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1532  }
1533
1534  FunctionProtoType::ExtProtoInfo EPI;
1535  if (HasBadAllocExceptionSpec) {
1536    if (!getLangOptions().CPlusPlus0x) {
1537      EPI.ExceptionSpecType = EST_Dynamic;
1538      EPI.NumExceptions = 1;
1539      EPI.Exceptions = &BadAllocType;
1540    }
1541  } else {
1542    EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1543                                EST_BasicNoexcept : EST_DynamicNone;
1544  }
1545
1546  QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
1547  FunctionDecl *Alloc =
1548    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1549                         SourceLocation(), Name,
1550                         FnType, /*TInfo=*/0, SC_None,
1551                         SC_None, false, true);
1552  Alloc->setImplicit();
1553
1554  if (AddMallocAttr)
1555    Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1556
1557  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1558                                           SourceLocation(), 0,
1559                                           Argument, /*TInfo=*/0,
1560                                           SC_None, SC_None, 0);
1561  Alloc->setParams(&Param, 1);
1562
1563  // FIXME: Also add this declaration to the IdentifierResolver, but
1564  // make sure it is at the end of the chain to coincide with the
1565  // global scope.
1566  Context.getTranslationUnitDecl()->addDecl(Alloc);
1567}
1568
1569bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1570                                    DeclarationName Name,
1571                                    FunctionDecl* &Operator) {
1572  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1573  // Try to find operator delete/operator delete[] in class scope.
1574  LookupQualifiedName(Found, RD);
1575
1576  if (Found.isAmbiguous())
1577    return true;
1578
1579  Found.suppressDiagnostics();
1580
1581  llvm::SmallVector<DeclAccessPair,4> Matches;
1582  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1583       F != FEnd; ++F) {
1584    NamedDecl *ND = (*F)->getUnderlyingDecl();
1585
1586    // Ignore template operator delete members from the check for a usual
1587    // deallocation function.
1588    if (isa<FunctionTemplateDecl>(ND))
1589      continue;
1590
1591    if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1592      Matches.push_back(F.getPair());
1593  }
1594
1595  // There's exactly one suitable operator;  pick it.
1596  if (Matches.size() == 1) {
1597    Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1598    CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1599                          Matches[0]);
1600    return false;
1601
1602  // We found multiple suitable operators;  complain about the ambiguity.
1603  } else if (!Matches.empty()) {
1604    Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1605      << Name << RD;
1606
1607    for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1608           F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1609      Diag((*F)->getUnderlyingDecl()->getLocation(),
1610           diag::note_member_declared_here) << Name;
1611    return true;
1612  }
1613
1614  // We did find operator delete/operator delete[] declarations, but
1615  // none of them were suitable.
1616  if (!Found.empty()) {
1617    Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1618      << Name << RD;
1619
1620    for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1621         F != FEnd; ++F)
1622      Diag((*F)->getUnderlyingDecl()->getLocation(),
1623           diag::note_member_declared_here) << Name;
1624
1625    return true;
1626  }
1627
1628  // Look for a global declaration.
1629  DeclareGlobalNewDelete();
1630  DeclContext *TUDecl = Context.getTranslationUnitDecl();
1631
1632  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1633  Expr* DeallocArgs[1];
1634  DeallocArgs[0] = &Null;
1635  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1636                             DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1637                             Operator))
1638    return true;
1639
1640  assert(Operator && "Did not find a deallocation function!");
1641  return false;
1642}
1643
1644/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1645/// @code ::delete ptr; @endcode
1646/// or
1647/// @code delete [] ptr; @endcode
1648ExprResult
1649Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1650                     bool ArrayForm, Expr *ExE) {
1651  // C++ [expr.delete]p1:
1652  //   The operand shall have a pointer type, or a class type having a single
1653  //   conversion function to a pointer type. The result has type void.
1654  //
1655  // DR599 amends "pointer type" to "pointer to object type" in both cases.
1656
1657  ExprResult Ex = Owned(ExE);
1658  FunctionDecl *OperatorDelete = 0;
1659  bool ArrayFormAsWritten = ArrayForm;
1660  bool UsualArrayDeleteWantsSize = false;
1661
1662  if (!Ex.get()->isTypeDependent()) {
1663    QualType Type = Ex.get()->getType();
1664
1665    if (const RecordType *Record = Type->getAs<RecordType>()) {
1666      if (RequireCompleteType(StartLoc, Type,
1667                              PDiag(diag::err_delete_incomplete_class_type)))
1668        return ExprError();
1669
1670      llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1671
1672      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1673      const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1674      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1675             E = Conversions->end(); I != E; ++I) {
1676        NamedDecl *D = I.getDecl();
1677        if (isa<UsingShadowDecl>(D))
1678          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1679
1680        // Skip over templated conversion functions; they aren't considered.
1681        if (isa<FunctionTemplateDecl>(D))
1682          continue;
1683
1684        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1685
1686        QualType ConvType = Conv->getConversionType().getNonReferenceType();
1687        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1688          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
1689            ObjectPtrConversions.push_back(Conv);
1690      }
1691      if (ObjectPtrConversions.size() == 1) {
1692        // We have a single conversion to a pointer-to-object type. Perform
1693        // that conversion.
1694        // TODO: don't redo the conversion calculation.
1695        ExprResult Res =
1696          PerformImplicitConversion(Ex.get(),
1697                            ObjectPtrConversions.front()->getConversionType(),
1698                                    AA_Converting);
1699        if (Res.isUsable()) {
1700          Ex = move(Res);
1701          Type = Ex.get()->getType();
1702        }
1703      }
1704      else if (ObjectPtrConversions.size() > 1) {
1705        Diag(StartLoc, diag::err_ambiguous_delete_operand)
1706              << Type << Ex.get()->getSourceRange();
1707        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1708          NoteOverloadCandidate(ObjectPtrConversions[i]);
1709        return ExprError();
1710      }
1711    }
1712
1713    if (!Type->isPointerType())
1714      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1715        << Type << Ex.get()->getSourceRange());
1716
1717    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1718    if (Pointee->isVoidType() && !isSFINAEContext()) {
1719      // The C++ standard bans deleting a pointer to a non-object type, which
1720      // effectively bans deletion of "void*". However, most compilers support
1721      // this, so we treat it as a warning unless we're in a SFINAE context.
1722      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1723        << Type << Ex.get()->getSourceRange();
1724    } else if (Pointee->isFunctionType() || Pointee->isVoidType())
1725      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1726        << Type << Ex.get()->getSourceRange());
1727    else if (!Pointee->isDependentType() &&
1728             RequireCompleteType(StartLoc, Pointee,
1729                                 PDiag(diag::warn_delete_incomplete)
1730                                   << Ex.get()->getSourceRange()))
1731      return ExprError();
1732    else if (unsigned AddressSpace = Pointee.getAddressSpace())
1733      return Diag(Ex.get()->getLocStart(),
1734                  diag::err_address_space_qualified_delete)
1735               << Pointee.getUnqualifiedType() << AddressSpace;
1736    // C++ [expr.delete]p2:
1737    //   [Note: a pointer to a const type can be the operand of a
1738    //   delete-expression; it is not necessary to cast away the constness
1739    //   (5.2.11) of the pointer expression before it is used as the operand
1740    //   of the delete-expression. ]
1741    Ex = ImpCastExprToType(Ex.take(), Context.getPointerType(Context.VoidTy),
1742                      CK_NoOp);
1743
1744    if (Pointee->isArrayType() && !ArrayForm) {
1745      Diag(StartLoc, diag::warn_delete_array_type)
1746          << Type << Ex.get()->getSourceRange()
1747          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1748      ArrayForm = true;
1749    }
1750
1751    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1752                                      ArrayForm ? OO_Array_Delete : OO_Delete);
1753
1754    QualType PointeeElem = Context.getBaseElementType(Pointee);
1755    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1756      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1757
1758      if (!UseGlobal &&
1759          FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1760        return ExprError();
1761
1762      // If we're allocating an array of records, check whether the
1763      // usual operator delete[] has a size_t parameter.
1764      if (ArrayForm) {
1765        // If the user specifically asked to use the global allocator,
1766        // we'll need to do the lookup into the class.
1767        if (UseGlobal)
1768          UsualArrayDeleteWantsSize =
1769            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1770
1771        // Otherwise, the usual operator delete[] should be the
1772        // function we just found.
1773        else if (isa<CXXMethodDecl>(OperatorDelete))
1774          UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1775      }
1776
1777      if (!RD->hasTrivialDestructor())
1778        if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1779          MarkDeclarationReferenced(StartLoc,
1780                                    const_cast<CXXDestructorDecl*>(Dtor));
1781          DiagnoseUseOfDecl(Dtor, StartLoc);
1782        }
1783    }
1784
1785    if (!OperatorDelete) {
1786      // Look for a global declaration.
1787      DeclareGlobalNewDelete();
1788      DeclContext *TUDecl = Context.getTranslationUnitDecl();
1789      Expr *Arg = Ex.get();
1790      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1791                                 &Arg, 1, TUDecl, /*AllowMissing=*/false,
1792                                 OperatorDelete))
1793        return ExprError();
1794    }
1795
1796    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1797
1798    // Check access and ambiguity of operator delete and destructor.
1799    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1800      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1801      if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1802          CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
1803                      PDiag(diag::err_access_dtor) << PointeeElem);
1804      }
1805    }
1806
1807  }
1808
1809  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1810                                           ArrayFormAsWritten,
1811                                           UsualArrayDeleteWantsSize,
1812                                           OperatorDelete, Ex.take(), StartLoc));
1813}
1814
1815/// \brief Check the use of the given variable as a C++ condition in an if,
1816/// while, do-while, or switch statement.
1817ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1818                                        SourceLocation StmtLoc,
1819                                        bool ConvertToBoolean) {
1820  QualType T = ConditionVar->getType();
1821
1822  // C++ [stmt.select]p2:
1823  //   The declarator shall not specify a function or an array.
1824  if (T->isFunctionType())
1825    return ExprError(Diag(ConditionVar->getLocation(),
1826                          diag::err_invalid_use_of_function_type)
1827                       << ConditionVar->getSourceRange());
1828  else if (T->isArrayType())
1829    return ExprError(Diag(ConditionVar->getLocation(),
1830                          diag::err_invalid_use_of_array_type)
1831                     << ConditionVar->getSourceRange());
1832
1833  ExprResult Condition =
1834    Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1835                                        ConditionVar,
1836                                        ConditionVar->getLocation(),
1837                            ConditionVar->getType().getNonReferenceType(),
1838                              VK_LValue));
1839  if (ConvertToBoolean) {
1840    Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
1841    if (Condition.isInvalid())
1842      return ExprError();
1843  }
1844
1845  return move(Condition);
1846}
1847
1848/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1849ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
1850  // C++ 6.4p4:
1851  // The value of a condition that is an initialized declaration in a statement
1852  // other than a switch statement is the value of the declared variable
1853  // implicitly converted to type bool. If that conversion is ill-formed, the
1854  // program is ill-formed.
1855  // The value of a condition that is an expression is the value of the
1856  // expression, implicitly converted to bool.
1857  //
1858  return PerformContextuallyConvertToBool(CondExpr);
1859}
1860
1861/// Helper function to determine whether this is the (deprecated) C++
1862/// conversion from a string literal to a pointer to non-const char or
1863/// non-const wchar_t (for narrow and wide string literals,
1864/// respectively).
1865bool
1866Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1867  // Look inside the implicit cast, if it exists.
1868  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1869    From = Cast->getSubExpr();
1870
1871  // A string literal (2.13.4) that is not a wide string literal can
1872  // be converted to an rvalue of type "pointer to char"; a wide
1873  // string literal can be converted to an rvalue of type "pointer
1874  // to wchar_t" (C++ 4.2p2).
1875  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
1876    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1877      if (const BuiltinType *ToPointeeType
1878          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1879        // This conversion is considered only when there is an
1880        // explicit appropriate pointer target type (C++ 4.2p2).
1881        if (!ToPtrType->getPointeeType().hasQualifiers() &&
1882            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1883             (!StrLit->isWide() &&
1884              (ToPointeeType->getKind() == BuiltinType::Char_U ||
1885               ToPointeeType->getKind() == BuiltinType::Char_S))))
1886          return true;
1887      }
1888
1889  return false;
1890}
1891
1892static ExprResult BuildCXXCastArgument(Sema &S,
1893                                       SourceLocation CastLoc,
1894                                       QualType Ty,
1895                                       CastKind Kind,
1896                                       CXXMethodDecl *Method,
1897                                       NamedDecl *FoundDecl,
1898                                       Expr *From) {
1899  switch (Kind) {
1900  default: assert(0 && "Unhandled cast kind!");
1901  case CK_ConstructorConversion: {
1902    ASTOwningVector<Expr*> ConstructorArgs(S);
1903
1904    if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1905                                  MultiExprArg(&From, 1),
1906                                  CastLoc, ConstructorArgs))
1907      return ExprError();
1908
1909    ExprResult Result =
1910    S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1911                            move_arg(ConstructorArgs),
1912                            /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1913                            SourceRange());
1914    if (Result.isInvalid())
1915      return ExprError();
1916
1917    return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1918  }
1919
1920  case CK_UserDefinedConversion: {
1921    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1922
1923    // Create an implicit call expr that calls it.
1924    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
1925    if (Result.isInvalid())
1926      return ExprError();
1927
1928    return S.MaybeBindToTemporary(Result.get());
1929  }
1930  }
1931}
1932
1933/// PerformImplicitConversion - Perform an implicit conversion of the
1934/// expression From to the type ToType using the pre-computed implicit
1935/// conversion sequence ICS. Returns the converted
1936/// expression. Action is the kind of conversion we're performing,
1937/// used in the error message.
1938ExprResult
1939Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1940                                const ImplicitConversionSequence &ICS,
1941                                AssignmentAction Action, bool CStyle) {
1942  switch (ICS.getKind()) {
1943  case ImplicitConversionSequence::StandardConversion: {
1944    ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
1945                                               Action, CStyle);
1946    if (Res.isInvalid())
1947      return ExprError();
1948    From = Res.take();
1949    break;
1950  }
1951
1952  case ImplicitConversionSequence::UserDefinedConversion: {
1953
1954      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1955      CastKind CastKind;
1956      QualType BeforeToType;
1957      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1958        CastKind = CK_UserDefinedConversion;
1959
1960        // If the user-defined conversion is specified by a conversion function,
1961        // the initial standard conversion sequence converts the source type to
1962        // the implicit object parameter of the conversion function.
1963        BeforeToType = Context.getTagDeclType(Conv->getParent());
1964      } else {
1965        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
1966        CastKind = CK_ConstructorConversion;
1967        // Do no conversion if dealing with ... for the first conversion.
1968        if (!ICS.UserDefined.EllipsisConversion) {
1969          // If the user-defined conversion is specified by a constructor, the
1970          // initial standard conversion sequence converts the source type to the
1971          // type required by the argument of the constructor
1972          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1973        }
1974      }
1975      // Watch out for elipsis conversion.
1976      if (!ICS.UserDefined.EllipsisConversion) {
1977        ExprResult Res =
1978          PerformImplicitConversion(From, BeforeToType,
1979                                    ICS.UserDefined.Before, AA_Converting,
1980                                    CStyle);
1981        if (Res.isInvalid())
1982          return ExprError();
1983        From = Res.take();
1984      }
1985
1986      ExprResult CastArg
1987        = BuildCXXCastArgument(*this,
1988                               From->getLocStart(),
1989                               ToType.getNonReferenceType(),
1990                               CastKind, cast<CXXMethodDecl>(FD),
1991                               ICS.UserDefined.FoundConversionFunction,
1992                               From);
1993
1994      if (CastArg.isInvalid())
1995        return ExprError();
1996
1997      From = CastArg.take();
1998
1999      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2000                                       AA_Converting, CStyle);
2001  }
2002
2003  case ImplicitConversionSequence::AmbiguousConversion:
2004    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2005                          PDiag(diag::err_typecheck_ambiguous_condition)
2006                            << From->getSourceRange());
2007     return ExprError();
2008
2009  case ImplicitConversionSequence::EllipsisConversion:
2010    assert(false && "Cannot perform an ellipsis conversion");
2011    return Owned(From);
2012
2013  case ImplicitConversionSequence::BadConversion:
2014    return ExprError();
2015  }
2016
2017  // Everything went well.
2018  return Owned(From);
2019}
2020
2021/// PerformImplicitConversion - Perform an implicit conversion of the
2022/// expression From to the type ToType by following the standard
2023/// conversion sequence SCS. Returns the converted
2024/// expression. Flavor is the context in which we're performing this
2025/// conversion, for use in error messages.
2026ExprResult
2027Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2028                                const StandardConversionSequence& SCS,
2029                                AssignmentAction Action, bool CStyle) {
2030  // Overall FIXME: we are recomputing too many types here and doing far too
2031  // much extra work. What this means is that we need to keep track of more
2032  // information that is computed when we try the implicit conversion initially,
2033  // so that we don't need to recompute anything here.
2034  QualType FromType = From->getType();
2035
2036  if (SCS.CopyConstructor) {
2037    // FIXME: When can ToType be a reference type?
2038    assert(!ToType->isReferenceType());
2039    if (SCS.Second == ICK_Derived_To_Base) {
2040      ASTOwningVector<Expr*> ConstructorArgs(*this);
2041      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2042                                  MultiExprArg(*this, &From, 1),
2043                                  /*FIXME:ConstructLoc*/SourceLocation(),
2044                                  ConstructorArgs))
2045        return ExprError();
2046      return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2047                                   ToType, SCS.CopyConstructor,
2048                                   move_arg(ConstructorArgs),
2049                                   /*ZeroInit*/ false,
2050                                   CXXConstructExpr::CK_Complete,
2051                                   SourceRange());
2052    }
2053    return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2054                                 ToType, SCS.CopyConstructor,
2055                                 MultiExprArg(*this, &From, 1),
2056                                 /*ZeroInit*/ false,
2057                                 CXXConstructExpr::CK_Complete,
2058                                 SourceRange());
2059  }
2060
2061  // Resolve overloaded function references.
2062  if (Context.hasSameType(FromType, Context.OverloadTy)) {
2063    DeclAccessPair Found;
2064    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2065                                                          true, Found);
2066    if (!Fn)
2067      return ExprError();
2068
2069    if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2070      return ExprError();
2071
2072    From = FixOverloadedFunctionReference(From, Found, Fn);
2073    FromType = From->getType();
2074  }
2075
2076  // Perform the first implicit conversion.
2077  switch (SCS.First) {
2078  case ICK_Identity:
2079    // Nothing to do.
2080    break;
2081
2082  case ICK_Lvalue_To_Rvalue:
2083    // Should this get its own ICK?
2084    if (From->getObjectKind() == OK_ObjCProperty) {
2085      ExprResult FromRes = ConvertPropertyForRValue(From);
2086      if (FromRes.isInvalid())
2087        return ExprError();
2088      From = FromRes.take();
2089      if (!From->isGLValue()) break;
2090    }
2091
2092    // Check for trivial buffer overflows.
2093    CheckArrayAccess(From);
2094
2095    FromType = FromType.getUnqualifiedType();
2096    From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2097                                    From, 0, VK_RValue);
2098    break;
2099
2100  case ICK_Array_To_Pointer:
2101    FromType = Context.getArrayDecayedType(FromType);
2102    From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay).take();
2103    break;
2104
2105  case ICK_Function_To_Pointer:
2106    FromType = Context.getPointerType(FromType);
2107    From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay).take();
2108    break;
2109
2110  default:
2111    assert(false && "Improper first standard conversion");
2112    break;
2113  }
2114
2115  // Perform the second implicit conversion
2116  switch (SCS.Second) {
2117  case ICK_Identity:
2118    // If both sides are functions (or pointers/references to them), there could
2119    // be incompatible exception declarations.
2120    if (CheckExceptionSpecCompatibility(From, ToType))
2121      return ExprError();
2122    // Nothing else to do.
2123    break;
2124
2125  case ICK_NoReturn_Adjustment:
2126    // If both sides are functions (or pointers/references to them), there could
2127    // be incompatible exception declarations.
2128    if (CheckExceptionSpecCompatibility(From, ToType))
2129      return ExprError();
2130
2131    From = ImpCastExprToType(From, ToType, CK_NoOp).take();
2132    break;
2133
2134  case ICK_Integral_Promotion:
2135  case ICK_Integral_Conversion:
2136    From = ImpCastExprToType(From, ToType, CK_IntegralCast).take();
2137    break;
2138
2139  case ICK_Floating_Promotion:
2140  case ICK_Floating_Conversion:
2141    From = ImpCastExprToType(From, ToType, CK_FloatingCast).take();
2142    break;
2143
2144  case ICK_Complex_Promotion:
2145  case ICK_Complex_Conversion: {
2146    QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2147    QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2148    CastKind CK;
2149    if (FromEl->isRealFloatingType()) {
2150      if (ToEl->isRealFloatingType())
2151        CK = CK_FloatingComplexCast;
2152      else
2153        CK = CK_FloatingComplexToIntegralComplex;
2154    } else if (ToEl->isRealFloatingType()) {
2155      CK = CK_IntegralComplexToFloatingComplex;
2156    } else {
2157      CK = CK_IntegralComplexCast;
2158    }
2159    From = ImpCastExprToType(From, ToType, CK).take();
2160    break;
2161  }
2162
2163  case ICK_Floating_Integral:
2164    if (ToType->isRealFloatingType())
2165      From = ImpCastExprToType(From, ToType, CK_IntegralToFloating).take();
2166    else
2167      From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral).take();
2168    break;
2169
2170  case ICK_Compatible_Conversion:
2171    From = ImpCastExprToType(From, ToType, CK_NoOp).take();
2172    break;
2173
2174  case ICK_Pointer_Conversion: {
2175    if (SCS.IncompatibleObjC && Action != AA_Casting) {
2176      // Diagnose incompatible Objective-C conversions
2177      if (Action == AA_Initializing)
2178        Diag(From->getSourceRange().getBegin(),
2179             diag::ext_typecheck_convert_incompatible_pointer)
2180          << ToType << From->getType() << Action
2181          << From->getSourceRange();
2182      else
2183        Diag(From->getSourceRange().getBegin(),
2184             diag::ext_typecheck_convert_incompatible_pointer)
2185          << From->getType() << ToType << Action
2186          << From->getSourceRange();
2187    }
2188
2189    CastKind Kind = CK_Invalid;
2190    CXXCastPath BasePath;
2191    if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2192      return ExprError();
2193    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
2194    break;
2195  }
2196
2197  case ICK_Pointer_Member: {
2198    CastKind Kind = CK_Invalid;
2199    CXXCastPath BasePath;
2200    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2201      return ExprError();
2202    if (CheckExceptionSpecCompatibility(From, ToType))
2203      return ExprError();
2204    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
2205    break;
2206  }
2207
2208  case ICK_Boolean_Conversion:
2209    From = ImpCastExprToType(From, Context.BoolTy,
2210                             ScalarTypeToBooleanCastKind(FromType)).take();
2211    break;
2212
2213  case ICK_Derived_To_Base: {
2214    CXXCastPath BasePath;
2215    if (CheckDerivedToBaseConversion(From->getType(),
2216                                     ToType.getNonReferenceType(),
2217                                     From->getLocStart(),
2218                                     From->getSourceRange(),
2219                                     &BasePath,
2220                                     CStyle))
2221      return ExprError();
2222
2223    From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2224                      CK_DerivedToBase, CastCategory(From),
2225                      &BasePath).take();
2226    break;
2227  }
2228
2229  case ICK_Vector_Conversion:
2230    From = ImpCastExprToType(From, ToType, CK_BitCast).take();
2231    break;
2232
2233  case ICK_Vector_Splat:
2234    From = ImpCastExprToType(From, ToType, CK_VectorSplat).take();
2235    break;
2236
2237  case ICK_Complex_Real:
2238    // Case 1.  x -> _Complex y
2239    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2240      QualType ElType = ToComplex->getElementType();
2241      bool isFloatingComplex = ElType->isRealFloatingType();
2242
2243      // x -> y
2244      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2245        // do nothing
2246      } else if (From->getType()->isRealFloatingType()) {
2247        From = ImpCastExprToType(From, ElType,
2248                isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2249      } else {
2250        assert(From->getType()->isIntegerType());
2251        From = ImpCastExprToType(From, ElType,
2252                isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2253      }
2254      // y -> _Complex y
2255      From = ImpCastExprToType(From, ToType,
2256                   isFloatingComplex ? CK_FloatingRealToComplex
2257                                     : CK_IntegralRealToComplex).take();
2258
2259    // Case 2.  _Complex x -> y
2260    } else {
2261      const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2262      assert(FromComplex);
2263
2264      QualType ElType = FromComplex->getElementType();
2265      bool isFloatingComplex = ElType->isRealFloatingType();
2266
2267      // _Complex x -> x
2268      From = ImpCastExprToType(From, ElType,
2269                   isFloatingComplex ? CK_FloatingComplexToReal
2270                                     : CK_IntegralComplexToReal).take();
2271
2272      // x -> y
2273      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2274        // do nothing
2275      } else if (ToType->isRealFloatingType()) {
2276        From = ImpCastExprToType(From, ToType,
2277                isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating).take();
2278      } else {
2279        assert(ToType->isIntegerType());
2280        From = ImpCastExprToType(From, ToType,
2281                isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast).take();
2282      }
2283    }
2284    break;
2285
2286  case ICK_Block_Pointer_Conversion: {
2287      From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2288                               VK_RValue).take();
2289      break;
2290    }
2291
2292  case ICK_TransparentUnionConversion: {
2293    ExprResult FromRes = Owned(From);
2294    Sema::AssignConvertType ConvTy =
2295      CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2296    if (FromRes.isInvalid())
2297      return ExprError();
2298    From = FromRes.take();
2299    assert ((ConvTy == Sema::Compatible) &&
2300            "Improper transparent union conversion");
2301    (void)ConvTy;
2302    break;
2303  }
2304
2305  case ICK_Lvalue_To_Rvalue:
2306  case ICK_Array_To_Pointer:
2307  case ICK_Function_To_Pointer:
2308  case ICK_Qualification:
2309  case ICK_Num_Conversion_Kinds:
2310    assert(false && "Improper second standard conversion");
2311    break;
2312  }
2313
2314  switch (SCS.Third) {
2315  case ICK_Identity:
2316    // Nothing to do.
2317    break;
2318
2319  case ICK_Qualification: {
2320    // The qualification keeps the category of the inner expression, unless the
2321    // target type isn't a reference.
2322    ExprValueKind VK = ToType->isReferenceType() ?
2323                                  CastCategory(From) : VK_RValue;
2324    From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2325                             CK_NoOp, VK).take();
2326
2327    if (SCS.DeprecatedStringLiteralToCharPtr &&
2328        !getLangOptions().WritableStrings)
2329      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2330        << ToType.getNonReferenceType();
2331
2332    break;
2333    }
2334
2335  default:
2336    assert(false && "Improper third standard conversion");
2337    break;
2338  }
2339
2340  return Owned(From);
2341}
2342
2343ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
2344                                     SourceLocation KWLoc,
2345                                     ParsedType Ty,
2346                                     SourceLocation RParen) {
2347  TypeSourceInfo *TSInfo;
2348  QualType T = GetTypeFromParser(Ty, &TSInfo);
2349
2350  if (!TSInfo)
2351    TSInfo = Context.getTrivialTypeSourceInfo(T);
2352  return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
2353}
2354
2355/// \brief Check the completeness of a type in a unary type trait.
2356///
2357/// If the particular type trait requires a complete type, tries to complete
2358/// it. If completing the type fails, a diagnostic is emitted and false
2359/// returned. If completing the type succeeds or no completion was required,
2360/// returns true.
2361static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2362                                                UnaryTypeTrait UTT,
2363                                                SourceLocation Loc,
2364                                                QualType ArgTy) {
2365  // C++0x [meta.unary.prop]p3:
2366  //   For all of the class templates X declared in this Clause, instantiating
2367  //   that template with a template argument that is a class template
2368  //   specialization may result in the implicit instantiation of the template
2369  //   argument if and only if the semantics of X require that the argument
2370  //   must be a complete type.
2371  // We apply this rule to all the type trait expressions used to implement
2372  // these class templates. We also try to follow any GCC documented behavior
2373  // in these expressions to ensure portability of standard libraries.
2374  switch (UTT) {
2375    // is_complete_type somewhat obviously cannot require a complete type.
2376  case UTT_IsCompleteType:
2377    // Fallthrough
2378
2379    // These traits are modeled on the type predicates in C++0x
2380    // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2381    // requiring a complete type, as whether or not they return true cannot be
2382    // impacted by the completeness of the type.
2383  case UTT_IsVoid:
2384  case UTT_IsIntegral:
2385  case UTT_IsFloatingPoint:
2386  case UTT_IsArray:
2387  case UTT_IsPointer:
2388  case UTT_IsLvalueReference:
2389  case UTT_IsRvalueReference:
2390  case UTT_IsMemberFunctionPointer:
2391  case UTT_IsMemberObjectPointer:
2392  case UTT_IsEnum:
2393  case UTT_IsUnion:
2394  case UTT_IsClass:
2395  case UTT_IsFunction:
2396  case UTT_IsReference:
2397  case UTT_IsArithmetic:
2398  case UTT_IsFundamental:
2399  case UTT_IsObject:
2400  case UTT_IsScalar:
2401  case UTT_IsCompound:
2402  case UTT_IsMemberPointer:
2403    // Fallthrough
2404
2405    // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2406    // which requires some of its traits to have the complete type. However,
2407    // the completeness of the type cannot impact these traits' semantics, and
2408    // so they don't require it. This matches the comments on these traits in
2409    // Table 49.
2410  case UTT_IsConst:
2411  case UTT_IsVolatile:
2412  case UTT_IsSigned:
2413  case UTT_IsUnsigned:
2414    return true;
2415
2416    // C++0x [meta.unary.prop] Table 49 requires the following traits to be
2417    // applied to a complete type, so we enumerate theme here even though the
2418    // default for non-Borland compilers is to require completeness for any
2419    // other traits than the ones specifically allowed to work on incomplete
2420    // types.
2421  case UTT_IsTrivial:
2422  case UTT_IsStandardLayout:
2423  case UTT_IsPOD:
2424  case UTT_IsLiteral:
2425  case UTT_IsEmpty:
2426  case UTT_IsPolymorphic:
2427  case UTT_IsAbstract:
2428    // Fallthrough
2429
2430    // These trait expressions are designed to help implement predicats in
2431    // [meta.unary.prop] despite not being named the same. They are specified
2432    // by both GCC and the Embarcadero C++ compiler, and require the complete
2433    // type due to the overarching C++0x type predicates being implemented
2434    // requiring the complete type.
2435  case UTT_HasNothrowAssign:
2436  case UTT_HasNothrowConstructor:
2437  case UTT_HasNothrowCopy:
2438  case UTT_HasTrivialAssign:
2439  case UTT_HasTrivialConstructor:
2440  case UTT_HasTrivialCopy:
2441  case UTT_HasTrivialDestructor:
2442  case UTT_HasVirtualDestructor:
2443    // Arrays of unknown bound are expressly allowed.
2444    QualType ElTy = ArgTy;
2445    if (ArgTy->isIncompleteArrayType())
2446      ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2447
2448    // The void type is expressly allowed.
2449    if (ElTy->isVoidType())
2450      return true;
2451
2452    return !S.RequireCompleteType(
2453      Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
2454  }
2455  llvm_unreachable("Type trait not handled by switch");
2456}
2457
2458static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2459                                   SourceLocation KeyLoc, QualType T) {
2460  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
2461
2462  ASTContext &C = Self.Context;
2463  switch(UTT) {
2464    // Type trait expressions corresponding to the primary type category
2465    // predicates in C++0x [meta.unary.cat].
2466  case UTT_IsVoid:
2467    return T->isVoidType();
2468  case UTT_IsIntegral:
2469    return T->isIntegralType(C);
2470  case UTT_IsFloatingPoint:
2471    return T->isFloatingType();
2472  case UTT_IsArray:
2473    return T->isArrayType();
2474  case UTT_IsPointer:
2475    return T->isPointerType();
2476  case UTT_IsLvalueReference:
2477    return T->isLValueReferenceType();
2478  case UTT_IsRvalueReference:
2479    return T->isRValueReferenceType();
2480  case UTT_IsMemberFunctionPointer:
2481    return T->isMemberFunctionPointerType();
2482  case UTT_IsMemberObjectPointer:
2483    return T->isMemberDataPointerType();
2484  case UTT_IsEnum:
2485    return T->isEnumeralType();
2486  case UTT_IsUnion:
2487    return T->isUnionType();
2488  case UTT_IsClass:
2489    return T->isClassType() || T->isStructureType();
2490  case UTT_IsFunction:
2491    return T->isFunctionType();
2492
2493    // Type trait expressions which correspond to the convenient composition
2494    // predicates in C++0x [meta.unary.comp].
2495  case UTT_IsReference:
2496    return T->isReferenceType();
2497  case UTT_IsArithmetic:
2498    return T->isArithmeticType() && !T->isEnumeralType();
2499  case UTT_IsFundamental:
2500    return T->isFundamentalType();
2501  case UTT_IsObject:
2502    return T->isObjectType();
2503  case UTT_IsScalar:
2504    return T->isScalarType();
2505  case UTT_IsCompound:
2506    return T->isCompoundType();
2507  case UTT_IsMemberPointer:
2508    return T->isMemberPointerType();
2509
2510    // Type trait expressions which correspond to the type property predicates
2511    // in C++0x [meta.unary.prop].
2512  case UTT_IsConst:
2513    return T.isConstQualified();
2514  case UTT_IsVolatile:
2515    return T.isVolatileQualified();
2516  case UTT_IsTrivial:
2517    return T->isTrivialType();
2518  case UTT_IsStandardLayout:
2519    return T->isStandardLayoutType();
2520  case UTT_IsPOD:
2521    return T->isPODType();
2522  case UTT_IsLiteral:
2523    return T->isLiteralType();
2524  case UTT_IsEmpty:
2525    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2526      return !RD->isUnion() && RD->isEmpty();
2527    return false;
2528  case UTT_IsPolymorphic:
2529    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2530      return RD->isPolymorphic();
2531    return false;
2532  case UTT_IsAbstract:
2533    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2534      return RD->isAbstract();
2535    return false;
2536  case UTT_IsSigned:
2537    return T->isSignedIntegerType();
2538  case UTT_IsUnsigned:
2539    return T->isUnsignedIntegerType();
2540
2541    // Type trait expressions which query classes regarding their construction,
2542    // destruction, and copying. Rather than being based directly on the
2543    // related type predicates in the standard, they are specified by both
2544    // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2545    // specifications.
2546    //
2547    //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2548    //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2549  case UTT_HasTrivialConstructor:
2550    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2551    //   If __is_pod (type) is true then the trait is true, else if type is
2552    //   a cv class or union type (or array thereof) with a trivial default
2553    //   constructor ([class.ctor]) then the trait is true, else it is false.
2554    if (T->isPODType())
2555      return true;
2556    if (const RecordType *RT =
2557          C.getBaseElementType(T)->getAs<RecordType>())
2558      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2559    return false;
2560  case UTT_HasTrivialCopy:
2561    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2562    //   If __is_pod (type) is true or type is a reference type then
2563    //   the trait is true, else if type is a cv class or union type
2564    //   with a trivial copy constructor ([class.copy]) then the trait
2565    //   is true, else it is false.
2566    if (T->isPODType() || T->isReferenceType())
2567      return true;
2568    if (const RecordType *RT = T->getAs<RecordType>())
2569      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2570    return false;
2571  case UTT_HasTrivialAssign:
2572    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2573    //   If type is const qualified or is a reference type then the
2574    //   trait is false. Otherwise if __is_pod (type) is true then the
2575    //   trait is true, else if type is a cv class or union type with
2576    //   a trivial copy assignment ([class.copy]) then the trait is
2577    //   true, else it is false.
2578    // Note: the const and reference restrictions are interesting,
2579    // given that const and reference members don't prevent a class
2580    // from having a trivial copy assignment operator (but do cause
2581    // errors if the copy assignment operator is actually used, q.v.
2582    // [class.copy]p12).
2583
2584    if (C.getBaseElementType(T).isConstQualified())
2585      return false;
2586    if (T->isPODType())
2587      return true;
2588    if (const RecordType *RT = T->getAs<RecordType>())
2589      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2590    return false;
2591  case UTT_HasTrivialDestructor:
2592    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2593    //   If __is_pod (type) is true or type is a reference type
2594    //   then the trait is true, else if type is a cv class or union
2595    //   type (or array thereof) with a trivial destructor
2596    //   ([class.dtor]) then the trait is true, else it is
2597    //   false.
2598    if (T->isPODType() || T->isReferenceType())
2599      return true;
2600    if (const RecordType *RT =
2601          C.getBaseElementType(T)->getAs<RecordType>())
2602      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2603    return false;
2604  // TODO: Propagate nothrowness for implicitly declared special members.
2605  case UTT_HasNothrowAssign:
2606    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2607    //   If type is const qualified or is a reference type then the
2608    //   trait is false. Otherwise if __has_trivial_assign (type)
2609    //   is true then the trait is true, else if type is a cv class
2610    //   or union type with copy assignment operators that are known
2611    //   not to throw an exception then the trait is true, else it is
2612    //   false.
2613    if (C.getBaseElementType(T).isConstQualified())
2614      return false;
2615    if (T->isReferenceType())
2616      return false;
2617    if (T->isPODType())
2618      return true;
2619    if (const RecordType *RT = T->getAs<RecordType>()) {
2620      CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2621      if (RD->hasTrivialCopyAssignment())
2622        return true;
2623
2624      bool FoundAssign = false;
2625      bool AllNoThrow = true;
2626      DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
2627      LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2628                       Sema::LookupOrdinaryName);
2629      if (Self.LookupQualifiedName(Res, RD)) {
2630        for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2631             Op != OpEnd; ++Op) {
2632          CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2633          if (Operator->isCopyAssignmentOperator()) {
2634            FoundAssign = true;
2635            const FunctionProtoType *CPT
2636                = Operator->getType()->getAs<FunctionProtoType>();
2637            if (!CPT->isNothrow(Self.Context)) {
2638              AllNoThrow = false;
2639              break;
2640            }
2641          }
2642        }
2643      }
2644
2645      return FoundAssign && AllNoThrow;
2646    }
2647    return false;
2648  case UTT_HasNothrowCopy:
2649    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2650    //   If __has_trivial_copy (type) is true then the trait is true, else
2651    //   if type is a cv class or union type with copy constructors that are
2652    //   known not to throw an exception then the trait is true, else it is
2653    //   false.
2654    if (T->isPODType() || T->isReferenceType())
2655      return true;
2656    if (const RecordType *RT = T->getAs<RecordType>()) {
2657      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2658      if (RD->hasTrivialCopyConstructor())
2659        return true;
2660
2661      bool FoundConstructor = false;
2662      bool AllNoThrow = true;
2663      unsigned FoundTQs;
2664      DeclContext::lookup_const_iterator Con, ConEnd;
2665      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2666           Con != ConEnd; ++Con) {
2667        // A template constructor is never a copy constructor.
2668        // FIXME: However, it may actually be selected at the actual overload
2669        // resolution point.
2670        if (isa<FunctionTemplateDecl>(*Con))
2671          continue;
2672        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2673        if (Constructor->isCopyConstructor(FoundTQs)) {
2674          FoundConstructor = true;
2675          const FunctionProtoType *CPT
2676              = Constructor->getType()->getAs<FunctionProtoType>();
2677          // FIXME: check whether evaluating default arguments can throw.
2678          // For now, we'll be conservative and assume that they can throw.
2679          if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) {
2680            AllNoThrow = false;
2681            break;
2682          }
2683        }
2684      }
2685
2686      return FoundConstructor && AllNoThrow;
2687    }
2688    return false;
2689  case UTT_HasNothrowConstructor:
2690    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2691    //   If __has_trivial_constructor (type) is true then the trait is
2692    //   true, else if type is a cv class or union type (or array
2693    //   thereof) with a default constructor that is known not to
2694    //   throw an exception then the trait is true, else it is false.
2695    if (T->isPODType())
2696      return true;
2697    if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2698      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2699      if (RD->hasTrivialConstructor())
2700        return true;
2701
2702      DeclContext::lookup_const_iterator Con, ConEnd;
2703      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2704           Con != ConEnd; ++Con) {
2705        // FIXME: In C++0x, a constructor template can be a default constructor.
2706        if (isa<FunctionTemplateDecl>(*Con))
2707          continue;
2708        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2709        if (Constructor->isDefaultConstructor()) {
2710          const FunctionProtoType *CPT
2711              = Constructor->getType()->getAs<FunctionProtoType>();
2712          // TODO: check whether evaluating default arguments can throw.
2713          // For now, we'll be conservative and assume that they can throw.
2714          return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
2715        }
2716      }
2717    }
2718    return false;
2719  case UTT_HasVirtualDestructor:
2720    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2721    //   If type is a class type with a virtual destructor ([class.dtor])
2722    //   then the trait is true, else it is false.
2723    if (const RecordType *Record = T->getAs<RecordType>()) {
2724      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2725      if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
2726        return Destructor->isVirtual();
2727    }
2728    return false;
2729
2730    // These type trait expressions are modeled on the specifications for the
2731    // Embarcadero C++0x type trait functions:
2732    //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2733  case UTT_IsCompleteType:
2734    // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2735    //   Returns True if and only if T is a complete type at the point of the
2736    //   function call.
2737    return !T->isIncompleteType();
2738  }
2739  llvm_unreachable("Type trait not covered by switch");
2740}
2741
2742ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
2743                                     SourceLocation KWLoc,
2744                                     TypeSourceInfo *TSInfo,
2745                                     SourceLocation RParen) {
2746  QualType T = TSInfo->getType();
2747  if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2748    return ExprError();
2749
2750  bool Value = false;
2751  if (!T->isDependentType())
2752    Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
2753
2754  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
2755                                                RParen, Context.BoolTy));
2756}
2757
2758ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2759                                      SourceLocation KWLoc,
2760                                      ParsedType LhsTy,
2761                                      ParsedType RhsTy,
2762                                      SourceLocation RParen) {
2763  TypeSourceInfo *LhsTSInfo;
2764  QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2765  if (!LhsTSInfo)
2766    LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2767
2768  TypeSourceInfo *RhsTSInfo;
2769  QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2770  if (!RhsTSInfo)
2771    RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2772
2773  return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2774}
2775
2776static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2777                                    QualType LhsT, QualType RhsT,
2778                                    SourceLocation KeyLoc) {
2779  assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
2780         "Cannot evaluate traits of dependent types");
2781
2782  switch(BTT) {
2783  case BTT_IsBaseOf: {
2784    // C++0x [meta.rel]p2
2785    // Base is a base class of Derived without regard to cv-qualifiers or
2786    // Base and Derived are not unions and name the same class type without
2787    // regard to cv-qualifiers.
2788
2789    const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2790    if (!lhsRecord) return false;
2791
2792    const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2793    if (!rhsRecord) return false;
2794
2795    assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2796             == (lhsRecord == rhsRecord));
2797
2798    if (lhsRecord == rhsRecord)
2799      return !lhsRecord->getDecl()->isUnion();
2800
2801    // C++0x [meta.rel]p2:
2802    //   If Base and Derived are class types and are different types
2803    //   (ignoring possible cv-qualifiers) then Derived shall be a
2804    //   complete type.
2805    if (Self.RequireCompleteType(KeyLoc, RhsT,
2806                          diag::err_incomplete_type_used_in_type_trait_expr))
2807      return false;
2808
2809    return cast<CXXRecordDecl>(rhsRecord->getDecl())
2810      ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2811  }
2812  case BTT_IsSame:
2813    return Self.Context.hasSameType(LhsT, RhsT);
2814  case BTT_TypeCompatible:
2815    return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2816                                           RhsT.getUnqualifiedType());
2817  case BTT_IsConvertible:
2818  case BTT_IsConvertibleTo: {
2819    // C++0x [meta.rel]p4:
2820    //   Given the following function prototype:
2821    //
2822    //     template <class T>
2823    //       typename add_rvalue_reference<T>::type create();
2824    //
2825    //   the predicate condition for a template specialization
2826    //   is_convertible<From, To> shall be satisfied if and only if
2827    //   the return expression in the following code would be
2828    //   well-formed, including any implicit conversions to the return
2829    //   type of the function:
2830    //
2831    //     To test() {
2832    //       return create<From>();
2833    //     }
2834    //
2835    //   Access checking is performed as if in a context unrelated to To and
2836    //   From. Only the validity of the immediate context of the expression
2837    //   of the return-statement (including conversions to the return type)
2838    //   is considered.
2839    //
2840    // We model the initialization as a copy-initialization of a temporary
2841    // of the appropriate type, which for this expression is identical to the
2842    // return statement (since NRVO doesn't apply).
2843    if (LhsT->isObjectType() || LhsT->isFunctionType())
2844      LhsT = Self.Context.getRValueReferenceType(LhsT);
2845
2846    InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
2847    OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
2848                         Expr::getValueKindForType(LhsT));
2849    Expr *FromPtr = &From;
2850    InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2851                                                           SourceLocation()));
2852
2853    // Perform the initialization within a SFINAE trap at translation unit
2854    // scope.
2855    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2856    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
2857    InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2858    if (Init.getKind() == InitializationSequence::FailedSequence)
2859      return false;
2860
2861    ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2862    return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2863  }
2864  }
2865  llvm_unreachable("Unknown type trait or not implemented");
2866}
2867
2868ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2869                                      SourceLocation KWLoc,
2870                                      TypeSourceInfo *LhsTSInfo,
2871                                      TypeSourceInfo *RhsTSInfo,
2872                                      SourceLocation RParen) {
2873  QualType LhsT = LhsTSInfo->getType();
2874  QualType RhsT = RhsTSInfo->getType();
2875
2876  if (BTT == BTT_TypeCompatible) {
2877    if (getLangOptions().CPlusPlus) {
2878      Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2879        << SourceRange(KWLoc, RParen);
2880      return ExprError();
2881    }
2882  }
2883
2884  bool Value = false;
2885  if (!LhsT->isDependentType() && !RhsT->isDependentType())
2886    Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2887
2888  // Select trait result type.
2889  QualType ResultType;
2890  switch (BTT) {
2891  case BTT_IsBaseOf:       ResultType = Context.BoolTy; break;
2892  case BTT_IsConvertible:  ResultType = Context.BoolTy; break;
2893  case BTT_IsSame:         ResultType = Context.BoolTy; break;
2894  case BTT_TypeCompatible: ResultType = Context.IntTy; break;
2895  case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
2896  }
2897
2898  return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2899                                                 RhsTSInfo, Value, RParen,
2900                                                 ResultType));
2901}
2902
2903ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
2904                                     SourceLocation KWLoc,
2905                                     ParsedType Ty,
2906                                     Expr* DimExpr,
2907                                     SourceLocation RParen) {
2908  TypeSourceInfo *TSInfo;
2909  QualType T = GetTypeFromParser(Ty, &TSInfo);
2910  if (!TSInfo)
2911    TSInfo = Context.getTrivialTypeSourceInfo(T);
2912
2913  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
2914}
2915
2916static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
2917                                           QualType T, Expr *DimExpr,
2918                                           SourceLocation KeyLoc) {
2919  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
2920
2921  switch(ATT) {
2922  case ATT_ArrayRank:
2923    if (T->isArrayType()) {
2924      unsigned Dim = 0;
2925      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2926        ++Dim;
2927        T = AT->getElementType();
2928      }
2929      return Dim;
2930    }
2931    return 0;
2932
2933  case ATT_ArrayExtent: {
2934    llvm::APSInt Value;
2935    uint64_t Dim;
2936    if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
2937      if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
2938        Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2939          DimExpr->getSourceRange();
2940        return false;
2941      }
2942      Dim = Value.getLimitedValue();
2943    } else {
2944      Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2945        DimExpr->getSourceRange();
2946      return false;
2947    }
2948
2949    if (T->isArrayType()) {
2950      unsigned D = 0;
2951      bool Matched = false;
2952      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2953        if (Dim == D) {
2954          Matched = true;
2955          break;
2956        }
2957        ++D;
2958        T = AT->getElementType();
2959      }
2960
2961      if (Matched && T->isArrayType()) {
2962        if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
2963          return CAT->getSize().getLimitedValue();
2964      }
2965    }
2966    return 0;
2967  }
2968  }
2969  llvm_unreachable("Unknown type trait or not implemented");
2970}
2971
2972ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
2973                                     SourceLocation KWLoc,
2974                                     TypeSourceInfo *TSInfo,
2975                                     Expr* DimExpr,
2976                                     SourceLocation RParen) {
2977  QualType T = TSInfo->getType();
2978
2979  // FIXME: This should likely be tracked as an APInt to remove any host
2980  // assumptions about the width of size_t on the target.
2981  uint64_t Value = 0;
2982  if (!T->isDependentType())
2983    Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
2984
2985  // While the specification for these traits from the Embarcadero C++
2986  // compiler's documentation says the return type is 'unsigned int', Clang
2987  // returns 'size_t'. On Windows, the primary platform for the Embarcadero
2988  // compiler, there is no difference. On several other platforms this is an
2989  // important distinction.
2990  return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
2991                                                DimExpr, RParen,
2992                                                Context.getSizeType()));
2993}
2994
2995ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
2996                                      SourceLocation KWLoc,
2997                                      Expr *Queried,
2998                                      SourceLocation RParen) {
2999  // If error parsing the expression, ignore.
3000  if (!Queried)
3001    return ExprError();
3002
3003  ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
3004
3005  return move(Result);
3006}
3007
3008static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3009  switch (ET) {
3010  case ET_IsLValueExpr: return E->isLValue();
3011  case ET_IsRValueExpr: return E->isRValue();
3012  }
3013  llvm_unreachable("Expression trait not covered by switch");
3014}
3015
3016ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
3017                                      SourceLocation KWLoc,
3018                                      Expr *Queried,
3019                                      SourceLocation RParen) {
3020  if (Queried->isTypeDependent()) {
3021    // Delay type-checking for type-dependent expressions.
3022  } else if (Queried->getType()->isPlaceholderType()) {
3023    ExprResult PE = CheckPlaceholderExpr(Queried);
3024    if (PE.isInvalid()) return ExprError();
3025    return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3026  }
3027
3028  bool Value = EvaluateExpressionTrait(ET, Queried);
3029
3030  return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3031                                                 RParen, Context.BoolTy));
3032}
3033
3034QualType Sema::CheckPointerToMemberOperands(ExprResult &lex, ExprResult &rex,
3035                                            ExprValueKind &VK,
3036                                            SourceLocation Loc,
3037                                            bool isIndirect) {
3038  const char *OpSpelling = isIndirect ? "->*" : ".*";
3039  // C++ 5.5p2
3040  //   The binary operator .* [p3: ->*] binds its second operand, which shall
3041  //   be of type "pointer to member of T" (where T is a completely-defined
3042  //   class type) [...]
3043  QualType RType = rex.get()->getType();
3044  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
3045  if (!MemPtr) {
3046    Diag(Loc, diag::err_bad_memptr_rhs)
3047      << OpSpelling << RType << rex.get()->getSourceRange();
3048    return QualType();
3049  }
3050
3051  QualType Class(MemPtr->getClass(), 0);
3052
3053  // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3054  // member pointer points must be completely-defined. However, there is no
3055  // reason for this semantic distinction, and the rule is not enforced by
3056  // other compilers. Therefore, we do not check this property, as it is
3057  // likely to be considered a defect.
3058
3059  // C++ 5.5p2
3060  //   [...] to its first operand, which shall be of class T or of a class of
3061  //   which T is an unambiguous and accessible base class. [p3: a pointer to
3062  //   such a class]
3063  QualType LType = lex.get()->getType();
3064  if (isIndirect) {
3065    if (const PointerType *Ptr = LType->getAs<PointerType>())
3066      LType = Ptr->getPointeeType();
3067    else {
3068      Diag(Loc, diag::err_bad_memptr_lhs)
3069        << OpSpelling << 1 << LType
3070        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
3071      return QualType();
3072    }
3073  }
3074
3075  if (!Context.hasSameUnqualifiedType(Class, LType)) {
3076    // If we want to check the hierarchy, we need a complete type.
3077    if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
3078        << OpSpelling << (int)isIndirect)) {
3079      return QualType();
3080    }
3081    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3082                       /*DetectVirtual=*/false);
3083    // FIXME: Would it be useful to print full ambiguity paths, or is that
3084    // overkill?
3085    if (!IsDerivedFrom(LType, Class, Paths) ||
3086        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3087      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
3088        << (int)isIndirect << lex.get()->getType();
3089      return QualType();
3090    }
3091    // Cast LHS to type of use.
3092    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
3093    ExprValueKind VK =
3094        isIndirect ? VK_RValue : CastCategory(lex.get());
3095
3096    CXXCastPath BasePath;
3097    BuildBasePathArray(Paths, BasePath);
3098    lex = ImpCastExprToType(lex.take(), UseType, CK_DerivedToBase, VK, &BasePath);
3099  }
3100
3101  if (isa<CXXScalarValueInitExpr>(rex.get()->IgnoreParens())) {
3102    // Diagnose use of pointer-to-member type which when used as
3103    // the functional cast in a pointer-to-member expression.
3104    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3105     return QualType();
3106  }
3107
3108  // C++ 5.5p2
3109  //   The result is an object or a function of the type specified by the
3110  //   second operand.
3111  // The cv qualifiers are the union of those in the pointer and the left side,
3112  // in accordance with 5.5p5 and 5.2.5.
3113  QualType Result = MemPtr->getPointeeType();
3114  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
3115
3116  // C++0x [expr.mptr.oper]p6:
3117  //   In a .* expression whose object expression is an rvalue, the program is
3118  //   ill-formed if the second operand is a pointer to member function with
3119  //   ref-qualifier &. In a ->* expression or in a .* expression whose object
3120  //   expression is an lvalue, the program is ill-formed if the second operand
3121  //   is a pointer to member function with ref-qualifier &&.
3122  if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3123    switch (Proto->getRefQualifier()) {
3124    case RQ_None:
3125      // Do nothing
3126      break;
3127
3128    case RQ_LValue:
3129      if (!isIndirect && !lex.get()->Classify(Context).isLValue())
3130        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3131          << RType << 1 << lex.get()->getSourceRange();
3132      break;
3133
3134    case RQ_RValue:
3135      if (isIndirect || !lex.get()->Classify(Context).isRValue())
3136        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3137          << RType << 0 << lex.get()->getSourceRange();
3138      break;
3139    }
3140  }
3141
3142  // C++ [expr.mptr.oper]p6:
3143  //   The result of a .* expression whose second operand is a pointer
3144  //   to a data member is of the same value category as its
3145  //   first operand. The result of a .* expression whose second
3146  //   operand is a pointer to a member function is a prvalue. The
3147  //   result of an ->* expression is an lvalue if its second operand
3148  //   is a pointer to data member and a prvalue otherwise.
3149  if (Result->isFunctionType()) {
3150    VK = VK_RValue;
3151    return Context.BoundMemberTy;
3152  } else if (isIndirect) {
3153    VK = VK_LValue;
3154  } else {
3155    VK = lex.get()->getValueKind();
3156  }
3157
3158  return Result;
3159}
3160
3161/// \brief Try to convert a type to another according to C++0x 5.16p3.
3162///
3163/// This is part of the parameter validation for the ? operator. If either
3164/// value operand is a class type, the two operands are attempted to be
3165/// converted to each other. This function does the conversion in one direction.
3166/// It returns true if the program is ill-formed and has already been diagnosed
3167/// as such.
3168static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3169                                SourceLocation QuestionLoc,
3170                                bool &HaveConversion,
3171                                QualType &ToType) {
3172  HaveConversion = false;
3173  ToType = To->getType();
3174
3175  InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
3176                                                           SourceLocation());
3177  // C++0x 5.16p3
3178  //   The process for determining whether an operand expression E1 of type T1
3179  //   can be converted to match an operand expression E2 of type T2 is defined
3180  //   as follows:
3181  //   -- If E2 is an lvalue:
3182  bool ToIsLvalue = To->isLValue();
3183  if (ToIsLvalue) {
3184    //   E1 can be converted to match E2 if E1 can be implicitly converted to
3185    //   type "lvalue reference to T2", subject to the constraint that in the
3186    //   conversion the reference must bind directly to E1.
3187    QualType T = Self.Context.getLValueReferenceType(ToType);
3188    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3189
3190    InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3191    if (InitSeq.isDirectReferenceBinding()) {
3192      ToType = T;
3193      HaveConversion = true;
3194      return false;
3195    }
3196
3197    if (InitSeq.isAmbiguous())
3198      return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3199  }
3200
3201  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
3202  //      -- if E1 and E2 have class type, and the underlying class types are
3203  //         the same or one is a base class of the other:
3204  QualType FTy = From->getType();
3205  QualType TTy = To->getType();
3206  const RecordType *FRec = FTy->getAs<RecordType>();
3207  const RecordType *TRec = TTy->getAs<RecordType>();
3208  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
3209                       Self.IsDerivedFrom(FTy, TTy);
3210  if (FRec && TRec &&
3211      (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
3212    //         E1 can be converted to match E2 if the class of T2 is the
3213    //         same type as, or a base class of, the class of T1, and
3214    //         [cv2 > cv1].
3215    if (FRec == TRec || FDerivedFromT) {
3216      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
3217        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3218        InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3219        if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
3220          HaveConversion = true;
3221          return false;
3222        }
3223
3224        if (InitSeq.isAmbiguous())
3225          return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3226      }
3227    }
3228
3229    return false;
3230  }
3231
3232  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
3233  //        implicitly converted to the type that expression E2 would have
3234  //        if E2 were converted to an rvalue (or the type it has, if E2 is
3235  //        an rvalue).
3236  //
3237  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3238  // to the array-to-pointer or function-to-pointer conversions.
3239  if (!TTy->getAs<TagType>())
3240    TTy = TTy.getUnqualifiedType();
3241
3242  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3243  InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3244  HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
3245  ToType = TTy;
3246  if (InitSeq.isAmbiguous())
3247    return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3248
3249  return false;
3250}
3251
3252/// \brief Try to find a common type for two according to C++0x 5.16p5.
3253///
3254/// This is part of the parameter validation for the ? operator. If either
3255/// value operand is a class type, overload resolution is used to find a
3256/// conversion to a common type.
3257static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
3258                                    SourceLocation QuestionLoc) {
3259  Expr *Args[2] = { LHS.get(), RHS.get() };
3260  OverloadCandidateSet CandidateSet(QuestionLoc);
3261  Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3262                                    CandidateSet);
3263
3264  OverloadCandidateSet::iterator Best;
3265  switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
3266    case OR_Success: {
3267      // We found a match. Perform the conversions on the arguments and move on.
3268      ExprResult LHSRes =
3269        Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3270                                       Best->Conversions[0], Sema::AA_Converting);
3271      if (LHSRes.isInvalid())
3272        break;
3273      LHS = move(LHSRes);
3274
3275      ExprResult RHSRes =
3276        Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3277                                       Best->Conversions[1], Sema::AA_Converting);
3278      if (RHSRes.isInvalid())
3279        break;
3280      RHS = move(RHSRes);
3281      if (Best->Function)
3282        Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
3283      return false;
3284    }
3285
3286    case OR_No_Viable_Function:
3287
3288      // Emit a better diagnostic if one of the expressions is a null pointer
3289      // constant and the other is a pointer type. In this case, the user most
3290      // likely forgot to take the address of the other expression.
3291      if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3292        return true;
3293
3294      Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3295        << LHS.get()->getType() << RHS.get()->getType()
3296        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3297      return true;
3298
3299    case OR_Ambiguous:
3300      Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
3301        << LHS.get()->getType() << RHS.get()->getType()
3302        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3303      // FIXME: Print the possible common types by printing the return types of
3304      // the viable candidates.
3305      break;
3306
3307    case OR_Deleted:
3308      assert(false && "Conditional operator has only built-in overloads");
3309      break;
3310  }
3311  return true;
3312}
3313
3314/// \brief Perform an "extended" implicit conversion as returned by
3315/// TryClassUnification.
3316static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
3317  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3318  InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
3319                                                           SourceLocation());
3320  Expr *Arg = E.take();
3321  InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3322  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
3323  if (Result.isInvalid())
3324    return true;
3325
3326  E = Result;
3327  return false;
3328}
3329
3330/// \brief Check the operands of ?: under C++ semantics.
3331///
3332/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3333/// extension. In this case, LHS == Cond. (But they're not aliases.)
3334QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
3335                                           ExprValueKind &VK, ExprObjectKind &OK,
3336                                           SourceLocation QuestionLoc) {
3337  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3338  // interface pointers.
3339
3340  // C++0x 5.16p1
3341  //   The first expression is contextually converted to bool.
3342  if (!Cond.get()->isTypeDependent()) {
3343    ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3344    if (CondRes.isInvalid())
3345      return QualType();
3346    Cond = move(CondRes);
3347  }
3348
3349  // Assume r-value.
3350  VK = VK_RValue;
3351  OK = OK_Ordinary;
3352
3353  // Either of the arguments dependent?
3354  if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
3355    return Context.DependentTy;
3356
3357  // C++0x 5.16p2
3358  //   If either the second or the third operand has type (cv) void, ...
3359  QualType LTy = LHS.get()->getType();
3360  QualType RTy = RHS.get()->getType();
3361  bool LVoid = LTy->isVoidType();
3362  bool RVoid = RTy->isVoidType();
3363  if (LVoid || RVoid) {
3364    //   ... then the [l2r] conversions are performed on the second and third
3365    //   operands ...
3366    LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3367    RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3368    if (LHS.isInvalid() || RHS.isInvalid())
3369      return QualType();
3370    LTy = LHS.get()->getType();
3371    RTy = RHS.get()->getType();
3372
3373    //   ... and one of the following shall hold:
3374    //   -- The second or the third operand (but not both) is a throw-
3375    //      expression; the result is of the type of the other and is an rvalue.
3376    bool LThrow = isa<CXXThrowExpr>(LHS.get());
3377    bool RThrow = isa<CXXThrowExpr>(RHS.get());
3378    if (LThrow && !RThrow)
3379      return RTy;
3380    if (RThrow && !LThrow)
3381      return LTy;
3382
3383    //   -- Both the second and third operands have type void; the result is of
3384    //      type void and is an rvalue.
3385    if (LVoid && RVoid)
3386      return Context.VoidTy;
3387
3388    // Neither holds, error.
3389    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3390      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3391      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3392    return QualType();
3393  }
3394
3395  // Neither is void.
3396
3397  // C++0x 5.16p3
3398  //   Otherwise, if the second and third operand have different types, and
3399  //   either has (cv) class type, and attempt is made to convert each of those
3400  //   operands to the other.
3401  if (!Context.hasSameType(LTy, RTy) &&
3402      (LTy->isRecordType() || RTy->isRecordType())) {
3403    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3404    // These return true if a single direction is already ambiguous.
3405    QualType L2RType, R2LType;
3406    bool HaveL2R, HaveR2L;
3407    if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
3408      return QualType();
3409    if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
3410      return QualType();
3411
3412    //   If both can be converted, [...] the program is ill-formed.
3413    if (HaveL2R && HaveR2L) {
3414      Diag(QuestionLoc, diag::err_conditional_ambiguous)
3415        << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3416      return QualType();
3417    }
3418
3419    //   If exactly one conversion is possible, that conversion is applied to
3420    //   the chosen operand and the converted operands are used in place of the
3421    //   original operands for the remainder of this section.
3422    if (HaveL2R) {
3423      if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
3424        return QualType();
3425      LTy = LHS.get()->getType();
3426    } else if (HaveR2L) {
3427      if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
3428        return QualType();
3429      RTy = RHS.get()->getType();
3430    }
3431  }
3432
3433  // C++0x 5.16p4
3434  //   If the second and third operands are glvalues of the same value
3435  //   category and have the same type, the result is of that type and
3436  //   value category and it is a bit-field if the second or the third
3437  //   operand is a bit-field, or if both are bit-fields.
3438  // We only extend this to bitfields, not to the crazy other kinds of
3439  // l-values.
3440  bool Same = Context.hasSameType(LTy, RTy);
3441  if (Same &&
3442      LHS.get()->isGLValue() &&
3443      LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3444      LHS.get()->isOrdinaryOrBitFieldObject() &&
3445      RHS.get()->isOrdinaryOrBitFieldObject()) {
3446    VK = LHS.get()->getValueKind();
3447    if (LHS.get()->getObjectKind() == OK_BitField ||
3448        RHS.get()->getObjectKind() == OK_BitField)
3449      OK = OK_BitField;
3450    return LTy;
3451  }
3452
3453  // C++0x 5.16p5
3454  //   Otherwise, the result is an rvalue. If the second and third operands
3455  //   do not have the same type, and either has (cv) class type, ...
3456  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3457    //   ... overload resolution is used to determine the conversions (if any)
3458    //   to be applied to the operands. If the overload resolution fails, the
3459    //   program is ill-formed.
3460    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3461      return QualType();
3462  }
3463
3464  // C++0x 5.16p6
3465  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3466  //   conversions are performed on the second and third operands.
3467  LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3468  RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3469  if (LHS.isInvalid() || RHS.isInvalid())
3470    return QualType();
3471  LTy = LHS.get()->getType();
3472  RTy = RHS.get()->getType();
3473
3474  //   After those conversions, one of the following shall hold:
3475  //   -- The second and third operands have the same type; the result
3476  //      is of that type. If the operands have class type, the result
3477  //      is a prvalue temporary of the result type, which is
3478  //      copy-initialized from either the second operand or the third
3479  //      operand depending on the value of the first operand.
3480  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3481    if (LTy->isRecordType()) {
3482      // The operands have class type. Make a temporary copy.
3483      InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
3484      ExprResult LHSCopy = PerformCopyInitialization(Entity,
3485                                                     SourceLocation(),
3486                                                     LHS);
3487      if (LHSCopy.isInvalid())
3488        return QualType();
3489
3490      ExprResult RHSCopy = PerformCopyInitialization(Entity,
3491                                                     SourceLocation(),
3492                                                     RHS);
3493      if (RHSCopy.isInvalid())
3494        return QualType();
3495
3496      LHS = LHSCopy;
3497      RHS = RHSCopy;
3498    }
3499
3500    return LTy;
3501  }
3502
3503  // Extension: conditional operator involving vector types.
3504  if (LTy->isVectorType() || RTy->isVectorType())
3505    return CheckVectorOperands(QuestionLoc, LHS, RHS);
3506
3507  //   -- The second and third operands have arithmetic or enumeration type;
3508  //      the usual arithmetic conversions are performed to bring them to a
3509  //      common type, and the result is of that type.
3510  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3511    UsualArithmeticConversions(LHS, RHS);
3512    if (LHS.isInvalid() || RHS.isInvalid())
3513      return QualType();
3514    return LHS.get()->getType();
3515  }
3516
3517  //   -- The second and third operands have pointer type, or one has pointer
3518  //      type and the other is a null pointer constant; pointer conversions
3519  //      and qualification conversions are performed to bring them to their
3520  //      composite pointer type. The result is of the composite pointer type.
3521  //   -- The second and third operands have pointer to member type, or one has
3522  //      pointer to member type and the other is a null pointer constant;
3523  //      pointer to member conversions and qualification conversions are
3524  //      performed to bring them to a common type, whose cv-qualification
3525  //      shall match the cv-qualification of either the second or the third
3526  //      operand. The result is of the common type.
3527  bool NonStandardCompositeType = false;
3528  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
3529                              isSFINAEContext()? 0 : &NonStandardCompositeType);
3530  if (!Composite.isNull()) {
3531    if (NonStandardCompositeType)
3532      Diag(QuestionLoc,
3533           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3534        << LTy << RTy << Composite
3535        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3536
3537    return Composite;
3538  }
3539
3540  // Similarly, attempt to find composite type of two objective-c pointers.
3541  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3542  if (!Composite.isNull())
3543    return Composite;
3544
3545  // Check if we are using a null with a non-pointer type.
3546  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3547    return QualType();
3548
3549  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3550    << LHS.get()->getType() << RHS.get()->getType()
3551    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3552  return QualType();
3553}
3554
3555/// \brief Find a merged pointer type and convert the two expressions to it.
3556///
3557/// This finds the composite pointer type (or member pointer type) for @p E1
3558/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3559/// type and returns it.
3560/// It does not emit diagnostics.
3561///
3562/// \param Loc The location of the operator requiring these two expressions to
3563/// be converted to the composite pointer type.
3564///
3565/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3566/// a non-standard (but still sane) composite type to which both expressions
3567/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3568/// will be set true.
3569QualType Sema::FindCompositePointerType(SourceLocation Loc,
3570                                        Expr *&E1, Expr *&E2,
3571                                        bool *NonStandardCompositeType) {
3572  if (NonStandardCompositeType)
3573    *NonStandardCompositeType = false;
3574
3575  assert(getLangOptions().CPlusPlus && "This function assumes C++");
3576  QualType T1 = E1->getType(), T2 = E2->getType();
3577
3578  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3579      !T2->isAnyPointerType() && !T2->isMemberPointerType())
3580   return QualType();
3581
3582  // C++0x 5.9p2
3583  //   Pointer conversions and qualification conversions are performed on
3584  //   pointer operands to bring them to their composite pointer type. If
3585  //   one operand is a null pointer constant, the composite pointer type is
3586  //   the type of the other operand.
3587  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3588    if (T2->isMemberPointerType())
3589      E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
3590    else
3591      E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
3592    return T2;
3593  }
3594  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3595    if (T1->isMemberPointerType())
3596      E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
3597    else
3598      E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
3599    return T1;
3600  }
3601
3602  // Now both have to be pointers or member pointers.
3603  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3604      (!T2->isPointerType() && !T2->isMemberPointerType()))
3605    return QualType();
3606
3607  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
3608  //   the other has type "pointer to cv2 T" and the composite pointer type is
3609  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3610  //   Otherwise, the composite pointer type is a pointer type similar to the
3611  //   type of one of the operands, with a cv-qualification signature that is
3612  //   the union of the cv-qualification signatures of the operand types.
3613  // In practice, the first part here is redundant; it's subsumed by the second.
3614  // What we do here is, we build the two possible composite types, and try the
3615  // conversions in both directions. If only one works, or if the two composite
3616  // types are the same, we have succeeded.
3617  // FIXME: extended qualifiers?
3618  typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3619  QualifierVector QualifierUnion;
3620  typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3621      ContainingClassVector;
3622  ContainingClassVector MemberOfClass;
3623  QualType Composite1 = Context.getCanonicalType(T1),
3624           Composite2 = Context.getCanonicalType(T2);
3625  unsigned NeedConstBefore = 0;
3626  do {
3627    const PointerType *Ptr1, *Ptr2;
3628    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3629        (Ptr2 = Composite2->getAs<PointerType>())) {
3630      Composite1 = Ptr1->getPointeeType();
3631      Composite2 = Ptr2->getPointeeType();
3632
3633      // If we're allowed to create a non-standard composite type, keep track
3634      // of where we need to fill in additional 'const' qualifiers.
3635      if (NonStandardCompositeType &&
3636          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3637        NeedConstBefore = QualifierUnion.size();
3638
3639      QualifierUnion.push_back(
3640                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3641      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3642      continue;
3643    }
3644
3645    const MemberPointerType *MemPtr1, *MemPtr2;
3646    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3647        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3648      Composite1 = MemPtr1->getPointeeType();
3649      Composite2 = MemPtr2->getPointeeType();
3650
3651      // If we're allowed to create a non-standard composite type, keep track
3652      // of where we need to fill in additional 'const' qualifiers.
3653      if (NonStandardCompositeType &&
3654          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3655        NeedConstBefore = QualifierUnion.size();
3656
3657      QualifierUnion.push_back(
3658                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3659      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3660                                             MemPtr2->getClass()));
3661      continue;
3662    }
3663
3664    // FIXME: block pointer types?
3665
3666    // Cannot unwrap any more types.
3667    break;
3668  } while (true);
3669
3670  if (NeedConstBefore && NonStandardCompositeType) {
3671    // Extension: Add 'const' to qualifiers that come before the first qualifier
3672    // mismatch, so that our (non-standard!) composite type meets the
3673    // requirements of C++ [conv.qual]p4 bullet 3.
3674    for (unsigned I = 0; I != NeedConstBefore; ++I) {
3675      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3676        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3677        *NonStandardCompositeType = true;
3678      }
3679    }
3680  }
3681
3682  // Rewrap the composites as pointers or member pointers with the union CVRs.
3683  ContainingClassVector::reverse_iterator MOC
3684    = MemberOfClass.rbegin();
3685  for (QualifierVector::reverse_iterator
3686         I = QualifierUnion.rbegin(),
3687         E = QualifierUnion.rend();
3688       I != E; (void)++I, ++MOC) {
3689    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
3690    if (MOC->first && MOC->second) {
3691      // Rebuild member pointer type
3692      Composite1 = Context.getMemberPointerType(
3693                                    Context.getQualifiedType(Composite1, Quals),
3694                                    MOC->first);
3695      Composite2 = Context.getMemberPointerType(
3696                                    Context.getQualifiedType(Composite2, Quals),
3697                                    MOC->second);
3698    } else {
3699      // Rebuild pointer type
3700      Composite1
3701        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3702      Composite2
3703        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
3704    }
3705  }
3706
3707  // Try to convert to the first composite pointer type.
3708  InitializedEntity Entity1
3709    = InitializedEntity::InitializeTemporary(Composite1);
3710  InitializationKind Kind
3711    = InitializationKind::CreateCopy(Loc, SourceLocation());
3712  InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3713  InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
3714
3715  if (E1ToC1 && E2ToC1) {
3716    // Conversion to Composite1 is viable.
3717    if (!Context.hasSameType(Composite1, Composite2)) {
3718      // Composite2 is a different type from Composite1. Check whether
3719      // Composite2 is also viable.
3720      InitializedEntity Entity2
3721        = InitializedEntity::InitializeTemporary(Composite2);
3722      InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3723      InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3724      if (E1ToC2 && E2ToC2) {
3725        // Both Composite1 and Composite2 are viable and are different;
3726        // this is an ambiguity.
3727        return QualType();
3728      }
3729    }
3730
3731    // Convert E1 to Composite1
3732    ExprResult E1Result
3733      = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
3734    if (E1Result.isInvalid())
3735      return QualType();
3736    E1 = E1Result.takeAs<Expr>();
3737
3738    // Convert E2 to Composite1
3739    ExprResult E2Result
3740      = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
3741    if (E2Result.isInvalid())
3742      return QualType();
3743    E2 = E2Result.takeAs<Expr>();
3744
3745    return Composite1;
3746  }
3747
3748  // Check whether Composite2 is viable.
3749  InitializedEntity Entity2
3750    = InitializedEntity::InitializeTemporary(Composite2);
3751  InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3752  InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3753  if (!E1ToC2 || !E2ToC2)
3754    return QualType();
3755
3756  // Convert E1 to Composite2
3757  ExprResult E1Result
3758    = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
3759  if (E1Result.isInvalid())
3760    return QualType();
3761  E1 = E1Result.takeAs<Expr>();
3762
3763  // Convert E2 to Composite2
3764  ExprResult E2Result
3765    = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
3766  if (E2Result.isInvalid())
3767    return QualType();
3768  E2 = E2Result.takeAs<Expr>();
3769
3770  return Composite2;
3771}
3772
3773ExprResult Sema::MaybeBindToTemporary(Expr *E) {
3774  if (!E)
3775    return ExprError();
3776
3777  if (!Context.getLangOptions().CPlusPlus)
3778    return Owned(E);
3779
3780  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3781
3782  const RecordType *RT = E->getType()->getAs<RecordType>();
3783  if (!RT)
3784    return Owned(E);
3785
3786  // If the result is a glvalue, we shouldn't bind it.
3787  if (E->Classify(Context).isGLValue())
3788    return Owned(E);
3789
3790  // That should be enough to guarantee that this type is complete.
3791  // If it has a trivial destructor, we can avoid the extra copy.
3792  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3793  if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
3794    return Owned(E);
3795
3796  CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
3797  ExprTemporaries.push_back(Temp);
3798  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
3799    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
3800    CheckDestructorAccess(E->getExprLoc(), Destructor,
3801                          PDiag(diag::err_access_dtor_temp)
3802                            << E->getType());
3803  }
3804  // FIXME: Add the temporary to the temporaries vector.
3805  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3806}
3807
3808Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
3809  assert(SubExpr && "sub expression can't be null!");
3810
3811  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3812  assert(ExprTemporaries.size() >= FirstTemporary);
3813  if (ExprTemporaries.size() == FirstTemporary)
3814    return SubExpr;
3815
3816  Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3817                                     &ExprTemporaries[FirstTemporary],
3818                                     ExprTemporaries.size() - FirstTemporary);
3819  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3820                        ExprTemporaries.end());
3821
3822  return E;
3823}
3824
3825ExprResult
3826Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
3827  if (SubExpr.isInvalid())
3828    return ExprError();
3829
3830  return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
3831}
3832
3833Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
3834  assert(SubStmt && "sub statement can't be null!");
3835
3836  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3837  assert(ExprTemporaries.size() >= FirstTemporary);
3838  if (ExprTemporaries.size() == FirstTemporary)
3839    return SubStmt;
3840
3841  // FIXME: In order to attach the temporaries, wrap the statement into
3842  // a StmtExpr; currently this is only used for asm statements.
3843  // This is hacky, either create a new CXXStmtWithTemporaries statement or
3844  // a new AsmStmtWithTemporaries.
3845  CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3846                                                      SourceLocation(),
3847                                                      SourceLocation());
3848  Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3849                                   SourceLocation());
3850  return MaybeCreateExprWithCleanups(E);
3851}
3852
3853ExprResult
3854Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
3855                                   tok::TokenKind OpKind, ParsedType &ObjectType,
3856                                   bool &MayBePseudoDestructor) {
3857  // Since this might be a postfix expression, get rid of ParenListExprs.
3858  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3859  if (Result.isInvalid()) return ExprError();
3860  Base = Result.get();
3861
3862  QualType BaseType = Base->getType();
3863  MayBePseudoDestructor = false;
3864  if (BaseType->isDependentType()) {
3865    // If we have a pointer to a dependent type and are using the -> operator,
3866    // the object type is the type that the pointer points to. We might still
3867    // have enough information about that type to do something useful.
3868    if (OpKind == tok::arrow)
3869      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3870        BaseType = Ptr->getPointeeType();
3871
3872    ObjectType = ParsedType::make(BaseType);
3873    MayBePseudoDestructor = true;
3874    return Owned(Base);
3875  }
3876
3877  // C++ [over.match.oper]p8:
3878  //   [...] When operator->returns, the operator-> is applied  to the value
3879  //   returned, with the original second operand.
3880  if (OpKind == tok::arrow) {
3881    // The set of types we've considered so far.
3882    llvm::SmallPtrSet<CanQualType,8> CTypes;
3883    llvm::SmallVector<SourceLocation, 8> Locations;
3884    CTypes.insert(Context.getCanonicalType(BaseType));
3885
3886    while (BaseType->isRecordType()) {
3887      Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3888      if (Result.isInvalid())
3889        return ExprError();
3890      Base = Result.get();
3891      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
3892        Locations.push_back(OpCall->getDirectCallee()->getLocation());
3893      BaseType = Base->getType();
3894      CanQualType CBaseType = Context.getCanonicalType(BaseType);
3895      if (!CTypes.insert(CBaseType)) {
3896        Diag(OpLoc, diag::err_operator_arrow_circular);
3897        for (unsigned i = 0; i < Locations.size(); i++)
3898          Diag(Locations[i], diag::note_declared_at);
3899        return ExprError();
3900      }
3901    }
3902
3903    if (BaseType->isPointerType())
3904      BaseType = BaseType->getPointeeType();
3905  }
3906
3907  // We could end up with various non-record types here, such as extended
3908  // vector types or Objective-C interfaces. Just return early and let
3909  // ActOnMemberReferenceExpr do the work.
3910  if (!BaseType->isRecordType()) {
3911    // C++ [basic.lookup.classref]p2:
3912    //   [...] If the type of the object expression is of pointer to scalar
3913    //   type, the unqualified-id is looked up in the context of the complete
3914    //   postfix-expression.
3915    //
3916    // This also indicates that we should be parsing a
3917    // pseudo-destructor-name.
3918    ObjectType = ParsedType();
3919    MayBePseudoDestructor = true;
3920    return Owned(Base);
3921  }
3922
3923  // The object type must be complete (or dependent).
3924  if (!BaseType->isDependentType() &&
3925      RequireCompleteType(OpLoc, BaseType,
3926                          PDiag(diag::err_incomplete_member_access)))
3927    return ExprError();
3928
3929  // C++ [basic.lookup.classref]p2:
3930  //   If the id-expression in a class member access (5.2.5) is an
3931  //   unqualified-id, and the type of the object expression is of a class
3932  //   type C (or of pointer to a class type C), the unqualified-id is looked
3933  //   up in the scope of class C. [...]
3934  ObjectType = ParsedType::make(BaseType);
3935  return move(Base);
3936}
3937
3938ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
3939                                                   Expr *MemExpr) {
3940  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
3941  Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3942    << isa<CXXPseudoDestructorExpr>(MemExpr)
3943    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
3944
3945  return ActOnCallExpr(/*Scope*/ 0,
3946                       MemExpr,
3947                       /*LPLoc*/ ExpectedLParenLoc,
3948                       MultiExprArg(),
3949                       /*RPLoc*/ ExpectedLParenLoc);
3950}
3951
3952ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
3953                                           SourceLocation OpLoc,
3954                                           tok::TokenKind OpKind,
3955                                           const CXXScopeSpec &SS,
3956                                           TypeSourceInfo *ScopeTypeInfo,
3957                                           SourceLocation CCLoc,
3958                                           SourceLocation TildeLoc,
3959                                         PseudoDestructorTypeStorage Destructed,
3960                                           bool HasTrailingLParen) {
3961  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
3962
3963  // C++ [expr.pseudo]p2:
3964  //   The left-hand side of the dot operator shall be of scalar type. The
3965  //   left-hand side of the arrow operator shall be of pointer to scalar type.
3966  //   This scalar type is the object type.
3967  QualType ObjectType = Base->getType();
3968  if (OpKind == tok::arrow) {
3969    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3970      ObjectType = Ptr->getPointeeType();
3971    } else if (!Base->isTypeDependent()) {
3972      // The user wrote "p->" when she probably meant "p."; fix it.
3973      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3974        << ObjectType << true
3975        << FixItHint::CreateReplacement(OpLoc, ".");
3976      if (isSFINAEContext())
3977        return ExprError();
3978
3979      OpKind = tok::period;
3980    }
3981  }
3982
3983  if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3984    Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
3985      << ObjectType << Base->getSourceRange();
3986    return ExprError();
3987  }
3988
3989  // C++ [expr.pseudo]p2:
3990  //   [...] The cv-unqualified versions of the object type and of the type
3991  //   designated by the pseudo-destructor-name shall be the same type.
3992  if (DestructedTypeInfo) {
3993    QualType DestructedType = DestructedTypeInfo->getType();
3994    SourceLocation DestructedTypeStart
3995      = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
3996    if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3997        !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3998      Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
3999        << ObjectType << DestructedType << Base->getSourceRange()
4000        << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4001
4002      // Recover by setting the destructed type to the object type.
4003      DestructedType = ObjectType;
4004      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4005                                                           DestructedTypeStart);
4006      Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4007    }
4008  }
4009
4010  // C++ [expr.pseudo]p2:
4011  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4012  //   form
4013  //
4014  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
4015  //
4016  //   shall designate the same scalar type.
4017  if (ScopeTypeInfo) {
4018    QualType ScopeType = ScopeTypeInfo->getType();
4019    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
4020        !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
4021
4022      Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
4023           diag::err_pseudo_dtor_type_mismatch)
4024        << ObjectType << ScopeType << Base->getSourceRange()
4025        << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
4026
4027      ScopeType = QualType();
4028      ScopeTypeInfo = 0;
4029    }
4030  }
4031
4032  Expr *Result
4033    = new (Context) CXXPseudoDestructorExpr(Context, Base,
4034                                            OpKind == tok::arrow, OpLoc,
4035                                            SS.getWithLocInContext(Context),
4036                                            ScopeTypeInfo,
4037                                            CCLoc,
4038                                            TildeLoc,
4039                                            Destructed);
4040
4041  if (HasTrailingLParen)
4042    return Owned(Result);
4043
4044  return DiagnoseDtorReference(Destructed.getLocation(), Result);
4045}
4046
4047ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4048                                           SourceLocation OpLoc,
4049                                           tok::TokenKind OpKind,
4050                                           CXXScopeSpec &SS,
4051                                           UnqualifiedId &FirstTypeName,
4052                                           SourceLocation CCLoc,
4053                                           SourceLocation TildeLoc,
4054                                           UnqualifiedId &SecondTypeName,
4055                                           bool HasTrailingLParen) {
4056  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4057          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4058         "Invalid first type name in pseudo-destructor");
4059  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4060          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4061         "Invalid second type name in pseudo-destructor");
4062
4063  // C++ [expr.pseudo]p2:
4064  //   The left-hand side of the dot operator shall be of scalar type. The
4065  //   left-hand side of the arrow operator shall be of pointer to scalar type.
4066  //   This scalar type is the object type.
4067  QualType ObjectType = Base->getType();
4068  if (OpKind == tok::arrow) {
4069    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4070      ObjectType = Ptr->getPointeeType();
4071    } else if (!ObjectType->isDependentType()) {
4072      // The user wrote "p->" when she probably meant "p."; fix it.
4073      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4074        << ObjectType << true
4075        << FixItHint::CreateReplacement(OpLoc, ".");
4076      if (isSFINAEContext())
4077        return ExprError();
4078
4079      OpKind = tok::period;
4080    }
4081  }
4082
4083  // Compute the object type that we should use for name lookup purposes. Only
4084  // record types and dependent types matter.
4085  ParsedType ObjectTypePtrForLookup;
4086  if (!SS.isSet()) {
4087    if (ObjectType->isRecordType())
4088      ObjectTypePtrForLookup = ParsedType::make(ObjectType);
4089    else if (ObjectType->isDependentType())
4090      ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
4091  }
4092
4093  // Convert the name of the type being destructed (following the ~) into a
4094  // type (with source-location information).
4095  QualType DestructedType;
4096  TypeSourceInfo *DestructedTypeInfo = 0;
4097  PseudoDestructorTypeStorage Destructed;
4098  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
4099    ParsedType T = getTypeName(*SecondTypeName.Identifier,
4100                               SecondTypeName.StartLocation,
4101                               S, &SS, true, false, ObjectTypePtrForLookup);
4102    if (!T &&
4103        ((SS.isSet() && !computeDeclContext(SS, false)) ||
4104         (!SS.isSet() && ObjectType->isDependentType()))) {
4105      // The name of the type being destroyed is a dependent name, and we
4106      // couldn't find anything useful in scope. Just store the identifier and
4107      // it's location, and we'll perform (qualified) name lookup again at
4108      // template instantiation time.
4109      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4110                                               SecondTypeName.StartLocation);
4111    } else if (!T) {
4112      Diag(SecondTypeName.StartLocation,
4113           diag::err_pseudo_dtor_destructor_non_type)
4114        << SecondTypeName.Identifier << ObjectType;
4115      if (isSFINAEContext())
4116        return ExprError();
4117
4118      // Recover by assuming we had the right type all along.
4119      DestructedType = ObjectType;
4120    } else
4121      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
4122  } else {
4123    // Resolve the template-id to a type.
4124    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
4125    ASTTemplateArgsPtr TemplateArgsPtr(*this,
4126                                       TemplateId->getTemplateArgs(),
4127                                       TemplateId->NumArgs);
4128    TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4129                                       TemplateId->Template,
4130                                       TemplateId->TemplateNameLoc,
4131                                       TemplateId->LAngleLoc,
4132                                       TemplateArgsPtr,
4133                                       TemplateId->RAngleLoc);
4134    if (T.isInvalid() || !T.get()) {
4135      // Recover by assuming we had the right type all along.
4136      DestructedType = ObjectType;
4137    } else
4138      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
4139  }
4140
4141  // If we've performed some kind of recovery, (re-)build the type source
4142  // information.
4143  if (!DestructedType.isNull()) {
4144    if (!DestructedTypeInfo)
4145      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
4146                                                  SecondTypeName.StartLocation);
4147    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4148  }
4149
4150  // Convert the name of the scope type (the type prior to '::') into a type.
4151  TypeSourceInfo *ScopeTypeInfo = 0;
4152  QualType ScopeType;
4153  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4154      FirstTypeName.Identifier) {
4155    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
4156      ParsedType T = getTypeName(*FirstTypeName.Identifier,
4157                                 FirstTypeName.StartLocation,
4158                                 S, &SS, true, false, ObjectTypePtrForLookup);
4159      if (!T) {
4160        Diag(FirstTypeName.StartLocation,
4161             diag::err_pseudo_dtor_destructor_non_type)
4162          << FirstTypeName.Identifier << ObjectType;
4163
4164        if (isSFINAEContext())
4165          return ExprError();
4166
4167        // Just drop this type. It's unnecessary anyway.
4168        ScopeType = QualType();
4169      } else
4170        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
4171    } else {
4172      // Resolve the template-id to a type.
4173      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
4174      ASTTemplateArgsPtr TemplateArgsPtr(*this,
4175                                         TemplateId->getTemplateArgs(),
4176                                         TemplateId->NumArgs);
4177      TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4178                                         TemplateId->Template,
4179                                         TemplateId->TemplateNameLoc,
4180                                         TemplateId->LAngleLoc,
4181                                         TemplateArgsPtr,
4182                                         TemplateId->RAngleLoc);
4183      if (T.isInvalid() || !T.get()) {
4184        // Recover by dropping this type.
4185        ScopeType = QualType();
4186      } else
4187        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
4188    }
4189  }
4190
4191  if (!ScopeType.isNull() && !ScopeTypeInfo)
4192    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4193                                                  FirstTypeName.StartLocation);
4194
4195
4196  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
4197                                   ScopeTypeInfo, CCLoc, TildeLoc,
4198                                   Destructed, HasTrailingLParen);
4199}
4200
4201ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
4202                                        CXXMethodDecl *Method) {
4203  ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4204                                          FoundDecl, Method);
4205  if (Exp.isInvalid())
4206    return true;
4207
4208  MemberExpr *ME =
4209      new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
4210                               SourceLocation(), Method->getType(),
4211                               VK_RValue, OK_Ordinary);
4212  QualType ResultType = Method->getResultType();
4213  ExprValueKind VK = Expr::getValueKindForType(ResultType);
4214  ResultType = ResultType.getNonLValueExprType(Context);
4215
4216  MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
4217  CXXMemberCallExpr *CE =
4218    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
4219                                    Exp.get()->getLocEnd());
4220  return CE;
4221}
4222
4223ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4224                                      SourceLocation RParen) {
4225  return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4226                                             Operand->CanThrow(Context),
4227                                             KeyLoc, RParen));
4228}
4229
4230ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4231                                   Expr *Operand, SourceLocation RParen) {
4232  return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
4233}
4234
4235/// Perform the conversions required for an expression used in a
4236/// context that ignores the result.
4237ExprResult Sema::IgnoredValueConversions(Expr *E) {
4238  // C99 6.3.2.1:
4239  //   [Except in specific positions,] an lvalue that does not have
4240  //   array type is converted to the value stored in the
4241  //   designated object (and is no longer an lvalue).
4242  if (E->isRValue()) return Owned(E);
4243
4244  // We always want to do this on ObjC property references.
4245  if (E->getObjectKind() == OK_ObjCProperty) {
4246    ExprResult Res = ConvertPropertyForRValue(E);
4247    if (Res.isInvalid()) return Owned(E);
4248    E = Res.take();
4249    if (E->isRValue()) return Owned(E);
4250  }
4251
4252  // Otherwise, this rule does not apply in C++, at least not for the moment.
4253  if (getLangOptions().CPlusPlus) return Owned(E);
4254
4255  // GCC seems to also exclude expressions of incomplete enum type.
4256  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4257    if (!T->getDecl()->isComplete()) {
4258      // FIXME: stupid workaround for a codegen bug!
4259      E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4260      return Owned(E);
4261    }
4262  }
4263
4264  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4265  if (Res.isInvalid())
4266    return Owned(E);
4267  E = Res.take();
4268
4269  if (!E->getType()->isVoidType())
4270    RequireCompleteType(E->getExprLoc(), E->getType(),
4271                        diag::err_incomplete_type);
4272  return Owned(E);
4273}
4274
4275ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4276  ExprResult FullExpr = Owned(FE);
4277
4278  if (!FullExpr.get())
4279    return ExprError();
4280
4281  if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
4282    return ExprError();
4283
4284  FullExpr = CheckPlaceholderExpr(FullExpr.take());
4285  if (FullExpr.isInvalid())
4286    return ExprError();
4287
4288  FullExpr = IgnoredValueConversions(FullExpr.take());
4289  if (FullExpr.isInvalid())
4290    return ExprError();
4291
4292  CheckImplicitConversions(FullExpr.get());
4293  return MaybeCreateExprWithCleanups(FullExpr);
4294}
4295
4296StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4297  if (!FullStmt) return StmtError();
4298
4299  return MaybeCreateStmtWithCleanups(FullStmt);
4300}
4301