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 /// \file
11 /// \brief Implements semantic analysis for C++ expressions.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Sema/SemaInternal.h"
16 #include "TypeLocBuilder.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/ParsedTemplate.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/SemaLambda.h"
36 #include "clang/Sema/TemplateDeduction.h"
37 #include "llvm/ADT/APInt.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/Support/ErrorHandling.h"
40 using namespace clang;
41 using namespace sema;
42 
43 /// \brief Handle the result of the special case name lookup for inheriting
44 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
45 /// constructor names in member using declarations, even if 'X' is not the
46 /// name of the corresponding type.
47 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
48                                               SourceLocation NameLoc,
49                                               IdentifierInfo &Name) {
50   NestedNameSpecifier *NNS = SS.getScopeRep();
51 
52   // Convert the nested-name-specifier into a type.
53   QualType Type;
54   switch (NNS->getKind()) {
55   case NestedNameSpecifier::TypeSpec:
56   case NestedNameSpecifier::TypeSpecWithTemplate:
57     Type = QualType(NNS->getAsType(), 0);
58     break;
59 
60   case NestedNameSpecifier::Identifier:
61     // Strip off the last layer of the nested-name-specifier and build a
62     // typename type for it.
63     assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
64     Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
65                                         NNS->getAsIdentifier());
66     break;
67 
68   case NestedNameSpecifier::Global:
69   case NestedNameSpecifier::Namespace:
70   case NestedNameSpecifier::NamespaceAlias:
71     llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
72   }
73 
74   // This reference to the type is located entirely at the location of the
75   // final identifier in the qualified-id.
76   return CreateParsedType(Type,
77                           Context.getTrivialTypeSourceInfo(Type, NameLoc));
78 }
79 
80 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
81                                    IdentifierInfo &II,
82                                    SourceLocation NameLoc,
83                                    Scope *S, CXXScopeSpec &SS,
84                                    ParsedType ObjectTypePtr,
85                                    bool EnteringContext) {
86   // Determine where to perform name lookup.
87 
88   // FIXME: This area of the standard is very messy, and the current
89   // wording is rather unclear about which scopes we search for the
90   // destructor name; see core issues 399 and 555. Issue 399 in
91   // particular shows where the current description of destructor name
92   // lookup is completely out of line with existing practice, e.g.,
93   // this appears to be ill-formed:
94   //
95   //   namespace N {
96   //     template <typename T> struct S {
97   //       ~S();
98   //     };
99   //   }
100   //
101   //   void f(N::S<int>* s) {
102   //     s->N::S<int>::~S();
103   //   }
104   //
105   // See also PR6358 and PR6359.
106   // For this reason, we're currently only doing the C++03 version of this
107   // code; the C++0x version has to wait until we get a proper spec.
108   QualType SearchType;
109   DeclContext *LookupCtx = 0;
110   bool isDependent = false;
111   bool LookInScope = false;
112 
113   // If we have an object type, it's because we are in a
114   // pseudo-destructor-expression or a member access expression, and
115   // we know what type we're looking for.
116   if (ObjectTypePtr)
117     SearchType = GetTypeFromParser(ObjectTypePtr);
118 
119   if (SS.isSet()) {
120     NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
121 
122     bool AlreadySearched = false;
123     bool LookAtPrefix = true;
124     // C++ [basic.lookup.qual]p6:
125     //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
126     //   the type-names are looked up as types in the scope designated by the
127     //   nested-name-specifier. In a qualified-id of the form:
128     //
129     //     ::[opt] nested-name-specifier  ~ class-name
130     //
131     //   where the nested-name-specifier designates a namespace scope, and in
132     //   a qualified-id of the form:
133     //
134     //     ::opt nested-name-specifier class-name ::  ~ class-name
135     //
136     //   the class-names are looked up as types in the scope designated by
137     //   the nested-name-specifier.
138     //
139     // Here, we check the first case (completely) and determine whether the
140     // code below is permitted to look at the prefix of the
141     // nested-name-specifier.
142     DeclContext *DC = computeDeclContext(SS, EnteringContext);
143     if (DC && DC->isFileContext()) {
144       AlreadySearched = true;
145       LookupCtx = DC;
146       isDependent = false;
147     } else if (DC && isa<CXXRecordDecl>(DC))
148       LookAtPrefix = false;
149 
150     // The second case from the C++03 rules quoted further above.
151     NestedNameSpecifier *Prefix = 0;
152     if (AlreadySearched) {
153       // Nothing left to do.
154     } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155       CXXScopeSpec PrefixSS;
156       PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
157       LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158       isDependent = isDependentScopeSpecifier(PrefixSS);
159     } else if (ObjectTypePtr) {
160       LookupCtx = computeDeclContext(SearchType);
161       isDependent = SearchType->isDependentType();
162     } else {
163       LookupCtx = computeDeclContext(SS, EnteringContext);
164       isDependent = LookupCtx && LookupCtx->isDependentContext();
165     }
166 
167     LookInScope = false;
168   } else if (ObjectTypePtr) {
169     // C++ [basic.lookup.classref]p3:
170     //   If the unqualified-id is ~type-name, the type-name is looked up
171     //   in the context of the entire postfix-expression. If the type T
172     //   of the object expression is of a class type C, the type-name is
173     //   also looked up in the scope of class C. At least one of the
174     //   lookups shall find a name that refers to (possibly
175     //   cv-qualified) T.
176     LookupCtx = computeDeclContext(SearchType);
177     isDependent = SearchType->isDependentType();
178     assert((isDependent || !SearchType->isIncompleteType()) &&
179            "Caller should have completed object type");
180 
181     LookInScope = true;
182   } else {
183     // Perform lookup into the current scope (only).
184     LookInScope = true;
185   }
186 
187   TypeDecl *NonMatchingTypeDecl = 0;
188   LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
189   for (unsigned Step = 0; Step != 2; ++Step) {
190     // Look for the name first in the computed lookup context (if we
191     // have one) and, if that fails to find a match, in the scope (if
192     // we're allowed to look there).
193     Found.clear();
194     if (Step == 0 && LookupCtx)
195       LookupQualifiedName(Found, LookupCtx);
196     else if (Step == 1 && LookInScope && S)
197       LookupName(Found, S);
198     else
199       continue;
200 
201     // FIXME: Should we be suppressing ambiguities here?
202     if (Found.isAmbiguous())
203       return ParsedType();
204 
205     if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
206       QualType T = Context.getTypeDeclType(Type);
207 
208       if (SearchType.isNull() || SearchType->isDependentType() ||
209           Context.hasSameUnqualifiedType(T, SearchType)) {
210         // We found our type!
211 
212         return ParsedType::make(T);
213       }
214 
215       if (!SearchType.isNull())
216         NonMatchingTypeDecl = Type;
217     }
218 
219     // If the name that we found is a class template name, and it is
220     // the same name as the template name in the last part of the
221     // nested-name-specifier (if present) or the object type, then
222     // this is the destructor for that class.
223     // FIXME: This is a workaround until we get real drafting for core
224     // issue 399, for which there isn't even an obvious direction.
225     if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226       QualType MemberOfType;
227       if (SS.isSet()) {
228         if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229           // Figure out the type of the context, if it has one.
230           if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231             MemberOfType = Context.getTypeDeclType(Record);
232         }
233       }
234       if (MemberOfType.isNull())
235         MemberOfType = SearchType;
236 
237       if (MemberOfType.isNull())
238         continue;
239 
240       // We're referring into a class template specialization. If the
241       // class template we found is the same as the template being
242       // specialized, we found what we are looking for.
243       if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244         if (ClassTemplateSpecializationDecl *Spec
245               = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246           if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247                 Template->getCanonicalDecl())
248             return ParsedType::make(MemberOfType);
249         }
250 
251         continue;
252       }
253 
254       // We're referring to an unresolved class template
255       // specialization. Determine whether we class template we found
256       // is the same as the template being specialized or, if we don't
257       // know which template is being specialized, that it at least
258       // has the same name.
259       if (const TemplateSpecializationType *SpecType
260             = MemberOfType->getAs<TemplateSpecializationType>()) {
261         TemplateName SpecName = SpecType->getTemplateName();
262 
263         // The class template we found is the same template being
264         // specialized.
265         if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
266           if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
267             return ParsedType::make(MemberOfType);
268 
269           continue;
270         }
271 
272         // The class template we found has the same name as the
273         // (dependent) template name being specialized.
274         if (DependentTemplateName *DepTemplate
275                                     = SpecName.getAsDependentTemplateName()) {
276           if (DepTemplate->isIdentifier() &&
277               DepTemplate->getIdentifier() == Template->getIdentifier())
278             return ParsedType::make(MemberOfType);
279 
280           continue;
281         }
282       }
283     }
284   }
285 
286   if (isDependent) {
287     // We didn't find our type, but that's okay: it's dependent
288     // anyway.
289 
290     // FIXME: What if we have no nested-name-specifier?
291     QualType T = CheckTypenameType(ETK_None, SourceLocation(),
292                                    SS.getWithLocInContext(Context),
293                                    II, NameLoc);
294     return ParsedType::make(T);
295   }
296 
297   if (NonMatchingTypeDecl) {
298     QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
299     Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
300       << T << SearchType;
301     Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
302       << T;
303   } else if (ObjectTypePtr)
304     Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
305       << &II;
306   else {
307     SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
308                                           diag::err_destructor_class_name);
309     if (S) {
310       const DeclContext *Ctx = S->getEntity();
311       if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
312         DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
313                                                  Class->getNameAsString());
314     }
315   }
316 
317   return ParsedType();
318 }
319 
320 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
321     if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
322       return ParsedType();
323     assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
324            && "only get destructor types from declspecs");
325     QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
326     QualType SearchType = GetTypeFromParser(ObjectType);
327     if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
328       return ParsedType::make(T);
329     }
330 
331     Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
332       << T << SearchType;
333     return ParsedType();
334 }
335 
336 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
337                                   const UnqualifiedId &Name) {
338   assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
339 
340   if (!SS.isValid())
341     return false;
342 
343   switch (SS.getScopeRep()->getKind()) {
344   case NestedNameSpecifier::Identifier:
345   case NestedNameSpecifier::TypeSpec:
346   case NestedNameSpecifier::TypeSpecWithTemplate:
347     // Per C++11 [over.literal]p2, literal operators can only be declared at
348     // namespace scope. Therefore, this unqualified-id cannot name anything.
349     // Reject it early, because we have no AST representation for this in the
350     // case where the scope is dependent.
351     Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
352       << SS.getScopeRep();
353     return true;
354 
355   case NestedNameSpecifier::Global:
356   case NestedNameSpecifier::Namespace:
357   case NestedNameSpecifier::NamespaceAlias:
358     return false;
359   }
360 
361   llvm_unreachable("unknown nested name specifier kind");
362 }
363 
364 /// \brief Build a C++ typeid expression with a type operand.
365 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
366                                 SourceLocation TypeidLoc,
367                                 TypeSourceInfo *Operand,
368                                 SourceLocation RParenLoc) {
369   // C++ [expr.typeid]p4:
370   //   The top-level cv-qualifiers of the lvalue expression or the type-id
371   //   that is the operand of typeid are always ignored.
372   //   If the type of the type-id is a class type or a reference to a class
373   //   type, the class shall be completely-defined.
374   Qualifiers Quals;
375   QualType T
376     = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
377                                       Quals);
378   if (T->getAs<RecordType>() &&
379       RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
380     return ExprError();
381 
382   return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
383                                            Operand,
384                                            SourceRange(TypeidLoc, RParenLoc)));
385 }
386 
387 /// \brief Build a C++ typeid expression with an expression operand.
388 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
389                                 SourceLocation TypeidLoc,
390                                 Expr *E,
391                                 SourceLocation RParenLoc) {
392   if (E && !E->isTypeDependent()) {
393     if (E->getType()->isPlaceholderType()) {
394       ExprResult result = CheckPlaceholderExpr(E);
395       if (result.isInvalid()) return ExprError();
396       E = result.take();
397     }
398 
399     QualType T = E->getType();
400     if (const RecordType *RecordT = T->getAs<RecordType>()) {
401       CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
402       // C++ [expr.typeid]p3:
403       //   [...] If the type of the expression is a class type, the class
404       //   shall be completely-defined.
405       if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
406         return ExprError();
407 
408       // C++ [expr.typeid]p3:
409       //   When typeid is applied to an expression other than an glvalue of a
410       //   polymorphic class type [...] [the] expression is an unevaluated
411       //   operand. [...]
412       if (RecordD->isPolymorphic() && E->isGLValue()) {
413         // The subexpression is potentially evaluated; switch the context
414         // and recheck the subexpression.
415         ExprResult Result = TransformToPotentiallyEvaluated(E);
416         if (Result.isInvalid()) return ExprError();
417         E = Result.take();
418 
419         // We require a vtable to query the type at run time.
420         MarkVTableUsed(TypeidLoc, RecordD);
421       }
422     }
423 
424     // C++ [expr.typeid]p4:
425     //   [...] If the type of the type-id is a reference to a possibly
426     //   cv-qualified type, the result of the typeid expression refers to a
427     //   std::type_info object representing the cv-unqualified referenced
428     //   type.
429     Qualifiers Quals;
430     QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
431     if (!Context.hasSameType(T, UnqualT)) {
432       T = UnqualT;
433       E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
434     }
435   }
436 
437   return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
438                                            E,
439                                            SourceRange(TypeidLoc, RParenLoc)));
440 }
441 
442 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
443 ExprResult
444 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
445                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
446   // Find the std::type_info type.
447   if (!getStdNamespace())
448     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
449 
450   if (!CXXTypeInfoDecl) {
451     IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
452     LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
453     LookupQualifiedName(R, getStdNamespace());
454     CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
455     // Microsoft's typeinfo doesn't have type_info in std but in the global
456     // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
457     if (!CXXTypeInfoDecl && LangOpts.MicrosoftMode) {
458       LookupQualifiedName(R, Context.getTranslationUnitDecl());
459       CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
460     }
461     if (!CXXTypeInfoDecl)
462       return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
463   }
464 
465   if (!getLangOpts().RTTI) {
466     return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
467   }
468 
469   QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
470 
471   if (isType) {
472     // The operand is a type; handle it as such.
473     TypeSourceInfo *TInfo = 0;
474     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
475                                    &TInfo);
476     if (T.isNull())
477       return ExprError();
478 
479     if (!TInfo)
480       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
481 
482     return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
483   }
484 
485   // The operand is an expression.
486   return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
487 }
488 
489 /// \brief Build a Microsoft __uuidof expression with a type operand.
490 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
491                                 SourceLocation TypeidLoc,
492                                 TypeSourceInfo *Operand,
493                                 SourceLocation RParenLoc) {
494   if (!Operand->getType()->isDependentType()) {
495     bool HasMultipleGUIDs = false;
496     if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(),
497                                           &HasMultipleGUIDs)) {
498       if (HasMultipleGUIDs)
499         return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
500       else
501         return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
502     }
503   }
504 
505   return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
506                                            Operand,
507                                            SourceRange(TypeidLoc, RParenLoc)));
508 }
509 
510 /// \brief Build a Microsoft __uuidof expression with an expression operand.
511 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
512                                 SourceLocation TypeidLoc,
513                                 Expr *E,
514                                 SourceLocation RParenLoc) {
515   if (!E->getType()->isDependentType()) {
516     bool HasMultipleGUIDs = false;
517     if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) &&
518         !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
519       if (HasMultipleGUIDs)
520         return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
521       else
522         return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
523     }
524   }
525 
526   return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
527                                            E,
528                                            SourceRange(TypeidLoc, RParenLoc)));
529 }
530 
531 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
532 ExprResult
533 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
534                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
535   // If MSVCGuidDecl has not been cached, do the lookup.
536   if (!MSVCGuidDecl) {
537     IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
538     LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
539     LookupQualifiedName(R, Context.getTranslationUnitDecl());
540     MSVCGuidDecl = R.getAsSingle<RecordDecl>();
541     if (!MSVCGuidDecl)
542       return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
543   }
544 
545   QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
546 
547   if (isType) {
548     // The operand is a type; handle it as such.
549     TypeSourceInfo *TInfo = 0;
550     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
551                                    &TInfo);
552     if (T.isNull())
553       return ExprError();
554 
555     if (!TInfo)
556       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
557 
558     return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
559   }
560 
561   // The operand is an expression.
562   return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
563 }
564 
565 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
566 ExprResult
567 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
568   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
569          "Unknown C++ Boolean value!");
570   return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
571                                                 Context.BoolTy, OpLoc));
572 }
573 
574 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
575 ExprResult
576 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
577   return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
578 }
579 
580 /// ActOnCXXThrow - Parse throw expressions.
581 ExprResult
582 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
583   bool IsThrownVarInScope = false;
584   if (Ex) {
585     // C++0x [class.copymove]p31:
586     //   When certain criteria are met, an implementation is allowed to omit the
587     //   copy/move construction of a class object [...]
588     //
589     //     - in a throw-expression, when the operand is the name of a
590     //       non-volatile automatic object (other than a function or catch-
591     //       clause parameter) whose scope does not extend beyond the end of the
592     //       innermost enclosing try-block (if there is one), the copy/move
593     //       operation from the operand to the exception object (15.1) can be
594     //       omitted by constructing the automatic object directly into the
595     //       exception object
596     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
597       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
598         if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
599           for( ; S; S = S->getParent()) {
600             if (S->isDeclScope(Var)) {
601               IsThrownVarInScope = true;
602               break;
603             }
604 
605             if (S->getFlags() &
606                 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
607                  Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
608                  Scope::TryScope))
609               break;
610           }
611         }
612       }
613   }
614 
615   return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
616 }
617 
618 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
619                                bool IsThrownVarInScope) {
620   // Don't report an error if 'throw' is used in system headers.
621   if (!getLangOpts().CXXExceptions &&
622       !getSourceManager().isInSystemHeader(OpLoc))
623     Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
624 
625   if (Ex && !Ex->isTypeDependent()) {
626     ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
627     if (ExRes.isInvalid())
628       return ExprError();
629     Ex = ExRes.take();
630   }
631 
632   return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
633                                           IsThrownVarInScope));
634 }
635 
636 /// CheckCXXThrowOperand - Validate the operand of a throw.
637 ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
638                                       bool IsThrownVarInScope) {
639   // C++ [except.throw]p3:
640   //   A throw-expression initializes a temporary object, called the exception
641   //   object, the type of which is determined by removing any top-level
642   //   cv-qualifiers from the static type of the operand of throw and adjusting
643   //   the type from "array of T" or "function returning T" to "pointer to T"
644   //   or "pointer to function returning T", [...]
645   if (E->getType().hasQualifiers())
646     E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
647                           E->getValueKind()).take();
648 
649   ExprResult Res = DefaultFunctionArrayConversion(E);
650   if (Res.isInvalid())
651     return ExprError();
652   E = Res.take();
653 
654   //   If the type of the exception would be an incomplete type or a pointer
655   //   to an incomplete type other than (cv) void the program is ill-formed.
656   QualType Ty = E->getType();
657   bool isPointer = false;
658   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
659     Ty = Ptr->getPointeeType();
660     isPointer = true;
661   }
662   if (!isPointer || !Ty->isVoidType()) {
663     if (RequireCompleteType(ThrowLoc, Ty,
664                             isPointer? diag::err_throw_incomplete_ptr
665                                      : diag::err_throw_incomplete,
666                             E->getSourceRange()))
667       return ExprError();
668 
669     if (RequireNonAbstractType(ThrowLoc, E->getType(),
670                                diag::err_throw_abstract_type, E))
671       return ExprError();
672   }
673 
674   // Initialize the exception result.  This implicitly weeds out
675   // abstract types or types with inaccessible copy constructors.
676 
677   // C++0x [class.copymove]p31:
678   //   When certain criteria are met, an implementation is allowed to omit the
679   //   copy/move construction of a class object [...]
680   //
681   //     - in a throw-expression, when the operand is the name of a
682   //       non-volatile automatic object (other than a function or catch-clause
683   //       parameter) whose scope does not extend beyond the end of the
684   //       innermost enclosing try-block (if there is one), the copy/move
685   //       operation from the operand to the exception object (15.1) can be
686   //       omitted by constructing the automatic object directly into the
687   //       exception object
688   const VarDecl *NRVOVariable = 0;
689   if (IsThrownVarInScope)
690     NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
691 
692   InitializedEntity Entity =
693       InitializedEntity::InitializeException(ThrowLoc, E->getType(),
694                                              /*NRVO=*/NRVOVariable != 0);
695   Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
696                                         QualType(), E,
697                                         IsThrownVarInScope);
698   if (Res.isInvalid())
699     return ExprError();
700   E = Res.take();
701 
702   // If the exception has class type, we need additional handling.
703   const RecordType *RecordTy = Ty->getAs<RecordType>();
704   if (!RecordTy)
705     return Owned(E);
706   CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
707 
708   // If we are throwing a polymorphic class type or pointer thereof,
709   // exception handling will make use of the vtable.
710   MarkVTableUsed(ThrowLoc, RD);
711 
712   // If a pointer is thrown, the referenced object will not be destroyed.
713   if (isPointer)
714     return Owned(E);
715 
716   // If the class has a destructor, we must be able to call it.
717   if (RD->hasIrrelevantDestructor())
718     return Owned(E);
719 
720   CXXDestructorDecl *Destructor = LookupDestructor(RD);
721   if (!Destructor)
722     return Owned(E);
723 
724   MarkFunctionReferenced(E->getExprLoc(), Destructor);
725   CheckDestructorAccess(E->getExprLoc(), Destructor,
726                         PDiag(diag::err_access_dtor_exception) << Ty);
727   if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
728     return ExprError();
729   return Owned(E);
730 }
731 
732 QualType Sema::getCurrentThisType() {
733   DeclContext *DC = getFunctionLevelDeclContext();
734   QualType ThisTy = CXXThisTypeOverride;
735   if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
736     if (method && method->isInstance())
737       ThisTy = method->getThisType(Context);
738   }
739 
740   return ThisTy;
741 }
742 
743 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
744                                          Decl *ContextDecl,
745                                          unsigned CXXThisTypeQuals,
746                                          bool Enabled)
747   : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
748 {
749   if (!Enabled || !ContextDecl)
750     return;
751 
752   CXXRecordDecl *Record = 0;
753   if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
754     Record = Template->getTemplatedDecl();
755   else
756     Record = cast<CXXRecordDecl>(ContextDecl);
757 
758   S.CXXThisTypeOverride
759     = S.Context.getPointerType(
760         S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
761 
762   this->Enabled = true;
763 }
764 
765 
766 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
767   if (Enabled) {
768     S.CXXThisTypeOverride = OldCXXThisTypeOverride;
769   }
770 }
771 
772 static Expr *captureThis(ASTContext &Context, RecordDecl *RD,
773                          QualType ThisTy, SourceLocation Loc) {
774   FieldDecl *Field
775     = FieldDecl::Create(Context, RD, Loc, Loc, 0, ThisTy,
776                         Context.getTrivialTypeSourceInfo(ThisTy, Loc),
777                         0, false, ICIS_NoInit);
778   Field->setImplicit(true);
779   Field->setAccess(AS_private);
780   RD->addDecl(Field);
781   return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true);
782 }
783 
784 bool Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit,
785     bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt) {
786   // We don't need to capture this in an unevaluated context.
787   if (isUnevaluatedContext() && !Explicit)
788     return true;
789 
790   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
791     *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
792  // Otherwise, check that we can capture 'this'.
793   unsigned NumClosures = 0;
794   for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
795     if (CapturingScopeInfo *CSI =
796             dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
797       if (CSI->CXXThisCaptureIndex != 0) {
798         // 'this' is already being captured; there isn't anything more to do.
799         break;
800       }
801       LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
802       if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
803         // This context can't implicitly capture 'this'; fail out.
804         if (BuildAndDiagnose)
805           Diag(Loc, diag::err_this_capture) << Explicit;
806         return true;
807       }
808       if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
809           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
810           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
811           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
812           Explicit) {
813         // This closure can capture 'this'; continue looking upwards.
814         NumClosures++;
815         Explicit = false;
816         continue;
817       }
818       // This context can't implicitly capture 'this'; fail out.
819       if (BuildAndDiagnose)
820         Diag(Loc, diag::err_this_capture) << Explicit;
821       return true;
822     }
823     break;
824   }
825   if (!BuildAndDiagnose) return false;
826   // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
827   // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
828   // contexts.
829   for (unsigned idx = MaxFunctionScopesIndex; NumClosures;
830       --idx, --NumClosures) {
831     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
832     Expr *ThisExpr = 0;
833     QualType ThisTy = getCurrentThisType();
834     if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI))
835       // For lambda expressions, build a field and an initializing expression.
836       ThisExpr = captureThis(Context, LSI->Lambda, ThisTy, Loc);
837     else if (CapturedRegionScopeInfo *RSI
838         = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
839       ThisExpr = captureThis(Context, RSI->TheRecordDecl, ThisTy, Loc);
840 
841     bool isNested = NumClosures > 1;
842     CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
843   }
844   return false;
845 }
846 
847 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
848   /// C++ 9.3.2: In the body of a non-static member function, the keyword this
849   /// is a non-lvalue expression whose value is the address of the object for
850   /// which the function is called.
851 
852   QualType ThisTy = getCurrentThisType();
853   if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
854 
855   CheckCXXThisCapture(Loc);
856   return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
857 }
858 
859 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
860   // If we're outside the body of a member function, then we'll have a specified
861   // type for 'this'.
862   if (CXXThisTypeOverride.isNull())
863     return false;
864 
865   // Determine whether we're looking into a class that's currently being
866   // defined.
867   CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
868   return Class && Class->isBeingDefined();
869 }
870 
871 ExprResult
872 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
873                                 SourceLocation LParenLoc,
874                                 MultiExprArg exprs,
875                                 SourceLocation RParenLoc) {
876   if (!TypeRep)
877     return ExprError();
878 
879   TypeSourceInfo *TInfo;
880   QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
881   if (!TInfo)
882     TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
883 
884   return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
885 }
886 
887 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
888 /// Can be interpreted either as function-style casting ("int(x)")
889 /// or class type construction ("ClassType(x,y,z)")
890 /// or creation of a value-initialized type ("int()").
891 ExprResult
892 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
893                                 SourceLocation LParenLoc,
894                                 MultiExprArg Exprs,
895                                 SourceLocation RParenLoc) {
896   QualType Ty = TInfo->getType();
897   SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
898 
899   if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
900     return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
901                                                     LParenLoc,
902                                                     Exprs,
903                                                     RParenLoc));
904   }
905 
906   bool ListInitialization = LParenLoc.isInvalid();
907   assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
908          && "List initialization must have initializer list as expression.");
909   SourceRange FullRange = SourceRange(TyBeginLoc,
910       ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
911 
912   // C++ [expr.type.conv]p1:
913   // If the expression list is a single expression, the type conversion
914   // expression is equivalent (in definedness, and if defined in meaning) to the
915   // corresponding cast expression.
916   if (Exprs.size() == 1 && !ListInitialization) {
917     Expr *Arg = Exprs[0];
918     return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
919   }
920 
921   QualType ElemTy = Ty;
922   if (Ty->isArrayType()) {
923     if (!ListInitialization)
924       return ExprError(Diag(TyBeginLoc,
925                             diag::err_value_init_for_array_type) << FullRange);
926     ElemTy = Context.getBaseElementType(Ty);
927   }
928 
929   if (!Ty->isVoidType() &&
930       RequireCompleteType(TyBeginLoc, ElemTy,
931                           diag::err_invalid_incomplete_type_use, FullRange))
932     return ExprError();
933 
934   if (RequireNonAbstractType(TyBeginLoc, Ty,
935                              diag::err_allocation_of_abstract_type))
936     return ExprError();
937 
938   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
939   InitializationKind Kind =
940       Exprs.size() ? ListInitialization
941       ? InitializationKind::CreateDirectList(TyBeginLoc)
942       : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
943       : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
944   InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
945   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
946 
947   if (Result.isInvalid() || !ListInitialization)
948     return Result;
949 
950   Expr *Inner = Result.get();
951   if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
952     Inner = BTE->getSubExpr();
953   if (isa<InitListExpr>(Inner)) {
954     // If the list-initialization doesn't involve a constructor call, we'll get
955     // the initializer-list (with corrected type) back, but that's not what we
956     // want, since it will be treated as an initializer list in further
957     // processing. Explicitly insert a cast here.
958     QualType ResultType = Result.get()->getType();
959     Result = Owned(CXXFunctionalCastExpr::Create(
960         Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
961         CK_NoOp, Result.take(), /*Path=*/ 0, LParenLoc, RParenLoc));
962   }
963 
964   // FIXME: Improve AST representation?
965   return Result;
966 }
967 
968 /// doesUsualArrayDeleteWantSize - Answers whether the usual
969 /// operator delete[] for the given type has a size_t parameter.
970 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
971                                          QualType allocType) {
972   const RecordType *record =
973     allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
974   if (!record) return false;
975 
976   // Try to find an operator delete[] in class scope.
977 
978   DeclarationName deleteName =
979     S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
980   LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
981   S.LookupQualifiedName(ops, record->getDecl());
982 
983   // We're just doing this for information.
984   ops.suppressDiagnostics();
985 
986   // Very likely: there's no operator delete[].
987   if (ops.empty()) return false;
988 
989   // If it's ambiguous, it should be illegal to call operator delete[]
990   // on this thing, so it doesn't matter if we allocate extra space or not.
991   if (ops.isAmbiguous()) return false;
992 
993   LookupResult::Filter filter = ops.makeFilter();
994   while (filter.hasNext()) {
995     NamedDecl *del = filter.next()->getUnderlyingDecl();
996 
997     // C++0x [basic.stc.dynamic.deallocation]p2:
998     //   A template instance is never a usual deallocation function,
999     //   regardless of its signature.
1000     if (isa<FunctionTemplateDecl>(del)) {
1001       filter.erase();
1002       continue;
1003     }
1004 
1005     // C++0x [basic.stc.dynamic.deallocation]p2:
1006     //   If class T does not declare [an operator delete[] with one
1007     //   parameter] but does declare a member deallocation function
1008     //   named operator delete[] with exactly two parameters, the
1009     //   second of which has type std::size_t, then this function
1010     //   is a usual deallocation function.
1011     if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
1012       filter.erase();
1013       continue;
1014     }
1015   }
1016   filter.done();
1017 
1018   if (!ops.isSingleResult()) return false;
1019 
1020   const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
1021   return (del->getNumParams() == 2);
1022 }
1023 
1024 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
1025 ///
1026 /// E.g.:
1027 /// @code new (memory) int[size][4] @endcode
1028 /// or
1029 /// @code ::new Foo(23, "hello") @endcode
1030 ///
1031 /// \param StartLoc The first location of the expression.
1032 /// \param UseGlobal True if 'new' was prefixed with '::'.
1033 /// \param PlacementLParen Opening paren of the placement arguments.
1034 /// \param PlacementArgs Placement new arguments.
1035 /// \param PlacementRParen Closing paren of the placement arguments.
1036 /// \param TypeIdParens If the type is in parens, the source range.
1037 /// \param D The type to be allocated, as well as array dimensions.
1038 /// \param Initializer The initializing expression or initializer-list, or null
1039 ///   if there is none.
1040 ExprResult
1041 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1042                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1043                   SourceLocation PlacementRParen, SourceRange TypeIdParens,
1044                   Declarator &D, Expr *Initializer) {
1045   bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1046 
1047   Expr *ArraySize = 0;
1048   // If the specified type is an array, unwrap it and save the expression.
1049   if (D.getNumTypeObjects() > 0 &&
1050       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1051      DeclaratorChunk &Chunk = D.getTypeObject(0);
1052     if (TypeContainsAuto)
1053       return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1054         << D.getSourceRange());
1055     if (Chunk.Arr.hasStatic)
1056       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1057         << D.getSourceRange());
1058     if (!Chunk.Arr.NumElts)
1059       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1060         << D.getSourceRange());
1061 
1062     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1063     D.DropFirstTypeObject();
1064   }
1065 
1066   // Every dimension shall be of constant size.
1067   if (ArraySize) {
1068     for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1069       if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1070         break;
1071 
1072       DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1073       if (Expr *NumElts = (Expr *)Array.NumElts) {
1074         if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1075           if (getLangOpts().CPlusPlus1y) {
1076 	    // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1077 	    //   shall be a converted constant expression (5.19) of type std::size_t
1078 	    //   and shall evaluate to a strictly positive value.
1079             unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1080             assert(IntWidth && "Builtin type of size 0?");
1081             llvm::APSInt Value(IntWidth);
1082             Array.NumElts
1083              = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1084                                                 CCEK_NewExpr)
1085                  .take();
1086           } else {
1087             Array.NumElts
1088               = VerifyIntegerConstantExpression(NumElts, 0,
1089                                                 diag::err_new_array_nonconst)
1090                   .take();
1091           }
1092           if (!Array.NumElts)
1093             return ExprError();
1094         }
1095       }
1096     }
1097   }
1098 
1099   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
1100   QualType AllocType = TInfo->getType();
1101   if (D.isInvalidType())
1102     return ExprError();
1103 
1104   SourceRange DirectInitRange;
1105   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1106     DirectInitRange = List->getSourceRange();
1107 
1108   return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1109                      PlacementLParen,
1110                      PlacementArgs,
1111                      PlacementRParen,
1112                      TypeIdParens,
1113                      AllocType,
1114                      TInfo,
1115                      ArraySize,
1116                      DirectInitRange,
1117                      Initializer,
1118                      TypeContainsAuto);
1119 }
1120 
1121 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1122                                        Expr *Init) {
1123   if (!Init)
1124     return true;
1125   if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1126     return PLE->getNumExprs() == 0;
1127   if (isa<ImplicitValueInitExpr>(Init))
1128     return true;
1129   else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1130     return !CCE->isListInitialization() &&
1131            CCE->getConstructor()->isDefaultConstructor();
1132   else if (Style == CXXNewExpr::ListInit) {
1133     assert(isa<InitListExpr>(Init) &&
1134            "Shouldn't create list CXXConstructExprs for arrays.");
1135     return true;
1136   }
1137   return false;
1138 }
1139 
1140 ExprResult
1141 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1142                   SourceLocation PlacementLParen,
1143                   MultiExprArg PlacementArgs,
1144                   SourceLocation PlacementRParen,
1145                   SourceRange TypeIdParens,
1146                   QualType AllocType,
1147                   TypeSourceInfo *AllocTypeInfo,
1148                   Expr *ArraySize,
1149                   SourceRange DirectInitRange,
1150                   Expr *Initializer,
1151                   bool TypeMayContainAuto) {
1152   SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1153   SourceLocation StartLoc = Range.getBegin();
1154 
1155   CXXNewExpr::InitializationStyle initStyle;
1156   if (DirectInitRange.isValid()) {
1157     assert(Initializer && "Have parens but no initializer.");
1158     initStyle = CXXNewExpr::CallInit;
1159   } else if (Initializer && isa<InitListExpr>(Initializer))
1160     initStyle = CXXNewExpr::ListInit;
1161   else {
1162     assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1163             isa<CXXConstructExpr>(Initializer)) &&
1164            "Initializer expression that cannot have been implicitly created.");
1165     initStyle = CXXNewExpr::NoInit;
1166   }
1167 
1168   Expr **Inits = &Initializer;
1169   unsigned NumInits = Initializer ? 1 : 0;
1170   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1171     assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1172     Inits = List->getExprs();
1173     NumInits = List->getNumExprs();
1174   }
1175 
1176   // Determine whether we've already built the initializer.
1177   bool HaveCompleteInit = false;
1178   if (Initializer && isa<CXXConstructExpr>(Initializer) &&
1179       !isa<CXXTemporaryObjectExpr>(Initializer))
1180     HaveCompleteInit = true;
1181   else if (Initializer && isa<ImplicitValueInitExpr>(Initializer))
1182     HaveCompleteInit = true;
1183 
1184   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1185   if (TypeMayContainAuto && AllocType->isUndeducedType()) {
1186     if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1187       return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1188                        << AllocType << TypeRange);
1189     if (initStyle == CXXNewExpr::ListInit)
1190       return ExprError(Diag(Inits[0]->getLocStart(),
1191                             diag::err_auto_new_requires_parens)
1192                        << AllocType << TypeRange);
1193     if (NumInits > 1) {
1194       Expr *FirstBad = Inits[1];
1195       return ExprError(Diag(FirstBad->getLocStart(),
1196                             diag::err_auto_new_ctor_multiple_expressions)
1197                        << AllocType << TypeRange);
1198     }
1199     Expr *Deduce = Inits[0];
1200     QualType DeducedType;
1201     if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1202       return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1203                        << AllocType << Deduce->getType()
1204                        << TypeRange << Deduce->getSourceRange());
1205     if (DeducedType.isNull())
1206       return ExprError();
1207     AllocType = DeducedType;
1208   }
1209 
1210   // Per C++0x [expr.new]p5, the type being constructed may be a
1211   // typedef of an array type.
1212   if (!ArraySize) {
1213     if (const ConstantArrayType *Array
1214                               = Context.getAsConstantArrayType(AllocType)) {
1215       ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1216                                          Context.getSizeType(),
1217                                          TypeRange.getEnd());
1218       AllocType = Array->getElementType();
1219     }
1220   }
1221 
1222   if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1223     return ExprError();
1224 
1225   if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
1226     Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1227          diag::warn_dangling_std_initializer_list)
1228         << /*at end of FE*/0 << Inits[0]->getSourceRange();
1229   }
1230 
1231   // In ARC, infer 'retaining' for the allocated
1232   if (getLangOpts().ObjCAutoRefCount &&
1233       AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1234       AllocType->isObjCLifetimeType()) {
1235     AllocType = Context.getLifetimeQualifiedType(AllocType,
1236                                     AllocType->getObjCARCImplicitLifetime());
1237   }
1238 
1239   QualType ResultType = Context.getPointerType(AllocType);
1240 
1241   if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1242     ExprResult result = CheckPlaceholderExpr(ArraySize);
1243     if (result.isInvalid()) return ExprError();
1244     ArraySize = result.take();
1245   }
1246   // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1247   //   integral or enumeration type with a non-negative value."
1248   // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1249   //   enumeration type, or a class type for which a single non-explicit
1250   //   conversion function to integral or unscoped enumeration type exists.
1251   // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1252   //   std::size_t.
1253   if (ArraySize && !ArraySize->isTypeDependent()) {
1254     ExprResult ConvertedSize;
1255     if (getLangOpts().CPlusPlus1y) {
1256       assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1257 
1258       ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1259 						AA_Converting);
1260 
1261       if (!ConvertedSize.isInvalid() &&
1262           ArraySize->getType()->getAs<RecordType>())
1263         // Diagnose the compatibility of this conversion.
1264         Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1265           << ArraySize->getType() << 0 << "'size_t'";
1266     } else {
1267       class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1268       protected:
1269         Expr *ArraySize;
1270 
1271       public:
1272         SizeConvertDiagnoser(Expr *ArraySize)
1273             : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1274               ArraySize(ArraySize) {}
1275 
1276         virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1277                                                      QualType T) {
1278           return S.Diag(Loc, diag::err_array_size_not_integral)
1279                    << S.getLangOpts().CPlusPlus11 << T;
1280         }
1281 
1282         virtual SemaDiagnosticBuilder diagnoseIncomplete(
1283             Sema &S, SourceLocation Loc, QualType T) {
1284           return S.Diag(Loc, diag::err_array_size_incomplete_type)
1285                    << T << ArraySize->getSourceRange();
1286         }
1287 
1288         virtual SemaDiagnosticBuilder diagnoseExplicitConv(
1289             Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
1290           return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1291         }
1292 
1293         virtual SemaDiagnosticBuilder noteExplicitConv(
1294             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
1295           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1296                    << ConvTy->isEnumeralType() << ConvTy;
1297         }
1298 
1299         virtual SemaDiagnosticBuilder diagnoseAmbiguous(
1300             Sema &S, SourceLocation Loc, QualType T) {
1301           return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1302         }
1303 
1304         virtual SemaDiagnosticBuilder noteAmbiguous(
1305             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
1306           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1307                    << ConvTy->isEnumeralType() << ConvTy;
1308         }
1309 
1310         virtual SemaDiagnosticBuilder diagnoseConversion(
1311             Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
1312           return S.Diag(Loc,
1313                         S.getLangOpts().CPlusPlus11
1314                           ? diag::warn_cxx98_compat_array_size_conversion
1315                           : diag::ext_array_size_conversion)
1316                    << T << ConvTy->isEnumeralType() << ConvTy;
1317         }
1318       } SizeDiagnoser(ArraySize);
1319 
1320       ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1321                                                           SizeDiagnoser);
1322     }
1323     if (ConvertedSize.isInvalid())
1324       return ExprError();
1325 
1326     ArraySize = ConvertedSize.take();
1327     QualType SizeType = ArraySize->getType();
1328 
1329     if (!SizeType->isIntegralOrUnscopedEnumerationType())
1330       return ExprError();
1331 
1332     // C++98 [expr.new]p7:
1333     //   The expression in a direct-new-declarator shall have integral type
1334     //   with a non-negative value.
1335     //
1336     // Let's see if this is a constant < 0. If so, we reject it out of
1337     // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1338     // array type.
1339     //
1340     // Note: such a construct has well-defined semantics in C++11: it throws
1341     // std::bad_array_new_length.
1342     if (!ArraySize->isValueDependent()) {
1343       llvm::APSInt Value;
1344       // We've already performed any required implicit conversion to integer or
1345       // unscoped enumeration type.
1346       if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1347         if (Value < llvm::APSInt(
1348                         llvm::APInt::getNullValue(Value.getBitWidth()),
1349                                  Value.isUnsigned())) {
1350           if (getLangOpts().CPlusPlus11)
1351             Diag(ArraySize->getLocStart(),
1352                  diag::warn_typecheck_negative_array_new_size)
1353               << ArraySize->getSourceRange();
1354           else
1355             return ExprError(Diag(ArraySize->getLocStart(),
1356                                   diag::err_typecheck_negative_array_size)
1357                              << ArraySize->getSourceRange());
1358         } else if (!AllocType->isDependentType()) {
1359           unsigned ActiveSizeBits =
1360             ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1361           if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1362             if (getLangOpts().CPlusPlus11)
1363               Diag(ArraySize->getLocStart(),
1364                    diag::warn_array_new_too_large)
1365                 << Value.toString(10)
1366                 << ArraySize->getSourceRange();
1367             else
1368               return ExprError(Diag(ArraySize->getLocStart(),
1369                                     diag::err_array_too_large)
1370                                << Value.toString(10)
1371                                << ArraySize->getSourceRange());
1372           }
1373         }
1374       } else if (TypeIdParens.isValid()) {
1375         // Can't have dynamic array size when the type-id is in parentheses.
1376         Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1377           << ArraySize->getSourceRange()
1378           << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1379           << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1380 
1381         TypeIdParens = SourceRange();
1382       }
1383     }
1384 
1385     // Note that we do *not* convert the argument in any way.  It can
1386     // be signed, larger than size_t, whatever.
1387   }
1388 
1389   FunctionDecl *OperatorNew = 0;
1390   FunctionDecl *OperatorDelete = 0;
1391 
1392   if (!AllocType->isDependentType() &&
1393       !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1394       FindAllocationFunctions(StartLoc,
1395                               SourceRange(PlacementLParen, PlacementRParen),
1396                               UseGlobal, AllocType, ArraySize, PlacementArgs,
1397                               OperatorNew, OperatorDelete))
1398     return ExprError();
1399 
1400   // If this is an array allocation, compute whether the usual array
1401   // deallocation function for the type has a size_t parameter.
1402   bool UsualArrayDeleteWantsSize = false;
1403   if (ArraySize && !AllocType->isDependentType())
1404     UsualArrayDeleteWantsSize
1405       = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1406 
1407   SmallVector<Expr *, 8> AllPlaceArgs;
1408   if (OperatorNew) {
1409     // Add default arguments, if any.
1410     const FunctionProtoType *Proto =
1411       OperatorNew->getType()->getAs<FunctionProtoType>();
1412     VariadicCallType CallType =
1413       Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
1414 
1415     if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
1416                                PlacementArgs, AllPlaceArgs, CallType))
1417       return ExprError();
1418 
1419     if (!AllPlaceArgs.empty())
1420       PlacementArgs = AllPlaceArgs;
1421 
1422     DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
1423 
1424     // FIXME: Missing call to CheckFunctionCall or equivalent
1425   }
1426 
1427   // Warn if the type is over-aligned and is being allocated by global operator
1428   // new.
1429   if (PlacementArgs.empty() && OperatorNew &&
1430       (OperatorNew->isImplicit() ||
1431        getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1432     if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1433       unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1434       if (Align > SuitableAlign)
1435         Diag(StartLoc, diag::warn_overaligned_type)
1436             << AllocType
1437             << unsigned(Align / Context.getCharWidth())
1438             << unsigned(SuitableAlign / Context.getCharWidth());
1439     }
1440   }
1441 
1442   QualType InitType = AllocType;
1443   // Array 'new' can't have any initializers except empty parentheses.
1444   // Initializer lists are also allowed, in C++11. Rely on the parser for the
1445   // dialect distinction.
1446   if (ResultType->isArrayType() || ArraySize) {
1447     if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1448       SourceRange InitRange(Inits[0]->getLocStart(),
1449                             Inits[NumInits - 1]->getLocEnd());
1450       Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1451       return ExprError();
1452     }
1453     if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1454       // We do the initialization typechecking against the array type
1455       // corresponding to the number of initializers + 1 (to also check
1456       // default-initialization).
1457       unsigned NumElements = ILE->getNumInits() + 1;
1458       InitType = Context.getConstantArrayType(AllocType,
1459           llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1460                                               ArrayType::Normal, 0);
1461     }
1462   }
1463 
1464   // If we can perform the initialization, and we've not already done so,
1465   // do it now.
1466   if (!AllocType->isDependentType() &&
1467       !Expr::hasAnyTypeDependentArguments(
1468         llvm::makeArrayRef(Inits, NumInits)) &&
1469       !HaveCompleteInit) {
1470     // C++11 [expr.new]p15:
1471     //   A new-expression that creates an object of type T initializes that
1472     //   object as follows:
1473     InitializationKind Kind
1474     //     - If the new-initializer is omitted, the object is default-
1475     //       initialized (8.5); if no initialization is performed,
1476     //       the object has indeterminate value
1477       = initStyle == CXXNewExpr::NoInit
1478           ? InitializationKind::CreateDefault(TypeRange.getBegin())
1479     //     - Otherwise, the new-initializer is interpreted according to the
1480     //       initialization rules of 8.5 for direct-initialization.
1481           : initStyle == CXXNewExpr::ListInit
1482               ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1483               : InitializationKind::CreateDirect(TypeRange.getBegin(),
1484                                                  DirectInitRange.getBegin(),
1485                                                  DirectInitRange.getEnd());
1486 
1487     InitializedEntity Entity
1488       = InitializedEntity::InitializeNew(StartLoc, InitType);
1489     InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1490     ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1491                                           MultiExprArg(Inits, NumInits));
1492     if (FullInit.isInvalid())
1493       return ExprError();
1494 
1495     // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1496     // we don't want the initialized object to be destructed.
1497     if (CXXBindTemporaryExpr *Binder =
1498             dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1499       FullInit = Owned(Binder->getSubExpr());
1500 
1501     Initializer = FullInit.take();
1502   }
1503 
1504   // Mark the new and delete operators as referenced.
1505   if (OperatorNew) {
1506     if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1507       return ExprError();
1508     MarkFunctionReferenced(StartLoc, OperatorNew);
1509   }
1510   if (OperatorDelete) {
1511     if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1512       return ExprError();
1513     MarkFunctionReferenced(StartLoc, OperatorDelete);
1514   }
1515 
1516   // C++0x [expr.new]p17:
1517   //   If the new expression creates an array of objects of class type,
1518   //   access and ambiguity control are done for the destructor.
1519   QualType BaseAllocType = Context.getBaseElementType(AllocType);
1520   if (ArraySize && !BaseAllocType->isDependentType()) {
1521     if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1522       if (CXXDestructorDecl *dtor = LookupDestructor(
1523               cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1524         MarkFunctionReferenced(StartLoc, dtor);
1525         CheckDestructorAccess(StartLoc, dtor,
1526                               PDiag(diag::err_access_dtor)
1527                                 << BaseAllocType);
1528         if (DiagnoseUseOfDecl(dtor, StartLoc))
1529           return ExprError();
1530       }
1531     }
1532   }
1533 
1534   return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1535                                         OperatorDelete,
1536                                         UsualArrayDeleteWantsSize,
1537                                         PlacementArgs, TypeIdParens,
1538                                         ArraySize, initStyle, Initializer,
1539                                         ResultType, AllocTypeInfo,
1540                                         Range, DirectInitRange));
1541 }
1542 
1543 /// \brief Checks that a type is suitable as the allocated type
1544 /// in a new-expression.
1545 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1546                               SourceRange R) {
1547   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1548   //   abstract class type or array thereof.
1549   if (AllocType->isFunctionType())
1550     return Diag(Loc, diag::err_bad_new_type)
1551       << AllocType << 0 << R;
1552   else if (AllocType->isReferenceType())
1553     return Diag(Loc, diag::err_bad_new_type)
1554       << AllocType << 1 << R;
1555   else if (!AllocType->isDependentType() &&
1556            RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
1557     return true;
1558   else if (RequireNonAbstractType(Loc, AllocType,
1559                                   diag::err_allocation_of_abstract_type))
1560     return true;
1561   else if (AllocType->isVariablyModifiedType())
1562     return Diag(Loc, diag::err_variably_modified_new_type)
1563              << AllocType;
1564   else if (unsigned AddressSpace = AllocType.getAddressSpace())
1565     return Diag(Loc, diag::err_address_space_qualified_new)
1566       << AllocType.getUnqualifiedType() << AddressSpace;
1567   else if (getLangOpts().ObjCAutoRefCount) {
1568     if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1569       QualType BaseAllocType = Context.getBaseElementType(AT);
1570       if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1571           BaseAllocType->isObjCLifetimeType())
1572         return Diag(Loc, diag::err_arc_new_array_without_ownership)
1573           << BaseAllocType;
1574     }
1575   }
1576 
1577   return false;
1578 }
1579 
1580 /// \brief Determine whether the given function is a non-placement
1581 /// deallocation function.
1582 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1583   if (FD->isInvalidDecl())
1584     return false;
1585 
1586   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1587     return Method->isUsualDeallocationFunction();
1588 
1589   if (FD->getOverloadedOperator() != OO_Delete &&
1590       FD->getOverloadedOperator() != OO_Array_Delete)
1591     return false;
1592 
1593   if (FD->getNumParams() == 1)
1594     return true;
1595 
1596   return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
1597          S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
1598                                           S.Context.getSizeType());
1599 }
1600 
1601 /// FindAllocationFunctions - Finds the overloads of operator new and delete
1602 /// that are appropriate for the allocation.
1603 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1604                                    bool UseGlobal, QualType AllocType,
1605                                    bool IsArray, MultiExprArg PlaceArgs,
1606                                    FunctionDecl *&OperatorNew,
1607                                    FunctionDecl *&OperatorDelete) {
1608   // --- Choosing an allocation function ---
1609   // C++ 5.3.4p8 - 14 & 18
1610   // 1) If UseGlobal is true, only look in the global scope. Else, also look
1611   //   in the scope of the allocated class.
1612   // 2) If an array size is given, look for operator new[], else look for
1613   //   operator new.
1614   // 3) The first argument is always size_t. Append the arguments from the
1615   //   placement form.
1616 
1617   SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
1618   // We don't care about the actual value of this argument.
1619   // FIXME: Should the Sema create the expression and embed it in the syntax
1620   // tree? Or should the consumer just recalculate the value?
1621   IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1622                       Context.getTargetInfo().getPointerWidth(0)),
1623                       Context.getSizeType(),
1624                       SourceLocation());
1625   AllocArgs[0] = &Size;
1626   std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
1627 
1628   // C++ [expr.new]p8:
1629   //   If the allocated type is a non-array type, the allocation
1630   //   function's name is operator new and the deallocation function's
1631   //   name is operator delete. If the allocated type is an array
1632   //   type, the allocation function's name is operator new[] and the
1633   //   deallocation function's name is operator delete[].
1634   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1635                                         IsArray ? OO_Array_New : OO_New);
1636   DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1637                                         IsArray ? OO_Array_Delete : OO_Delete);
1638 
1639   QualType AllocElemType = Context.getBaseElementType(AllocType);
1640 
1641   if (AllocElemType->isRecordType() && !UseGlobal) {
1642     CXXRecordDecl *Record
1643       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1644     if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
1645                                /*AllowMissing=*/true, OperatorNew))
1646       return true;
1647   }
1648 
1649   if (!OperatorNew) {
1650     // Didn't find a member overload. Look for a global one.
1651     DeclareGlobalNewDelete();
1652     DeclContext *TUDecl = Context.getTranslationUnitDecl();
1653     bool FallbackEnabled = IsArray && Context.getLangOpts().MicrosoftMode;
1654     if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
1655                                /*AllowMissing=*/FallbackEnabled, OperatorNew,
1656                                /*Diagnose=*/!FallbackEnabled)) {
1657       if (!FallbackEnabled)
1658         return true;
1659 
1660       // MSVC will fall back on trying to find a matching global operator new
1661       // if operator new[] cannot be found.  Also, MSVC will leak by not
1662       // generating a call to operator delete or operator delete[], but we
1663       // will not replicate that bug.
1664       NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
1665       DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1666       if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
1667                                /*AllowMissing=*/false, OperatorNew))
1668       return true;
1669     }
1670   }
1671 
1672   // We don't need an operator delete if we're running under
1673   // -fno-exceptions.
1674   if (!getLangOpts().Exceptions) {
1675     OperatorDelete = 0;
1676     return false;
1677   }
1678 
1679   // FindAllocationOverload can change the passed in arguments, so we need to
1680   // copy them back.
1681   if (!PlaceArgs.empty())
1682     std::copy(AllocArgs.begin() + 1, AllocArgs.end(), PlaceArgs.data());
1683 
1684   // C++ [expr.new]p19:
1685   //
1686   //   If the new-expression begins with a unary :: operator, the
1687   //   deallocation function's name is looked up in the global
1688   //   scope. Otherwise, if the allocated type is a class type T or an
1689   //   array thereof, the deallocation function's name is looked up in
1690   //   the scope of T. If this lookup fails to find the name, or if
1691   //   the allocated type is not a class type or array thereof, the
1692   //   deallocation function's name is looked up in the global scope.
1693   LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1694   if (AllocElemType->isRecordType() && !UseGlobal) {
1695     CXXRecordDecl *RD
1696       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1697     LookupQualifiedName(FoundDelete, RD);
1698   }
1699   if (FoundDelete.isAmbiguous())
1700     return true; // FIXME: clean up expressions?
1701 
1702   if (FoundDelete.empty()) {
1703     DeclareGlobalNewDelete();
1704     LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1705   }
1706 
1707   FoundDelete.suppressDiagnostics();
1708 
1709   SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1710 
1711   // Whether we're looking for a placement operator delete is dictated
1712   // by whether we selected a placement operator new, not by whether
1713   // we had explicit placement arguments.  This matters for things like
1714   //   struct A { void *operator new(size_t, int = 0); ... };
1715   //   A *a = new A()
1716   bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
1717 
1718   if (isPlacementNew) {
1719     // C++ [expr.new]p20:
1720     //   A declaration of a placement deallocation function matches the
1721     //   declaration of a placement allocation function if it has the
1722     //   same number of parameters and, after parameter transformations
1723     //   (8.3.5), all parameter types except the first are
1724     //   identical. [...]
1725     //
1726     // To perform this comparison, we compute the function type that
1727     // the deallocation function should have, and use that type both
1728     // for template argument deduction and for comparison purposes.
1729     //
1730     // FIXME: this comparison should ignore CC and the like.
1731     QualType ExpectedFunctionType;
1732     {
1733       const FunctionProtoType *Proto
1734         = OperatorNew->getType()->getAs<FunctionProtoType>();
1735 
1736       SmallVector<QualType, 4> ArgTypes;
1737       ArgTypes.push_back(Context.VoidPtrTy);
1738       for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1739         ArgTypes.push_back(Proto->getArgType(I));
1740 
1741       FunctionProtoType::ExtProtoInfo EPI;
1742       EPI.Variadic = Proto->isVariadic();
1743 
1744       ExpectedFunctionType
1745         = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
1746     }
1747 
1748     for (LookupResult::iterator D = FoundDelete.begin(),
1749                              DEnd = FoundDelete.end();
1750          D != DEnd; ++D) {
1751       FunctionDecl *Fn = 0;
1752       if (FunctionTemplateDecl *FnTmpl
1753             = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1754         // Perform template argument deduction to try to match the
1755         // expected function type.
1756         TemplateDeductionInfo Info(StartLoc);
1757         if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1758           continue;
1759       } else
1760         Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1761 
1762       if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1763         Matches.push_back(std::make_pair(D.getPair(), Fn));
1764     }
1765   } else {
1766     // C++ [expr.new]p20:
1767     //   [...] Any non-placement deallocation function matches a
1768     //   non-placement allocation function. [...]
1769     for (LookupResult::iterator D = FoundDelete.begin(),
1770                              DEnd = FoundDelete.end();
1771          D != DEnd; ++D) {
1772       if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1773         if (isNonPlacementDeallocationFunction(*this, Fn))
1774           Matches.push_back(std::make_pair(D.getPair(), Fn));
1775     }
1776 
1777     // C++1y [expr.new]p22:
1778     //   For a non-placement allocation function, the normal deallocation
1779     //   function lookup is used
1780     // C++1y [expr.delete]p?:
1781     //   If [...] deallocation function lookup finds both a usual deallocation
1782     //   function with only a pointer parameter and a usual deallocation
1783     //   function with both a pointer parameter and a size parameter, then the
1784     //   selected deallocation function shall be the one with two parameters.
1785     //   Otherwise, the selected deallocation function shall be the function
1786     //   with one parameter.
1787     if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
1788       if (Matches[0].second->getNumParams() == 1)
1789         Matches.erase(Matches.begin());
1790       else
1791         Matches.erase(Matches.begin() + 1);
1792       assert(Matches[0].second->getNumParams() == 2 &&
1793              "found an unexpected uusal deallocation function");
1794     }
1795   }
1796 
1797   // C++ [expr.new]p20:
1798   //   [...] If the lookup finds a single matching deallocation
1799   //   function, that function will be called; otherwise, no
1800   //   deallocation function will be called.
1801   if (Matches.size() == 1) {
1802     OperatorDelete = Matches[0].second;
1803 
1804     // C++0x [expr.new]p20:
1805     //   If the lookup finds the two-parameter form of a usual
1806     //   deallocation function (3.7.4.2) and that function, considered
1807     //   as a placement deallocation function, would have been
1808     //   selected as a match for the allocation function, the program
1809     //   is ill-formed.
1810     if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
1811         isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
1812       Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1813         << SourceRange(PlaceArgs.front()->getLocStart(),
1814                        PlaceArgs.back()->getLocEnd());
1815       if (!OperatorDelete->isImplicit())
1816         Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1817           << DeleteName;
1818     } else {
1819       CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1820                             Matches[0].first);
1821     }
1822   }
1823 
1824   return false;
1825 }
1826 
1827 /// FindAllocationOverload - Find an fitting overload for the allocation
1828 /// function in the specified scope.
1829 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1830                                   DeclarationName Name, MultiExprArg Args,
1831                                   DeclContext *Ctx,
1832                                   bool AllowMissing, FunctionDecl *&Operator,
1833                                   bool Diagnose) {
1834   LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1835   LookupQualifiedName(R, Ctx);
1836   if (R.empty()) {
1837     if (AllowMissing || !Diagnose)
1838       return false;
1839     return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1840       << Name << Range;
1841   }
1842 
1843   if (R.isAmbiguous())
1844     return true;
1845 
1846   R.suppressDiagnostics();
1847 
1848   OverloadCandidateSet Candidates(StartLoc);
1849   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1850        Alloc != AllocEnd; ++Alloc) {
1851     // Even member operator new/delete are implicitly treated as
1852     // static, so don't use AddMemberCandidate.
1853     NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1854 
1855     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1856       AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1857                                    /*ExplicitTemplateArgs=*/0,
1858                                    Args, Candidates,
1859                                    /*SuppressUserConversions=*/false);
1860       continue;
1861     }
1862 
1863     FunctionDecl *Fn = cast<FunctionDecl>(D);
1864     AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
1865                          /*SuppressUserConversions=*/false);
1866   }
1867 
1868   // Do the resolution.
1869   OverloadCandidateSet::iterator Best;
1870   switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1871   case OR_Success: {
1872     // Got one!
1873     FunctionDecl *FnDecl = Best->Function;
1874     MarkFunctionReferenced(StartLoc, FnDecl);
1875     // The first argument is size_t, and the first parameter must be size_t,
1876     // too. This is checked on declaration and can be assumed. (It can't be
1877     // asserted on, though, since invalid decls are left in there.)
1878     // Watch out for variadic allocator function.
1879     unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1880     for (unsigned i = 0; (i < Args.size() && i < NumArgsInFnDecl); ++i) {
1881       InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1882                                                        FnDecl->getParamDecl(i));
1883 
1884       if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1885         return true;
1886 
1887       ExprResult Result
1888         = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
1889       if (Result.isInvalid())
1890         return true;
1891 
1892       Args[i] = Result.takeAs<Expr>();
1893     }
1894 
1895     Operator = FnDecl;
1896 
1897     if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1898                               Best->FoundDecl, Diagnose) == AR_inaccessible)
1899       return true;
1900 
1901     return false;
1902   }
1903 
1904   case OR_No_Viable_Function:
1905     if (Diagnose) {
1906       Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1907         << Name << Range;
1908       Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
1909     }
1910     return true;
1911 
1912   case OR_Ambiguous:
1913     if (Diagnose) {
1914       Diag(StartLoc, diag::err_ovl_ambiguous_call)
1915         << Name << Range;
1916       Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
1917     }
1918     return true;
1919 
1920   case OR_Deleted: {
1921     if (Diagnose) {
1922       Diag(StartLoc, diag::err_ovl_deleted_call)
1923         << Best->Function->isDeleted()
1924         << Name
1925         << getDeletedOrUnavailableSuffix(Best->Function)
1926         << Range;
1927       Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
1928     }
1929     return true;
1930   }
1931   }
1932   llvm_unreachable("Unreachable, bad result from BestViableFunction");
1933 }
1934 
1935 
1936 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
1937 /// delete. These are:
1938 /// @code
1939 ///   // C++03:
1940 ///   void* operator new(std::size_t) throw(std::bad_alloc);
1941 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
1942 ///   void operator delete(void *) throw();
1943 ///   void operator delete[](void *) throw();
1944 ///   // C++11:
1945 ///   void* operator new(std::size_t);
1946 ///   void* operator new[](std::size_t);
1947 ///   void operator delete(void *) noexcept;
1948 ///   void operator delete[](void *) noexcept;
1949 ///   // C++1y:
1950 ///   void* operator new(std::size_t);
1951 ///   void* operator new[](std::size_t);
1952 ///   void operator delete(void *) noexcept;
1953 ///   void operator delete[](void *) noexcept;
1954 ///   void operator delete(void *, std::size_t) noexcept;
1955 ///   void operator delete[](void *, std::size_t) noexcept;
1956 /// @endcode
1957 /// Note that the placement and nothrow forms of new are *not* implicitly
1958 /// declared. Their use requires including \<new\>.
1959 void Sema::DeclareGlobalNewDelete() {
1960   if (GlobalNewDeleteDeclared)
1961     return;
1962 
1963   // C++ [basic.std.dynamic]p2:
1964   //   [...] The following allocation and deallocation functions (18.4) are
1965   //   implicitly declared in global scope in each translation unit of a
1966   //   program
1967   //
1968   //     C++03:
1969   //     void* operator new(std::size_t) throw(std::bad_alloc);
1970   //     void* operator new[](std::size_t) throw(std::bad_alloc);
1971   //     void  operator delete(void*) throw();
1972   //     void  operator delete[](void*) throw();
1973   //     C++11:
1974   //     void* operator new(std::size_t);
1975   //     void* operator new[](std::size_t);
1976   //     void  operator delete(void*) noexcept;
1977   //     void  operator delete[](void*) noexcept;
1978   //     C++1y:
1979   //     void* operator new(std::size_t);
1980   //     void* operator new[](std::size_t);
1981   //     void  operator delete(void*) noexcept;
1982   //     void  operator delete[](void*) noexcept;
1983   //     void  operator delete(void*, std::size_t) noexcept;
1984   //     void  operator delete[](void*, std::size_t) noexcept;
1985   //
1986   //   These implicit declarations introduce only the function names operator
1987   //   new, operator new[], operator delete, operator delete[].
1988   //
1989   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1990   // "std" or "bad_alloc" as necessary to form the exception specification.
1991   // However, we do not make these implicit declarations visible to name
1992   // lookup.
1993   if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
1994     // The "std::bad_alloc" class has not yet been declared, so build it
1995     // implicitly.
1996     StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1997                                         getOrCreateStdNamespace(),
1998                                         SourceLocation(), SourceLocation(),
1999                                       &PP.getIdentifierTable().get("bad_alloc"),
2000                                         0);
2001     getStdBadAlloc()->setImplicit(true);
2002   }
2003 
2004   GlobalNewDeleteDeclared = true;
2005 
2006   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2007   QualType SizeT = Context.getSizeType();
2008   bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
2009 
2010   DeclareGlobalAllocationFunction(
2011       Context.DeclarationNames.getCXXOperatorName(OO_New),
2012       VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
2013   DeclareGlobalAllocationFunction(
2014       Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
2015       VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
2016   DeclareGlobalAllocationFunction(
2017       Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2018       Context.VoidTy, VoidPtr);
2019   DeclareGlobalAllocationFunction(
2020       Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2021       Context.VoidTy, VoidPtr);
2022   if (getLangOpts().SizedDeallocation) {
2023     DeclareGlobalAllocationFunction(
2024         Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2025         Context.VoidTy, VoidPtr, Context.getSizeType());
2026     DeclareGlobalAllocationFunction(
2027         Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2028         Context.VoidTy, VoidPtr, Context.getSizeType());
2029   }
2030 }
2031 
2032 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2033 /// allocation function if it doesn't already exist.
2034 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2035                                            QualType Return,
2036                                            QualType Param1, QualType Param2,
2037                                            bool AddMallocAttr) {
2038   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2039   unsigned NumParams = Param2.isNull() ? 1 : 2;
2040 
2041   // Check if this function is already declared.
2042   DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2043   for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2044        Alloc != AllocEnd; ++Alloc) {
2045     // Only look at non-template functions, as it is the predefined,
2046     // non-templated allocation function we are trying to declare here.
2047     if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2048       if (Func->getNumParams() == NumParams) {
2049         QualType InitialParam1Type =
2050             Context.getCanonicalType(Func->getParamDecl(0)
2051                                          ->getType().getUnqualifiedType());
2052         QualType InitialParam2Type =
2053             NumParams == 2
2054                 ? Context.getCanonicalType(Func->getParamDecl(1)
2055                                                ->getType().getUnqualifiedType())
2056                 : QualType();
2057         // FIXME: Do we need to check for default arguments here?
2058         if (InitialParam1Type == Param1 &&
2059             (NumParams == 1 || InitialParam2Type == Param2)) {
2060           if (AddMallocAttr && !Func->hasAttr<MallocAttr>())
2061             Func->addAttr(::new (Context) MallocAttr(SourceLocation(),
2062                                                      Context));
2063           // Make the function visible to name lookup, even if we found it in
2064           // an unimported module. It either is an implicitly-declared global
2065           // allocation function, or is suppressing that function.
2066           Func->setHidden(false);
2067           return;
2068         }
2069       }
2070     }
2071   }
2072 
2073   QualType BadAllocType;
2074   bool HasBadAllocExceptionSpec
2075     = (Name.getCXXOverloadedOperator() == OO_New ||
2076        Name.getCXXOverloadedOperator() == OO_Array_New);
2077   if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus11) {
2078     assert(StdBadAlloc && "Must have std::bad_alloc declared");
2079     BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2080   }
2081 
2082   FunctionProtoType::ExtProtoInfo EPI;
2083   if (HasBadAllocExceptionSpec) {
2084     if (!getLangOpts().CPlusPlus11) {
2085       EPI.ExceptionSpecType = EST_Dynamic;
2086       EPI.NumExceptions = 1;
2087       EPI.Exceptions = &BadAllocType;
2088     }
2089   } else {
2090     EPI.ExceptionSpecType = getLangOpts().CPlusPlus11 ?
2091                                 EST_BasicNoexcept : EST_DynamicNone;
2092   }
2093 
2094   QualType Params[] = { Param1, Param2 };
2095 
2096   QualType FnType = Context.getFunctionType(
2097       Return, ArrayRef<QualType>(Params, NumParams), EPI);
2098   FunctionDecl *Alloc =
2099     FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2100                          SourceLocation(), Name,
2101                          FnType, /*TInfo=*/0, SC_None, false, true);
2102   Alloc->setImplicit();
2103 
2104   if (AddMallocAttr)
2105     Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
2106 
2107   ParmVarDecl *ParamDecls[2];
2108   for (unsigned I = 0; I != NumParams; ++I)
2109     ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
2110                                         SourceLocation(), 0,
2111                                         Params[I], /*TInfo=*/0,
2112                                         SC_None, 0);
2113   Alloc->setParams(ArrayRef<ParmVarDecl*>(ParamDecls, NumParams));
2114 
2115   // FIXME: Also add this declaration to the IdentifierResolver, but
2116   // make sure it is at the end of the chain to coincide with the
2117   // global scope.
2118   Context.getTranslationUnitDecl()->addDecl(Alloc);
2119 }
2120 
2121 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2122                                                   bool CanProvideSize,
2123                                                   DeclarationName Name) {
2124   DeclareGlobalNewDelete();
2125 
2126   LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2127   LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2128 
2129   // C++ [expr.new]p20:
2130   //   [...] Any non-placement deallocation function matches a
2131   //   non-placement allocation function. [...]
2132   llvm::SmallVector<FunctionDecl*, 2> Matches;
2133   for (LookupResult::iterator D = FoundDelete.begin(),
2134                            DEnd = FoundDelete.end();
2135        D != DEnd; ++D) {
2136     if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
2137       if (isNonPlacementDeallocationFunction(*this, Fn))
2138         Matches.push_back(Fn);
2139   }
2140 
2141   // C++1y [expr.delete]p?:
2142   //   If the type is complete and deallocation function lookup finds both a
2143   //   usual deallocation function with only a pointer parameter and a usual
2144   //   deallocation function with both a pointer parameter and a size
2145   //   parameter, then the selected deallocation function shall be the one
2146   //   with two parameters.  Otherwise, the selected deallocation function
2147   //   shall be the function with one parameter.
2148   if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2149     unsigned NumArgs = CanProvideSize ? 2 : 1;
2150     if (Matches[0]->getNumParams() != NumArgs)
2151       Matches.erase(Matches.begin());
2152     else
2153       Matches.erase(Matches.begin() + 1);
2154     assert(Matches[0]->getNumParams() == NumArgs &&
2155            "found an unexpected uusal deallocation function");
2156   }
2157 
2158   assert(Matches.size() == 1 &&
2159          "unexpectedly have multiple usual deallocation functions");
2160   return Matches.front();
2161 }
2162 
2163 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2164                                     DeclarationName Name,
2165                                     FunctionDecl* &Operator, bool Diagnose) {
2166   LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2167   // Try to find operator delete/operator delete[] in class scope.
2168   LookupQualifiedName(Found, RD);
2169 
2170   if (Found.isAmbiguous())
2171     return true;
2172 
2173   Found.suppressDiagnostics();
2174 
2175   SmallVector<DeclAccessPair,4> Matches;
2176   for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2177        F != FEnd; ++F) {
2178     NamedDecl *ND = (*F)->getUnderlyingDecl();
2179 
2180     // Ignore template operator delete members from the check for a usual
2181     // deallocation function.
2182     if (isa<FunctionTemplateDecl>(ND))
2183       continue;
2184 
2185     if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
2186       Matches.push_back(F.getPair());
2187   }
2188 
2189   // There's exactly one suitable operator;  pick it.
2190   if (Matches.size() == 1) {
2191     Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
2192 
2193     if (Operator->isDeleted()) {
2194       if (Diagnose) {
2195         Diag(StartLoc, diag::err_deleted_function_use);
2196         NoteDeletedFunction(Operator);
2197       }
2198       return true;
2199     }
2200 
2201     if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2202                               Matches[0], Diagnose) == AR_inaccessible)
2203       return true;
2204 
2205     return false;
2206 
2207   // We found multiple suitable operators;  complain about the ambiguity.
2208   } else if (!Matches.empty()) {
2209     if (Diagnose) {
2210       Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2211         << Name << RD;
2212 
2213       for (SmallVectorImpl<DeclAccessPair>::iterator
2214              F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2215         Diag((*F)->getUnderlyingDecl()->getLocation(),
2216              diag::note_member_declared_here) << Name;
2217     }
2218     return true;
2219   }
2220 
2221   // We did find operator delete/operator delete[] declarations, but
2222   // none of them were suitable.
2223   if (!Found.empty()) {
2224     if (Diagnose) {
2225       Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2226         << Name << RD;
2227 
2228       for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2229            F != FEnd; ++F)
2230         Diag((*F)->getUnderlyingDecl()->getLocation(),
2231              diag::note_member_declared_here) << Name;
2232     }
2233     return true;
2234   }
2235 
2236   Operator = 0;
2237   return false;
2238 }
2239 
2240 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2241 /// @code ::delete ptr; @endcode
2242 /// or
2243 /// @code delete [] ptr; @endcode
2244 ExprResult
2245 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
2246                      bool ArrayForm, Expr *ExE) {
2247   // C++ [expr.delete]p1:
2248   //   The operand shall have a pointer type, or a class type having a single
2249   //   non-explicit conversion function to a pointer type. The result has type
2250   //   void.
2251   //
2252   // DR599 amends "pointer type" to "pointer to object type" in both cases.
2253 
2254   ExprResult Ex = Owned(ExE);
2255   FunctionDecl *OperatorDelete = 0;
2256   bool ArrayFormAsWritten = ArrayForm;
2257   bool UsualArrayDeleteWantsSize = false;
2258 
2259   if (!Ex.get()->isTypeDependent()) {
2260     // Perform lvalue-to-rvalue cast, if needed.
2261     Ex = DefaultLvalueConversion(Ex.take());
2262     if (Ex.isInvalid())
2263       return ExprError();
2264 
2265     QualType Type = Ex.get()->getType();
2266 
2267     class DeleteConverter : public ContextualImplicitConverter {
2268     public:
2269       DeleteConverter() : ContextualImplicitConverter(false, true) {}
2270 
2271       bool match(QualType ConvType) {
2272         // FIXME: If we have an operator T* and an operator void*, we must pick
2273         // the operator T*.
2274         if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
2275           if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
2276             return true;
2277         return false;
2278       }
2279 
2280       SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2281                                             QualType T) {
2282         return S.Diag(Loc, diag::err_delete_operand) << T;
2283       }
2284 
2285       SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2286                                                QualType T) {
2287         return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
2288       }
2289 
2290       SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2291                                                  QualType T, QualType ConvTy) {
2292         return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
2293       }
2294 
2295       SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2296                                              QualType ConvTy) {
2297         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2298           << ConvTy;
2299       }
2300 
2301       SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2302                                               QualType T) {
2303         return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
2304       }
2305 
2306       SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2307                                           QualType ConvTy) {
2308         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2309           << ConvTy;
2310       }
2311 
2312       SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2313                                                QualType T, QualType ConvTy) {
2314         llvm_unreachable("conversion functions are permitted");
2315       }
2316     } Converter;
2317 
2318     Ex = PerformContextualImplicitConversion(StartLoc, Ex.take(), Converter);
2319     if (Ex.isInvalid())
2320       return ExprError();
2321     Type = Ex.get()->getType();
2322     if (!Converter.match(Type))
2323       // FIXME: PerformContextualImplicitConversion should return ExprError
2324       //        itself in this case.
2325       return ExprError();
2326 
2327     QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
2328     QualType PointeeElem = Context.getBaseElementType(Pointee);
2329 
2330     if (unsigned AddressSpace = Pointee.getAddressSpace())
2331       return Diag(Ex.get()->getLocStart(),
2332                   diag::err_address_space_qualified_delete)
2333                << Pointee.getUnqualifiedType() << AddressSpace;
2334 
2335     CXXRecordDecl *PointeeRD = 0;
2336     if (Pointee->isVoidType() && !isSFINAEContext()) {
2337       // The C++ standard bans deleting a pointer to a non-object type, which
2338       // effectively bans deletion of "void*". However, most compilers support
2339       // this, so we treat it as a warning unless we're in a SFINAE context.
2340       Diag(StartLoc, diag::ext_delete_void_ptr_operand)
2341         << Type << Ex.get()->getSourceRange();
2342     } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
2343       return ExprError(Diag(StartLoc, diag::err_delete_operand)
2344         << Type << Ex.get()->getSourceRange());
2345     } else if (!Pointee->isDependentType()) {
2346       if (!RequireCompleteType(StartLoc, Pointee,
2347                                diag::warn_delete_incomplete, Ex.get())) {
2348         if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2349           PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2350       }
2351     }
2352 
2353     // C++ [expr.delete]p2:
2354     //   [Note: a pointer to a const type can be the operand of a
2355     //   delete-expression; it is not necessary to cast away the constness
2356     //   (5.2.11) of the pointer expression before it is used as the operand
2357     //   of the delete-expression. ]
2358 
2359     if (Pointee->isArrayType() && !ArrayForm) {
2360       Diag(StartLoc, diag::warn_delete_array_type)
2361           << Type << Ex.get()->getSourceRange()
2362           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2363       ArrayForm = true;
2364     }
2365 
2366     DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2367                                       ArrayForm ? OO_Array_Delete : OO_Delete);
2368 
2369     if (PointeeRD) {
2370       if (!UseGlobal &&
2371           FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2372                                    OperatorDelete))
2373         return ExprError();
2374 
2375       // If we're allocating an array of records, check whether the
2376       // usual operator delete[] has a size_t parameter.
2377       if (ArrayForm) {
2378         // If the user specifically asked to use the global allocator,
2379         // we'll need to do the lookup into the class.
2380         if (UseGlobal)
2381           UsualArrayDeleteWantsSize =
2382             doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2383 
2384         // Otherwise, the usual operator delete[] should be the
2385         // function we just found.
2386         else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
2387           UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2388       }
2389 
2390       if (!PointeeRD->hasIrrelevantDestructor())
2391         if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2392           MarkFunctionReferenced(StartLoc,
2393                                     const_cast<CXXDestructorDecl*>(Dtor));
2394           if (DiagnoseUseOfDecl(Dtor, StartLoc))
2395             return ExprError();
2396         }
2397 
2398       // C++ [expr.delete]p3:
2399       //   In the first alternative (delete object), if the static type of the
2400       //   object to be deleted is different from its dynamic type, the static
2401       //   type shall be a base class of the dynamic type of the object to be
2402       //   deleted and the static type shall have a virtual destructor or the
2403       //   behavior is undefined.
2404       //
2405       // Note: a final class cannot be derived from, no issue there
2406       if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
2407         CXXDestructorDecl *dtor = PointeeRD->getDestructor();
2408         if (dtor && !dtor->isVirtual()) {
2409           if (PointeeRD->isAbstract()) {
2410             // If the class is abstract, we warn by default, because we're
2411             // sure the code has undefined behavior.
2412             Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2413                 << PointeeElem;
2414           } else if (!ArrayForm) {
2415             // Otherwise, if this is not an array delete, it's a bit suspect,
2416             // but not necessarily wrong.
2417             Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2418           }
2419         }
2420       }
2421 
2422     }
2423 
2424     if (!OperatorDelete)
2425       // Look for a global declaration.
2426       OperatorDelete = FindUsualDeallocationFunction(
2427           StartLoc, !RequireCompleteType(StartLoc, Pointee, 0) &&
2428                     (!ArrayForm || UsualArrayDeleteWantsSize ||
2429                      Pointee.isDestructedType()),
2430           DeleteName);
2431 
2432     MarkFunctionReferenced(StartLoc, OperatorDelete);
2433 
2434     // Check access and ambiguity of operator delete and destructor.
2435     if (PointeeRD) {
2436       if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2437           CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
2438                       PDiag(diag::err_access_dtor) << PointeeElem);
2439       }
2440     }
2441   }
2442 
2443   return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
2444                                            ArrayFormAsWritten,
2445                                            UsualArrayDeleteWantsSize,
2446                                            OperatorDelete, Ex.take(), StartLoc));
2447 }
2448 
2449 /// \brief Check the use of the given variable as a C++ condition in an if,
2450 /// while, do-while, or switch statement.
2451 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
2452                                         SourceLocation StmtLoc,
2453                                         bool ConvertToBoolean) {
2454   if (ConditionVar->isInvalidDecl())
2455     return ExprError();
2456 
2457   QualType T = ConditionVar->getType();
2458 
2459   // C++ [stmt.select]p2:
2460   //   The declarator shall not specify a function or an array.
2461   if (T->isFunctionType())
2462     return ExprError(Diag(ConditionVar->getLocation(),
2463                           diag::err_invalid_use_of_function_type)
2464                        << ConditionVar->getSourceRange());
2465   else if (T->isArrayType())
2466     return ExprError(Diag(ConditionVar->getLocation(),
2467                           diag::err_invalid_use_of_array_type)
2468                      << ConditionVar->getSourceRange());
2469 
2470   ExprResult Condition =
2471     Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2472                               SourceLocation(),
2473                               ConditionVar,
2474                               /*enclosing*/ false,
2475                               ConditionVar->getLocation(),
2476                               ConditionVar->getType().getNonReferenceType(),
2477                               VK_LValue));
2478 
2479   MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
2480 
2481   if (ConvertToBoolean) {
2482     Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2483     if (Condition.isInvalid())
2484       return ExprError();
2485   }
2486 
2487   return Condition;
2488 }
2489 
2490 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
2491 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
2492   // C++ 6.4p4:
2493   // The value of a condition that is an initialized declaration in a statement
2494   // other than a switch statement is the value of the declared variable
2495   // implicitly converted to type bool. If that conversion is ill-formed, the
2496   // program is ill-formed.
2497   // The value of a condition that is an expression is the value of the
2498   // expression, implicitly converted to bool.
2499   //
2500   return PerformContextuallyConvertToBool(CondExpr);
2501 }
2502 
2503 /// Helper function to determine whether this is the (deprecated) C++
2504 /// conversion from a string literal to a pointer to non-const char or
2505 /// non-const wchar_t (for narrow and wide string literals,
2506 /// respectively).
2507 bool
2508 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2509   // Look inside the implicit cast, if it exists.
2510   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2511     From = Cast->getSubExpr();
2512 
2513   // A string literal (2.13.4) that is not a wide string literal can
2514   // be converted to an rvalue of type "pointer to char"; a wide
2515   // string literal can be converted to an rvalue of type "pointer
2516   // to wchar_t" (C++ 4.2p2).
2517   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
2518     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
2519       if (const BuiltinType *ToPointeeType
2520           = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
2521         // This conversion is considered only when there is an
2522         // explicit appropriate pointer target type (C++ 4.2p2).
2523         if (!ToPtrType->getPointeeType().hasQualifiers()) {
2524           switch (StrLit->getKind()) {
2525             case StringLiteral::UTF8:
2526             case StringLiteral::UTF16:
2527             case StringLiteral::UTF32:
2528               // We don't allow UTF literals to be implicitly converted
2529               break;
2530             case StringLiteral::Ascii:
2531               return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2532                       ToPointeeType->getKind() == BuiltinType::Char_S);
2533             case StringLiteral::Wide:
2534               return ToPointeeType->isWideCharType();
2535           }
2536         }
2537       }
2538 
2539   return false;
2540 }
2541 
2542 static ExprResult BuildCXXCastArgument(Sema &S,
2543                                        SourceLocation CastLoc,
2544                                        QualType Ty,
2545                                        CastKind Kind,
2546                                        CXXMethodDecl *Method,
2547                                        DeclAccessPair FoundDecl,
2548                                        bool HadMultipleCandidates,
2549                                        Expr *From) {
2550   switch (Kind) {
2551   default: llvm_unreachable("Unhandled cast kind!");
2552   case CK_ConstructorConversion: {
2553     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
2554     SmallVector<Expr*, 8> ConstructorArgs;
2555 
2556     if (S.RequireNonAbstractType(CastLoc, Ty,
2557                                  diag::err_allocation_of_abstract_type))
2558       return ExprError();
2559 
2560     if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
2561       return ExprError();
2562 
2563     S.CheckConstructorAccess(CastLoc, Constructor,
2564                              InitializedEntity::InitializeTemporary(Ty),
2565                              Constructor->getAccess());
2566 
2567     ExprResult Result
2568       = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2569                                 ConstructorArgs, HadMultipleCandidates,
2570                                 /*ListInit*/ false, /*ZeroInit*/ false,
2571                                 CXXConstructExpr::CK_Complete, SourceRange());
2572     if (Result.isInvalid())
2573       return ExprError();
2574 
2575     return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2576   }
2577 
2578   case CK_UserDefinedConversion: {
2579     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
2580 
2581     // Create an implicit call expr that calls it.
2582     CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2583     ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
2584                                                  HadMultipleCandidates);
2585     if (Result.isInvalid())
2586       return ExprError();
2587     // Record usage of conversion in an implicit cast.
2588     Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2589                                               Result.get()->getType(),
2590                                               CK_UserDefinedConversion,
2591                                               Result.get(), 0,
2592                                               Result.get()->getValueKind()));
2593 
2594     S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2595 
2596     return S.MaybeBindToTemporary(Result.get());
2597   }
2598   }
2599 }
2600 
2601 /// PerformImplicitConversion - Perform an implicit conversion of the
2602 /// expression From to the type ToType using the pre-computed implicit
2603 /// conversion sequence ICS. Returns the converted
2604 /// expression. Action is the kind of conversion we're performing,
2605 /// used in the error message.
2606 ExprResult
2607 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2608                                 const ImplicitConversionSequence &ICS,
2609                                 AssignmentAction Action,
2610                                 CheckedConversionKind CCK) {
2611   switch (ICS.getKind()) {
2612   case ImplicitConversionSequence::StandardConversion: {
2613     ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2614                                                Action, CCK);
2615     if (Res.isInvalid())
2616       return ExprError();
2617     From = Res.take();
2618     break;
2619   }
2620 
2621   case ImplicitConversionSequence::UserDefinedConversion: {
2622 
2623       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
2624       CastKind CastKind;
2625       QualType BeforeToType;
2626       assert(FD && "FIXME: aggregate initialization from init list");
2627       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
2628         CastKind = CK_UserDefinedConversion;
2629 
2630         // If the user-defined conversion is specified by a conversion function,
2631         // the initial standard conversion sequence converts the source type to
2632         // the implicit object parameter of the conversion function.
2633         BeforeToType = Context.getTagDeclType(Conv->getParent());
2634       } else {
2635         const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
2636         CastKind = CK_ConstructorConversion;
2637         // Do no conversion if dealing with ... for the first conversion.
2638         if (!ICS.UserDefined.EllipsisConversion) {
2639           // If the user-defined conversion is specified by a constructor, the
2640           // initial standard conversion sequence converts the source type to the
2641           // type required by the argument of the constructor
2642           BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2643         }
2644       }
2645       // Watch out for ellipsis conversion.
2646       if (!ICS.UserDefined.EllipsisConversion) {
2647         ExprResult Res =
2648           PerformImplicitConversion(From, BeforeToType,
2649                                     ICS.UserDefined.Before, AA_Converting,
2650                                     CCK);
2651         if (Res.isInvalid())
2652           return ExprError();
2653         From = Res.take();
2654       }
2655 
2656       ExprResult CastArg
2657         = BuildCXXCastArgument(*this,
2658                                From->getLocStart(),
2659                                ToType.getNonReferenceType(),
2660                                CastKind, cast<CXXMethodDecl>(FD),
2661                                ICS.UserDefined.FoundConversionFunction,
2662                                ICS.UserDefined.HadMultipleCandidates,
2663                                From);
2664 
2665       if (CastArg.isInvalid())
2666         return ExprError();
2667 
2668       From = CastArg.take();
2669 
2670       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2671                                        AA_Converting, CCK);
2672   }
2673 
2674   case ImplicitConversionSequence::AmbiguousConversion:
2675     ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2676                           PDiag(diag::err_typecheck_ambiguous_condition)
2677                             << From->getSourceRange());
2678      return ExprError();
2679 
2680   case ImplicitConversionSequence::EllipsisConversion:
2681     llvm_unreachable("Cannot perform an ellipsis conversion");
2682 
2683   case ImplicitConversionSequence::BadConversion:
2684     return ExprError();
2685   }
2686 
2687   // Everything went well.
2688   return Owned(From);
2689 }
2690 
2691 /// PerformImplicitConversion - Perform an implicit conversion of the
2692 /// expression From to the type ToType by following the standard
2693 /// conversion sequence SCS. Returns the converted
2694 /// expression. Flavor is the context in which we're performing this
2695 /// conversion, for use in error messages.
2696 ExprResult
2697 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2698                                 const StandardConversionSequence& SCS,
2699                                 AssignmentAction Action,
2700                                 CheckedConversionKind CCK) {
2701   bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2702 
2703   // Overall FIXME: we are recomputing too many types here and doing far too
2704   // much extra work. What this means is that we need to keep track of more
2705   // information that is computed when we try the implicit conversion initially,
2706   // so that we don't need to recompute anything here.
2707   QualType FromType = From->getType();
2708 
2709   if (SCS.CopyConstructor) {
2710     // FIXME: When can ToType be a reference type?
2711     assert(!ToType->isReferenceType());
2712     if (SCS.Second == ICK_Derived_To_Base) {
2713       SmallVector<Expr*, 8> ConstructorArgs;
2714       if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2715                                   From, /*FIXME:ConstructLoc*/SourceLocation(),
2716                                   ConstructorArgs))
2717         return ExprError();
2718       return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2719                                    ToType, SCS.CopyConstructor,
2720                                    ConstructorArgs,
2721                                    /*HadMultipleCandidates*/ false,
2722                                    /*ListInit*/ false, /*ZeroInit*/ false,
2723                                    CXXConstructExpr::CK_Complete,
2724                                    SourceRange());
2725     }
2726     return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2727                                  ToType, SCS.CopyConstructor,
2728                                  From, /*HadMultipleCandidates*/ false,
2729                                  /*ListInit*/ false, /*ZeroInit*/ false,
2730                                  CXXConstructExpr::CK_Complete,
2731                                  SourceRange());
2732   }
2733 
2734   // Resolve overloaded function references.
2735   if (Context.hasSameType(FromType, Context.OverloadTy)) {
2736     DeclAccessPair Found;
2737     FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2738                                                           true, Found);
2739     if (!Fn)
2740       return ExprError();
2741 
2742     if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
2743       return ExprError();
2744 
2745     From = FixOverloadedFunctionReference(From, Found, Fn);
2746     FromType = From->getType();
2747   }
2748 
2749   // If we're converting to an atomic type, first convert to the corresponding
2750   // non-atomic type.
2751   QualType ToAtomicType;
2752   if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
2753     ToAtomicType = ToType;
2754     ToType = ToAtomic->getValueType();
2755   }
2756 
2757   // Perform the first implicit conversion.
2758   switch (SCS.First) {
2759   case ICK_Identity:
2760     // Nothing to do.
2761     break;
2762 
2763   case ICK_Lvalue_To_Rvalue: {
2764     assert(From->getObjectKind() != OK_ObjCProperty);
2765     FromType = FromType.getUnqualifiedType();
2766     ExprResult FromRes = DefaultLvalueConversion(From);
2767     assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2768     From = FromRes.take();
2769     break;
2770   }
2771 
2772   case ICK_Array_To_Pointer:
2773     FromType = Context.getArrayDecayedType(FromType);
2774     From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2775                              VK_RValue, /*BasePath=*/0, CCK).take();
2776     break;
2777 
2778   case ICK_Function_To_Pointer:
2779     FromType = Context.getPointerType(FromType);
2780     From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2781                              VK_RValue, /*BasePath=*/0, CCK).take();
2782     break;
2783 
2784   default:
2785     llvm_unreachable("Improper first standard conversion");
2786   }
2787 
2788   // Perform the second implicit conversion
2789   switch (SCS.Second) {
2790   case ICK_Identity:
2791     // If both sides are functions (or pointers/references to them), there could
2792     // be incompatible exception declarations.
2793     if (CheckExceptionSpecCompatibility(From, ToType))
2794       return ExprError();
2795     // Nothing else to do.
2796     break;
2797 
2798   case ICK_NoReturn_Adjustment:
2799     // If both sides are functions (or pointers/references to them), there could
2800     // be incompatible exception declarations.
2801     if (CheckExceptionSpecCompatibility(From, ToType))
2802       return ExprError();
2803 
2804     From = ImpCastExprToType(From, ToType, CK_NoOp,
2805                              VK_RValue, /*BasePath=*/0, CCK).take();
2806     break;
2807 
2808   case ICK_Integral_Promotion:
2809   case ICK_Integral_Conversion:
2810     if (ToType->isBooleanType()) {
2811       assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
2812              SCS.Second == ICK_Integral_Promotion &&
2813              "only enums with fixed underlying type can promote to bool");
2814       From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
2815                                VK_RValue, /*BasePath=*/0, CCK).take();
2816     } else {
2817       From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2818                                VK_RValue, /*BasePath=*/0, CCK).take();
2819     }
2820     break;
2821 
2822   case ICK_Floating_Promotion:
2823   case ICK_Floating_Conversion:
2824     From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2825                              VK_RValue, /*BasePath=*/0, CCK).take();
2826     break;
2827 
2828   case ICK_Complex_Promotion:
2829   case ICK_Complex_Conversion: {
2830     QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2831     QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2832     CastKind CK;
2833     if (FromEl->isRealFloatingType()) {
2834       if (ToEl->isRealFloatingType())
2835         CK = CK_FloatingComplexCast;
2836       else
2837         CK = CK_FloatingComplexToIntegralComplex;
2838     } else if (ToEl->isRealFloatingType()) {
2839       CK = CK_IntegralComplexToFloatingComplex;
2840     } else {
2841       CK = CK_IntegralComplexCast;
2842     }
2843     From = ImpCastExprToType(From, ToType, CK,
2844                              VK_RValue, /*BasePath=*/0, CCK).take();
2845     break;
2846   }
2847 
2848   case ICK_Floating_Integral:
2849     if (ToType->isRealFloatingType())
2850       From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2851                                VK_RValue, /*BasePath=*/0, CCK).take();
2852     else
2853       From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2854                                VK_RValue, /*BasePath=*/0, CCK).take();
2855     break;
2856 
2857   case ICK_Compatible_Conversion:
2858       From = ImpCastExprToType(From, ToType, CK_NoOp,
2859                                VK_RValue, /*BasePath=*/0, CCK).take();
2860     break;
2861 
2862   case ICK_Writeback_Conversion:
2863   case ICK_Pointer_Conversion: {
2864     if (SCS.IncompatibleObjC && Action != AA_Casting) {
2865       // Diagnose incompatible Objective-C conversions
2866       if (Action == AA_Initializing || Action == AA_Assigning)
2867         Diag(From->getLocStart(),
2868              diag::ext_typecheck_convert_incompatible_pointer)
2869           << ToType << From->getType() << Action
2870           << From->getSourceRange() << 0;
2871       else
2872         Diag(From->getLocStart(),
2873              diag::ext_typecheck_convert_incompatible_pointer)
2874           << From->getType() << ToType << Action
2875           << From->getSourceRange() << 0;
2876 
2877       if (From->getType()->isObjCObjectPointerType() &&
2878           ToType->isObjCObjectPointerType())
2879         EmitRelatedResultTypeNote(From);
2880     }
2881     else if (getLangOpts().ObjCAutoRefCount &&
2882              !CheckObjCARCUnavailableWeakConversion(ToType,
2883                                                     From->getType())) {
2884       if (Action == AA_Initializing)
2885         Diag(From->getLocStart(),
2886              diag::err_arc_weak_unavailable_assign);
2887       else
2888         Diag(From->getLocStart(),
2889              diag::err_arc_convesion_of_weak_unavailable)
2890           << (Action == AA_Casting) << From->getType() << ToType
2891           << From->getSourceRange();
2892     }
2893 
2894     CastKind Kind = CK_Invalid;
2895     CXXCastPath BasePath;
2896     if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2897       return ExprError();
2898 
2899     // Make sure we extend blocks if necessary.
2900     // FIXME: doing this here is really ugly.
2901     if (Kind == CK_BlockPointerToObjCPointerCast) {
2902       ExprResult E = From;
2903       (void) PrepareCastToObjCObjectPointer(E);
2904       From = E.take();
2905     }
2906     if (getLangOpts().ObjCAutoRefCount)
2907       CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
2908     From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2909              .take();
2910     break;
2911   }
2912 
2913   case ICK_Pointer_Member: {
2914     CastKind Kind = CK_Invalid;
2915     CXXCastPath BasePath;
2916     if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2917       return ExprError();
2918     if (CheckExceptionSpecCompatibility(From, ToType))
2919       return ExprError();
2920     From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2921              .take();
2922     break;
2923   }
2924 
2925   case ICK_Boolean_Conversion:
2926     // Perform half-to-boolean conversion via float.
2927     if (From->getType()->isHalfType()) {
2928       From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2929       FromType = Context.FloatTy;
2930     }
2931 
2932     From = ImpCastExprToType(From, Context.BoolTy,
2933                              ScalarTypeToBooleanCastKind(FromType),
2934                              VK_RValue, /*BasePath=*/0, CCK).take();
2935     break;
2936 
2937   case ICK_Derived_To_Base: {
2938     CXXCastPath BasePath;
2939     if (CheckDerivedToBaseConversion(From->getType(),
2940                                      ToType.getNonReferenceType(),
2941                                      From->getLocStart(),
2942                                      From->getSourceRange(),
2943                                      &BasePath,
2944                                      CStyle))
2945       return ExprError();
2946 
2947     From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2948                       CK_DerivedToBase, From->getValueKind(),
2949                       &BasePath, CCK).take();
2950     break;
2951   }
2952 
2953   case ICK_Vector_Conversion:
2954     From = ImpCastExprToType(From, ToType, CK_BitCast,
2955                              VK_RValue, /*BasePath=*/0, CCK).take();
2956     break;
2957 
2958   case ICK_Vector_Splat:
2959     From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2960                              VK_RValue, /*BasePath=*/0, CCK).take();
2961     break;
2962 
2963   case ICK_Complex_Real:
2964     // Case 1.  x -> _Complex y
2965     if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2966       QualType ElType = ToComplex->getElementType();
2967       bool isFloatingComplex = ElType->isRealFloatingType();
2968 
2969       // x -> y
2970       if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2971         // do nothing
2972       } else if (From->getType()->isRealFloatingType()) {
2973         From = ImpCastExprToType(From, ElType,
2974                 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2975       } else {
2976         assert(From->getType()->isIntegerType());
2977         From = ImpCastExprToType(From, ElType,
2978                 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2979       }
2980       // y -> _Complex y
2981       From = ImpCastExprToType(From, ToType,
2982                    isFloatingComplex ? CK_FloatingRealToComplex
2983                                      : CK_IntegralRealToComplex).take();
2984 
2985     // Case 2.  _Complex x -> y
2986     } else {
2987       const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2988       assert(FromComplex);
2989 
2990       QualType ElType = FromComplex->getElementType();
2991       bool isFloatingComplex = ElType->isRealFloatingType();
2992 
2993       // _Complex x -> x
2994       From = ImpCastExprToType(From, ElType,
2995                    isFloatingComplex ? CK_FloatingComplexToReal
2996                                      : CK_IntegralComplexToReal,
2997                                VK_RValue, /*BasePath=*/0, CCK).take();
2998 
2999       // x -> y
3000       if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3001         // do nothing
3002       } else if (ToType->isRealFloatingType()) {
3003         From = ImpCastExprToType(From, ToType,
3004                    isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
3005                                  VK_RValue, /*BasePath=*/0, CCK).take();
3006       } else {
3007         assert(ToType->isIntegerType());
3008         From = ImpCastExprToType(From, ToType,
3009                    isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
3010                                  VK_RValue, /*BasePath=*/0, CCK).take();
3011       }
3012     }
3013     break;
3014 
3015   case ICK_Block_Pointer_Conversion: {
3016     From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
3017                              VK_RValue, /*BasePath=*/0, CCK).take();
3018     break;
3019   }
3020 
3021   case ICK_TransparentUnionConversion: {
3022     ExprResult FromRes = Owned(From);
3023     Sema::AssignConvertType ConvTy =
3024       CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3025     if (FromRes.isInvalid())
3026       return ExprError();
3027     From = FromRes.take();
3028     assert ((ConvTy == Sema::Compatible) &&
3029             "Improper transparent union conversion");
3030     (void)ConvTy;
3031     break;
3032   }
3033 
3034   case ICK_Zero_Event_Conversion:
3035     From = ImpCastExprToType(From, ToType,
3036                              CK_ZeroToOCLEvent,
3037                              From->getValueKind()).take();
3038     break;
3039 
3040   case ICK_Lvalue_To_Rvalue:
3041   case ICK_Array_To_Pointer:
3042   case ICK_Function_To_Pointer:
3043   case ICK_Qualification:
3044   case ICK_Num_Conversion_Kinds:
3045     llvm_unreachable("Improper second standard conversion");
3046   }
3047 
3048   switch (SCS.Third) {
3049   case ICK_Identity:
3050     // Nothing to do.
3051     break;
3052 
3053   case ICK_Qualification: {
3054     // The qualification keeps the category of the inner expression, unless the
3055     // target type isn't a reference.
3056     ExprValueKind VK = ToType->isReferenceType() ?
3057                                   From->getValueKind() : VK_RValue;
3058     From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
3059                              CK_NoOp, VK, /*BasePath=*/0, CCK).take();
3060 
3061     if (SCS.DeprecatedStringLiteralToCharPtr &&
3062         !getLangOpts().WritableStrings)
3063       Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
3064         << ToType.getNonReferenceType();
3065 
3066     break;
3067   }
3068 
3069   default:
3070     llvm_unreachable("Improper third standard conversion");
3071   }
3072 
3073   // If this conversion sequence involved a scalar -> atomic conversion, perform
3074   // that conversion now.
3075   if (!ToAtomicType.isNull()) {
3076     assert(Context.hasSameType(
3077         ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3078     From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
3079                              VK_RValue, 0, CCK).take();
3080   }
3081 
3082   return Owned(From);
3083 }
3084 
3085 ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
3086                                      SourceLocation KWLoc,
3087                                      ParsedType Ty,
3088                                      SourceLocation RParen) {
3089   TypeSourceInfo *TSInfo;
3090   QualType T = GetTypeFromParser(Ty, &TSInfo);
3091 
3092   if (!TSInfo)
3093     TSInfo = Context.getTrivialTypeSourceInfo(T);
3094   return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
3095 }
3096 
3097 /// \brief Check the completeness of a type in a unary type trait.
3098 ///
3099 /// If the particular type trait requires a complete type, tries to complete
3100 /// it. If completing the type fails, a diagnostic is emitted and false
3101 /// returned. If completing the type succeeds or no completion was required,
3102 /// returns true.
3103 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
3104                                                 UnaryTypeTrait UTT,
3105                                                 SourceLocation Loc,
3106                                                 QualType ArgTy) {
3107   // C++0x [meta.unary.prop]p3:
3108   //   For all of the class templates X declared in this Clause, instantiating
3109   //   that template with a template argument that is a class template
3110   //   specialization may result in the implicit instantiation of the template
3111   //   argument if and only if the semantics of X require that the argument
3112   //   must be a complete type.
3113   // We apply this rule to all the type trait expressions used to implement
3114   // these class templates. We also try to follow any GCC documented behavior
3115   // in these expressions to ensure portability of standard libraries.
3116   switch (UTT) {
3117     // is_complete_type somewhat obviously cannot require a complete type.
3118   case UTT_IsCompleteType:
3119     // Fall-through
3120 
3121     // These traits are modeled on the type predicates in C++0x
3122     // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3123     // requiring a complete type, as whether or not they return true cannot be
3124     // impacted by the completeness of the type.
3125   case UTT_IsVoid:
3126   case UTT_IsIntegral:
3127   case UTT_IsFloatingPoint:
3128   case UTT_IsArray:
3129   case UTT_IsPointer:
3130   case UTT_IsLvalueReference:
3131   case UTT_IsRvalueReference:
3132   case UTT_IsMemberFunctionPointer:
3133   case UTT_IsMemberObjectPointer:
3134   case UTT_IsEnum:
3135   case UTT_IsUnion:
3136   case UTT_IsClass:
3137   case UTT_IsFunction:
3138   case UTT_IsReference:
3139   case UTT_IsArithmetic:
3140   case UTT_IsFundamental:
3141   case UTT_IsObject:
3142   case UTT_IsScalar:
3143   case UTT_IsCompound:
3144   case UTT_IsMemberPointer:
3145     // Fall-through
3146 
3147     // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3148     // which requires some of its traits to have the complete type. However,
3149     // the completeness of the type cannot impact these traits' semantics, and
3150     // so they don't require it. This matches the comments on these traits in
3151     // Table 49.
3152   case UTT_IsConst:
3153   case UTT_IsVolatile:
3154   case UTT_IsSigned:
3155   case UTT_IsUnsigned:
3156     return true;
3157 
3158     // C++0x [meta.unary.prop] Table 49 requires the following traits to be
3159     // applied to a complete type.
3160   case UTT_IsTrivial:
3161   case UTT_IsTriviallyCopyable:
3162   case UTT_IsStandardLayout:
3163   case UTT_IsPOD:
3164   case UTT_IsLiteral:
3165   case UTT_IsEmpty:
3166   case UTT_IsPolymorphic:
3167   case UTT_IsAbstract:
3168   case UTT_IsInterfaceClass:
3169     // Fall-through
3170 
3171   // These traits require a complete type.
3172   case UTT_IsFinal:
3173   case UTT_IsSealed:
3174 
3175     // These trait expressions are designed to help implement predicates in
3176     // [meta.unary.prop] despite not being named the same. They are specified
3177     // by both GCC and the Embarcadero C++ compiler, and require the complete
3178     // type due to the overarching C++0x type predicates being implemented
3179     // requiring the complete type.
3180   case UTT_HasNothrowAssign:
3181   case UTT_HasNothrowMoveAssign:
3182   case UTT_HasNothrowConstructor:
3183   case UTT_HasNothrowCopy:
3184   case UTT_HasTrivialAssign:
3185   case UTT_HasTrivialMoveAssign:
3186   case UTT_HasTrivialDefaultConstructor:
3187   case UTT_HasTrivialMoveConstructor:
3188   case UTT_HasTrivialCopy:
3189   case UTT_HasTrivialDestructor:
3190   case UTT_HasVirtualDestructor:
3191     // Arrays of unknown bound are expressly allowed.
3192     QualType ElTy = ArgTy;
3193     if (ArgTy->isIncompleteArrayType())
3194       ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
3195 
3196     // The void type is expressly allowed.
3197     if (ElTy->isVoidType())
3198       return true;
3199 
3200     return !S.RequireCompleteType(
3201       Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
3202   }
3203   llvm_unreachable("Type trait not handled by switch");
3204 }
3205 
3206 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
3207                                Sema &Self, SourceLocation KeyLoc, ASTContext &C,
3208                                bool (CXXRecordDecl::*HasTrivial)() const,
3209                                bool (CXXRecordDecl::*HasNonTrivial)() const,
3210                                bool (CXXMethodDecl::*IsDesiredOp)() const)
3211 {
3212   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3213   if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
3214     return true;
3215 
3216   DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
3217   DeclarationNameInfo NameInfo(Name, KeyLoc);
3218   LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
3219   if (Self.LookupQualifiedName(Res, RD)) {
3220     bool FoundOperator = false;
3221     Res.suppressDiagnostics();
3222     for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3223          Op != OpEnd; ++Op) {
3224       if (isa<FunctionTemplateDecl>(*Op))
3225         continue;
3226 
3227       CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3228       if((Operator->*IsDesiredOp)()) {
3229         FoundOperator = true;
3230         const FunctionProtoType *CPT =
3231           Operator->getType()->getAs<FunctionProtoType>();
3232         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3233         if (!CPT || !CPT->isNothrow(Self.Context))
3234           return false;
3235       }
3236     }
3237     return FoundOperator;
3238   }
3239   return false;
3240 }
3241 
3242 static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
3243                                    SourceLocation KeyLoc, QualType T) {
3244   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3245 
3246   ASTContext &C = Self.Context;
3247   switch(UTT) {
3248     // Type trait expressions corresponding to the primary type category
3249     // predicates in C++0x [meta.unary.cat].
3250   case UTT_IsVoid:
3251     return T->isVoidType();
3252   case UTT_IsIntegral:
3253     return T->isIntegralType(C);
3254   case UTT_IsFloatingPoint:
3255     return T->isFloatingType();
3256   case UTT_IsArray:
3257     return T->isArrayType();
3258   case UTT_IsPointer:
3259     return T->isPointerType();
3260   case UTT_IsLvalueReference:
3261     return T->isLValueReferenceType();
3262   case UTT_IsRvalueReference:
3263     return T->isRValueReferenceType();
3264   case UTT_IsMemberFunctionPointer:
3265     return T->isMemberFunctionPointerType();
3266   case UTT_IsMemberObjectPointer:
3267     return T->isMemberDataPointerType();
3268   case UTT_IsEnum:
3269     return T->isEnumeralType();
3270   case UTT_IsUnion:
3271     return T->isUnionType();
3272   case UTT_IsClass:
3273     return T->isClassType() || T->isStructureType() || T->isInterfaceType();
3274   case UTT_IsFunction:
3275     return T->isFunctionType();
3276 
3277     // Type trait expressions which correspond to the convenient composition
3278     // predicates in C++0x [meta.unary.comp].
3279   case UTT_IsReference:
3280     return T->isReferenceType();
3281   case UTT_IsArithmetic:
3282     return T->isArithmeticType() && !T->isEnumeralType();
3283   case UTT_IsFundamental:
3284     return T->isFundamentalType();
3285   case UTT_IsObject:
3286     return T->isObjectType();
3287   case UTT_IsScalar:
3288     // Note: semantic analysis depends on Objective-C lifetime types to be
3289     // considered scalar types. However, such types do not actually behave
3290     // like scalar types at run time (since they may require retain/release
3291     // operations), so we report them as non-scalar.
3292     if (T->isObjCLifetimeType()) {
3293       switch (T.getObjCLifetime()) {
3294       case Qualifiers::OCL_None:
3295       case Qualifiers::OCL_ExplicitNone:
3296         return true;
3297 
3298       case Qualifiers::OCL_Strong:
3299       case Qualifiers::OCL_Weak:
3300       case Qualifiers::OCL_Autoreleasing:
3301         return false;
3302       }
3303     }
3304 
3305     return T->isScalarType();
3306   case UTT_IsCompound:
3307     return T->isCompoundType();
3308   case UTT_IsMemberPointer:
3309     return T->isMemberPointerType();
3310 
3311     // Type trait expressions which correspond to the type property predicates
3312     // in C++0x [meta.unary.prop].
3313   case UTT_IsConst:
3314     return T.isConstQualified();
3315   case UTT_IsVolatile:
3316     return T.isVolatileQualified();
3317   case UTT_IsTrivial:
3318     return T.isTrivialType(Self.Context);
3319   case UTT_IsTriviallyCopyable:
3320     return T.isTriviallyCopyableType(Self.Context);
3321   case UTT_IsStandardLayout:
3322     return T->isStandardLayoutType();
3323   case UTT_IsPOD:
3324     return T.isPODType(Self.Context);
3325   case UTT_IsLiteral:
3326     return T->isLiteralType(Self.Context);
3327   case UTT_IsEmpty:
3328     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3329       return !RD->isUnion() && RD->isEmpty();
3330     return false;
3331   case UTT_IsPolymorphic:
3332     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3333       return RD->isPolymorphic();
3334     return false;
3335   case UTT_IsAbstract:
3336     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3337       return RD->isAbstract();
3338     return false;
3339   case UTT_IsInterfaceClass:
3340     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3341       return RD->isInterface();
3342     return false;
3343   case UTT_IsFinal:
3344     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3345       return RD->hasAttr<FinalAttr>();
3346     return false;
3347   case UTT_IsSealed:
3348     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3349       if (FinalAttr *FA = RD->getAttr<FinalAttr>())
3350         return FA->isSpelledAsSealed();
3351     return false;
3352   case UTT_IsSigned:
3353     return T->isSignedIntegerType();
3354   case UTT_IsUnsigned:
3355     return T->isUnsignedIntegerType();
3356 
3357     // Type trait expressions which query classes regarding their construction,
3358     // destruction, and copying. Rather than being based directly on the
3359     // related type predicates in the standard, they are specified by both
3360     // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3361     // specifications.
3362     //
3363     //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3364     //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3365     //
3366     // Note that these builtins do not behave as documented in g++: if a class
3367     // has both a trivial and a non-trivial special member of a particular kind,
3368     // they return false! For now, we emulate this behavior.
3369     // FIXME: This appears to be a g++ bug: more complex cases reveal that it
3370     // does not correctly compute triviality in the presence of multiple special
3371     // members of the same kind. Revisit this once the g++ bug is fixed.
3372   case UTT_HasTrivialDefaultConstructor:
3373     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3374     //   If __is_pod (type) is true then the trait is true, else if type is
3375     //   a cv class or union type (or array thereof) with a trivial default
3376     //   constructor ([class.ctor]) then the trait is true, else it is false.
3377     if (T.isPODType(Self.Context))
3378       return true;
3379     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3380       return RD->hasTrivialDefaultConstructor() &&
3381              !RD->hasNonTrivialDefaultConstructor();
3382     return false;
3383   case UTT_HasTrivialMoveConstructor:
3384     //  This trait is implemented by MSVC 2012 and needed to parse the
3385     //  standard library headers. Specifically this is used as the logic
3386     //  behind std::is_trivially_move_constructible (20.9.4.3).
3387     if (T.isPODType(Self.Context))
3388       return true;
3389     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3390       return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
3391     return false;
3392   case UTT_HasTrivialCopy:
3393     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3394     //   If __is_pod (type) is true or type is a reference type then
3395     //   the trait is true, else if type is a cv class or union type
3396     //   with a trivial copy constructor ([class.copy]) then the trait
3397     //   is true, else it is false.
3398     if (T.isPODType(Self.Context) || T->isReferenceType())
3399       return true;
3400     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3401       return RD->hasTrivialCopyConstructor() &&
3402              !RD->hasNonTrivialCopyConstructor();
3403     return false;
3404   case UTT_HasTrivialMoveAssign:
3405     //  This trait is implemented by MSVC 2012 and needed to parse the
3406     //  standard library headers. Specifically it is used as the logic
3407     //  behind std::is_trivially_move_assignable (20.9.4.3)
3408     if (T.isPODType(Self.Context))
3409       return true;
3410     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3411       return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
3412     return false;
3413   case UTT_HasTrivialAssign:
3414     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3415     //   If type is const qualified or is a reference type then the
3416     //   trait is false. Otherwise if __is_pod (type) is true then the
3417     //   trait is true, else if type is a cv class or union type with
3418     //   a trivial copy assignment ([class.copy]) then the trait is
3419     //   true, else it is false.
3420     // Note: the const and reference restrictions are interesting,
3421     // given that const and reference members don't prevent a class
3422     // from having a trivial copy assignment operator (but do cause
3423     // errors if the copy assignment operator is actually used, q.v.
3424     // [class.copy]p12).
3425 
3426     if (T.isConstQualified())
3427       return false;
3428     if (T.isPODType(Self.Context))
3429       return true;
3430     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3431       return RD->hasTrivialCopyAssignment() &&
3432              !RD->hasNonTrivialCopyAssignment();
3433     return false;
3434   case UTT_HasTrivialDestructor:
3435     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3436     //   If __is_pod (type) is true or type is a reference type
3437     //   then the trait is true, else if type is a cv class or union
3438     //   type (or array thereof) with a trivial destructor
3439     //   ([class.dtor]) then the trait is true, else it is
3440     //   false.
3441     if (T.isPODType(Self.Context) || T->isReferenceType())
3442       return true;
3443 
3444     // Objective-C++ ARC: autorelease types don't require destruction.
3445     if (T->isObjCLifetimeType() &&
3446         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3447       return true;
3448 
3449     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3450       return RD->hasTrivialDestructor();
3451     return false;
3452   // TODO: Propagate nothrowness for implicitly declared special members.
3453   case UTT_HasNothrowAssign:
3454     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3455     //   If type is const qualified or is a reference type then the
3456     //   trait is false. Otherwise if __has_trivial_assign (type)
3457     //   is true then the trait is true, else if type is a cv class
3458     //   or union type with copy assignment operators that are known
3459     //   not to throw an exception then the trait is true, else it is
3460     //   false.
3461     if (C.getBaseElementType(T).isConstQualified())
3462       return false;
3463     if (T->isReferenceType())
3464       return false;
3465     if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3466       return true;
3467 
3468     if (const RecordType *RT = T->getAs<RecordType>())
3469       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3470                                 &CXXRecordDecl::hasTrivialCopyAssignment,
3471                                 &CXXRecordDecl::hasNonTrivialCopyAssignment,
3472                                 &CXXMethodDecl::isCopyAssignmentOperator);
3473     return false;
3474   case UTT_HasNothrowMoveAssign:
3475     //  This trait is implemented by MSVC 2012 and needed to parse the
3476     //  standard library headers. Specifically this is used as the logic
3477     //  behind std::is_nothrow_move_assignable (20.9.4.3).
3478     if (T.isPODType(Self.Context))
3479       return true;
3480 
3481     if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
3482       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3483                                 &CXXRecordDecl::hasTrivialMoveAssignment,
3484                                 &CXXRecordDecl::hasNonTrivialMoveAssignment,
3485                                 &CXXMethodDecl::isMoveAssignmentOperator);
3486     return false;
3487   case UTT_HasNothrowCopy:
3488     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3489     //   If __has_trivial_copy (type) is true then the trait is true, else
3490     //   if type is a cv class or union type with copy constructors that are
3491     //   known not to throw an exception then the trait is true, else it is
3492     //   false.
3493     if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
3494       return true;
3495     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
3496       if (RD->hasTrivialCopyConstructor() &&
3497           !RD->hasNonTrivialCopyConstructor())
3498         return true;
3499 
3500       bool FoundConstructor = false;
3501       unsigned FoundTQs;
3502       DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3503       for (DeclContext::lookup_const_iterator Con = R.begin(),
3504            ConEnd = R.end(); Con != ConEnd; ++Con) {
3505         // A template constructor is never a copy constructor.
3506         // FIXME: However, it may actually be selected at the actual overload
3507         // resolution point.
3508         if (isa<FunctionTemplateDecl>(*Con))
3509           continue;
3510         CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3511         if (Constructor->isCopyConstructor(FoundTQs)) {
3512           FoundConstructor = true;
3513           const FunctionProtoType *CPT
3514               = Constructor->getType()->getAs<FunctionProtoType>();
3515           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3516           if (!CPT)
3517             return false;
3518           // FIXME: check whether evaluating default arguments can throw.
3519           // For now, we'll be conservative and assume that they can throw.
3520           if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3521             return false;
3522         }
3523       }
3524 
3525       return FoundConstructor;
3526     }
3527     return false;
3528   case UTT_HasNothrowConstructor:
3529     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3530     //   If __has_trivial_constructor (type) is true then the trait is
3531     //   true, else if type is a cv class or union type (or array
3532     //   thereof) with a default constructor that is known not to
3533     //   throw an exception then the trait is true, else it is false.
3534     if (T.isPODType(C) || T->isObjCLifetimeType())
3535       return true;
3536     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
3537       if (RD->hasTrivialDefaultConstructor() &&
3538           !RD->hasNonTrivialDefaultConstructor())
3539         return true;
3540 
3541       DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3542       for (DeclContext::lookup_const_iterator Con = R.begin(),
3543            ConEnd = R.end(); Con != ConEnd; ++Con) {
3544         // FIXME: In C++0x, a constructor template can be a default constructor.
3545         if (isa<FunctionTemplateDecl>(*Con))
3546           continue;
3547         CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3548         if (Constructor->isDefaultConstructor()) {
3549           const FunctionProtoType *CPT
3550               = Constructor->getType()->getAs<FunctionProtoType>();
3551           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3552           if (!CPT)
3553             return false;
3554           // TODO: check whether evaluating default arguments can throw.
3555           // For now, we'll be conservative and assume that they can throw.
3556           return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
3557         }
3558       }
3559     }
3560     return false;
3561   case UTT_HasVirtualDestructor:
3562     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3563     //   If type is a class type with a virtual destructor ([class.dtor])
3564     //   then the trait is true, else it is false.
3565     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3566       if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
3567         return Destructor->isVirtual();
3568     return false;
3569 
3570     // These type trait expressions are modeled on the specifications for the
3571     // Embarcadero C++0x type trait functions:
3572     //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3573   case UTT_IsCompleteType:
3574     // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3575     //   Returns True if and only if T is a complete type at the point of the
3576     //   function call.
3577     return !T->isIncompleteType();
3578   }
3579   llvm_unreachable("Type trait not covered by switch");
3580 }
3581 
3582 ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
3583                                      SourceLocation KWLoc,
3584                                      TypeSourceInfo *TSInfo,
3585                                      SourceLocation RParen) {
3586   QualType T = TSInfo->getType();
3587   if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3588     return ExprError();
3589 
3590   bool Value = false;
3591   if (!T->isDependentType())
3592     Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
3593 
3594   return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
3595                                                 RParen, Context.BoolTy));
3596 }
3597 
3598 ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3599                                       SourceLocation KWLoc,
3600                                       ParsedType LhsTy,
3601                                       ParsedType RhsTy,
3602                                       SourceLocation RParen) {
3603   TypeSourceInfo *LhsTSInfo;
3604   QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3605   if (!LhsTSInfo)
3606     LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3607 
3608   TypeSourceInfo *RhsTSInfo;
3609   QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3610   if (!RhsTSInfo)
3611     RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3612 
3613   return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3614 }
3615 
3616 /// \brief Determine whether T has a non-trivial Objective-C lifetime in
3617 /// ARC mode.
3618 static bool hasNontrivialObjCLifetime(QualType T) {
3619   switch (T.getObjCLifetime()) {
3620   case Qualifiers::OCL_ExplicitNone:
3621     return false;
3622 
3623   case Qualifiers::OCL_Strong:
3624   case Qualifiers::OCL_Weak:
3625   case Qualifiers::OCL_Autoreleasing:
3626     return true;
3627 
3628   case Qualifiers::OCL_None:
3629     return T->isObjCLifetimeType();
3630   }
3631 
3632   llvm_unreachable("Unknown ObjC lifetime qualifier");
3633 }
3634 
3635 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3636                               ArrayRef<TypeSourceInfo *> Args,
3637                               SourceLocation RParenLoc) {
3638   switch (Kind) {
3639   case clang::TT_IsTriviallyConstructible: {
3640     // C++11 [meta.unary.prop]:
3641     //   is_trivially_constructible is defined as:
3642     //
3643     //     is_constructible<T, Args...>::value is true and the variable
3644     //     definition for is_constructible, as defined below, is known to call
3645     //     no operation that is not trivial.
3646     //
3647     //   The predicate condition for a template specialization
3648     //   is_constructible<T, Args...> shall be satisfied if and only if the
3649     //   following variable definition would be well-formed for some invented
3650     //   variable t:
3651     //
3652     //     T t(create<Args>()...);
3653     if (Args.empty()) {
3654       S.Diag(KWLoc, diag::err_type_trait_arity)
3655         << 1 << 1 << 1 << (int)Args.size();
3656       return false;
3657     }
3658 
3659     // Precondition: T and all types in the parameter pack Args shall be
3660     // complete types, (possibly cv-qualified) void, or arrays of
3661     // unknown bound.
3662     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3663       QualType ArgTy = Args[I]->getType();
3664       if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
3665         continue;
3666 
3667       if (S.RequireCompleteType(KWLoc, ArgTy,
3668           diag::err_incomplete_type_used_in_type_trait_expr))
3669         return false;
3670     }
3671 
3672     // Make sure the first argument is a complete type.
3673     if (Args[0]->getType()->isIncompleteType())
3674       return false;
3675 
3676     SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3677     SmallVector<Expr *, 2> ArgExprs;
3678     ArgExprs.reserve(Args.size() - 1);
3679     for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3680       QualType T = Args[I]->getType();
3681       if (T->isObjectType() || T->isFunctionType())
3682         T = S.Context.getRValueReferenceType(T);
3683       OpaqueArgExprs.push_back(
3684         OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
3685                         T.getNonLValueExprType(S.Context),
3686                         Expr::getValueKindForType(T)));
3687       ArgExprs.push_back(&OpaqueArgExprs.back());
3688     }
3689 
3690     // Perform the initialization in an unevaluated context within a SFINAE
3691     // trap at translation unit scope.
3692     EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3693     Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3694     Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3695     InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3696     InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3697                                                                  RParenLoc));
3698     InitializationSequence Init(S, To, InitKind, ArgExprs);
3699     if (Init.Failed())
3700       return false;
3701 
3702     ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
3703     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3704       return false;
3705 
3706     // Under Objective-C ARC, if the destination has non-trivial Objective-C
3707     // lifetime, this is a non-trivial construction.
3708     if (S.getLangOpts().ObjCAutoRefCount &&
3709         hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
3710       return false;
3711 
3712     // The initialization succeeded; now make sure there are no non-trivial
3713     // calls.
3714     return !Result.get()->hasNonTrivialCall(S.Context);
3715   }
3716   }
3717 
3718   return false;
3719 }
3720 
3721 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3722                                 ArrayRef<TypeSourceInfo *> Args,
3723                                 SourceLocation RParenLoc) {
3724   bool Dependent = false;
3725   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3726     if (Args[I]->getType()->isDependentType()) {
3727       Dependent = true;
3728       break;
3729     }
3730   }
3731 
3732   bool Value = false;
3733   if (!Dependent)
3734     Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3735 
3736   return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3737                                Args, RParenLoc, Value);
3738 }
3739 
3740 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3741                                 ArrayRef<ParsedType> Args,
3742                                 SourceLocation RParenLoc) {
3743   SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3744   ConvertedArgs.reserve(Args.size());
3745 
3746   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3747     TypeSourceInfo *TInfo;
3748     QualType T = GetTypeFromParser(Args[I], &TInfo);
3749     if (!TInfo)
3750       TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3751 
3752     ConvertedArgs.push_back(TInfo);
3753   }
3754 
3755   return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3756 }
3757 
3758 static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3759                                     QualType LhsT, QualType RhsT,
3760                                     SourceLocation KeyLoc) {
3761   assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3762          "Cannot evaluate traits of dependent types");
3763 
3764   switch(BTT) {
3765   case BTT_IsBaseOf: {
3766     // C++0x [meta.rel]p2
3767     // Base is a base class of Derived without regard to cv-qualifiers or
3768     // Base and Derived are not unions and name the same class type without
3769     // regard to cv-qualifiers.
3770 
3771     const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3772     if (!lhsRecord) return false;
3773 
3774     const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3775     if (!rhsRecord) return false;
3776 
3777     assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3778              == (lhsRecord == rhsRecord));
3779 
3780     if (lhsRecord == rhsRecord)
3781       return !lhsRecord->getDecl()->isUnion();
3782 
3783     // C++0x [meta.rel]p2:
3784     //   If Base and Derived are class types and are different types
3785     //   (ignoring possible cv-qualifiers) then Derived shall be a
3786     //   complete type.
3787     if (Self.RequireCompleteType(KeyLoc, RhsT,
3788                           diag::err_incomplete_type_used_in_type_trait_expr))
3789       return false;
3790 
3791     return cast<CXXRecordDecl>(rhsRecord->getDecl())
3792       ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3793   }
3794   case BTT_IsSame:
3795     return Self.Context.hasSameType(LhsT, RhsT);
3796   case BTT_TypeCompatible:
3797     return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3798                                            RhsT.getUnqualifiedType());
3799   case BTT_IsConvertible:
3800   case BTT_IsConvertibleTo: {
3801     // C++0x [meta.rel]p4:
3802     //   Given the following function prototype:
3803     //
3804     //     template <class T>
3805     //       typename add_rvalue_reference<T>::type create();
3806     //
3807     //   the predicate condition for a template specialization
3808     //   is_convertible<From, To> shall be satisfied if and only if
3809     //   the return expression in the following code would be
3810     //   well-formed, including any implicit conversions to the return
3811     //   type of the function:
3812     //
3813     //     To test() {
3814     //       return create<From>();
3815     //     }
3816     //
3817     //   Access checking is performed as if in a context unrelated to To and
3818     //   From. Only the validity of the immediate context of the expression
3819     //   of the return-statement (including conversions to the return type)
3820     //   is considered.
3821     //
3822     // We model the initialization as a copy-initialization of a temporary
3823     // of the appropriate type, which for this expression is identical to the
3824     // return statement (since NRVO doesn't apply).
3825 
3826     // Functions aren't allowed to return function or array types.
3827     if (RhsT->isFunctionType() || RhsT->isArrayType())
3828       return false;
3829 
3830     // A return statement in a void function must have void type.
3831     if (RhsT->isVoidType())
3832       return LhsT->isVoidType();
3833 
3834     // A function definition requires a complete, non-abstract return type.
3835     if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
3836         Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
3837       return false;
3838 
3839     // Compute the result of add_rvalue_reference.
3840     if (LhsT->isObjectType() || LhsT->isFunctionType())
3841       LhsT = Self.Context.getRValueReferenceType(LhsT);
3842 
3843     // Build a fake source and destination for initialization.
3844     InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
3845     OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3846                          Expr::getValueKindForType(LhsT));
3847     Expr *FromPtr = &From;
3848     InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3849                                                            SourceLocation()));
3850 
3851     // Perform the initialization in an unevaluated context within a SFINAE
3852     // trap at translation unit scope.
3853     EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3854     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3855     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3856     InitializationSequence Init(Self, To, Kind, FromPtr);
3857     if (Init.Failed())
3858       return false;
3859 
3860     ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
3861     return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3862   }
3863 
3864   case BTT_IsTriviallyAssignable: {
3865     // C++11 [meta.unary.prop]p3:
3866     //   is_trivially_assignable is defined as:
3867     //     is_assignable<T, U>::value is true and the assignment, as defined by
3868     //     is_assignable, is known to call no operation that is not trivial
3869     //
3870     //   is_assignable is defined as:
3871     //     The expression declval<T>() = declval<U>() is well-formed when
3872     //     treated as an unevaluated operand (Clause 5).
3873     //
3874     //   For both, T and U shall be complete types, (possibly cv-qualified)
3875     //   void, or arrays of unknown bound.
3876     if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3877         Self.RequireCompleteType(KeyLoc, LhsT,
3878           diag::err_incomplete_type_used_in_type_trait_expr))
3879       return false;
3880     if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3881         Self.RequireCompleteType(KeyLoc, RhsT,
3882           diag::err_incomplete_type_used_in_type_trait_expr))
3883       return false;
3884 
3885     // cv void is never assignable.
3886     if (LhsT->isVoidType() || RhsT->isVoidType())
3887       return false;
3888 
3889     // Build expressions that emulate the effect of declval<T>() and
3890     // declval<U>().
3891     if (LhsT->isObjectType() || LhsT->isFunctionType())
3892       LhsT = Self.Context.getRValueReferenceType(LhsT);
3893     if (RhsT->isObjectType() || RhsT->isFunctionType())
3894       RhsT = Self.Context.getRValueReferenceType(RhsT);
3895     OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3896                         Expr::getValueKindForType(LhsT));
3897     OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3898                         Expr::getValueKindForType(RhsT));
3899 
3900     // Attempt the assignment in an unevaluated context within a SFINAE
3901     // trap at translation unit scope.
3902     EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3903     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3904     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3905     ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3906     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3907       return false;
3908 
3909     // Under Objective-C ARC, if the destination has non-trivial Objective-C
3910     // lifetime, this is a non-trivial assignment.
3911     if (Self.getLangOpts().ObjCAutoRefCount &&
3912         hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
3913       return false;
3914 
3915     return !Result.get()->hasNonTrivialCall(Self.Context);
3916   }
3917   }
3918   llvm_unreachable("Unknown type trait or not implemented");
3919 }
3920 
3921 ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3922                                       SourceLocation KWLoc,
3923                                       TypeSourceInfo *LhsTSInfo,
3924                                       TypeSourceInfo *RhsTSInfo,
3925                                       SourceLocation RParen) {
3926   QualType LhsT = LhsTSInfo->getType();
3927   QualType RhsT = RhsTSInfo->getType();
3928 
3929   if (BTT == BTT_TypeCompatible) {
3930     if (getLangOpts().CPlusPlus) {
3931       Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3932         << SourceRange(KWLoc, RParen);
3933       return ExprError();
3934     }
3935   }
3936 
3937   bool Value = false;
3938   if (!LhsT->isDependentType() && !RhsT->isDependentType())
3939     Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3940 
3941   // Select trait result type.
3942   QualType ResultType;
3943   switch (BTT) {
3944   case BTT_IsBaseOf:       ResultType = Context.BoolTy; break;
3945   case BTT_IsConvertible:  ResultType = Context.BoolTy; break;
3946   case BTT_IsSame:         ResultType = Context.BoolTy; break;
3947   case BTT_TypeCompatible: ResultType = Context.IntTy; break;
3948   case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
3949   case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
3950   }
3951 
3952   return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3953                                                  RhsTSInfo, Value, RParen,
3954                                                  ResultType));
3955 }
3956 
3957 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3958                                      SourceLocation KWLoc,
3959                                      ParsedType Ty,
3960                                      Expr* DimExpr,
3961                                      SourceLocation RParen) {
3962   TypeSourceInfo *TSInfo;
3963   QualType T = GetTypeFromParser(Ty, &TSInfo);
3964   if (!TSInfo)
3965     TSInfo = Context.getTrivialTypeSourceInfo(T);
3966 
3967   return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3968 }
3969 
3970 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3971                                            QualType T, Expr *DimExpr,
3972                                            SourceLocation KeyLoc) {
3973   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3974 
3975   switch(ATT) {
3976   case ATT_ArrayRank:
3977     if (T->isArrayType()) {
3978       unsigned Dim = 0;
3979       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3980         ++Dim;
3981         T = AT->getElementType();
3982       }
3983       return Dim;
3984     }
3985     return 0;
3986 
3987   case ATT_ArrayExtent: {
3988     llvm::APSInt Value;
3989     uint64_t Dim;
3990     if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3991           diag::err_dimension_expr_not_constant_integer,
3992           false).isInvalid())
3993       return 0;
3994     if (Value.isSigned() && Value.isNegative()) {
3995       Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3996         << DimExpr->getSourceRange();
3997       return 0;
3998     }
3999     Dim = Value.getLimitedValue();
4000 
4001     if (T->isArrayType()) {
4002       unsigned D = 0;
4003       bool Matched = false;
4004       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4005         if (Dim == D) {
4006           Matched = true;
4007           break;
4008         }
4009         ++D;
4010         T = AT->getElementType();
4011       }
4012 
4013       if (Matched && T->isArrayType()) {
4014         if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4015           return CAT->getSize().getLimitedValue();
4016       }
4017     }
4018     return 0;
4019   }
4020   }
4021   llvm_unreachable("Unknown type trait or not implemented");
4022 }
4023 
4024 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4025                                      SourceLocation KWLoc,
4026                                      TypeSourceInfo *TSInfo,
4027                                      Expr* DimExpr,
4028                                      SourceLocation RParen) {
4029   QualType T = TSInfo->getType();
4030 
4031   // FIXME: This should likely be tracked as an APInt to remove any host
4032   // assumptions about the width of size_t on the target.
4033   uint64_t Value = 0;
4034   if (!T->isDependentType())
4035     Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4036 
4037   // While the specification for these traits from the Embarcadero C++
4038   // compiler's documentation says the return type is 'unsigned int', Clang
4039   // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4040   // compiler, there is no difference. On several other platforms this is an
4041   // important distinction.
4042   return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
4043                                                 DimExpr, RParen,
4044                                                 Context.getSizeType()));
4045 }
4046 
4047 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
4048                                       SourceLocation KWLoc,
4049                                       Expr *Queried,
4050                                       SourceLocation RParen) {
4051   // If error parsing the expression, ignore.
4052   if (!Queried)
4053     return ExprError();
4054 
4055   ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
4056 
4057   return Result;
4058 }
4059 
4060 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4061   switch (ET) {
4062   case ET_IsLValueExpr: return E->isLValue();
4063   case ET_IsRValueExpr: return E->isRValue();
4064   }
4065   llvm_unreachable("Expression trait not covered by switch");
4066 }
4067 
4068 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
4069                                       SourceLocation KWLoc,
4070                                       Expr *Queried,
4071                                       SourceLocation RParen) {
4072   if (Queried->isTypeDependent()) {
4073     // Delay type-checking for type-dependent expressions.
4074   } else if (Queried->getType()->isPlaceholderType()) {
4075     ExprResult PE = CheckPlaceholderExpr(Queried);
4076     if (PE.isInvalid()) return ExprError();
4077     return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
4078   }
4079 
4080   bool Value = EvaluateExpressionTrait(ET, Queried);
4081 
4082   return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
4083                                                  RParen, Context.BoolTy));
4084 }
4085 
4086 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
4087                                             ExprValueKind &VK,
4088                                             SourceLocation Loc,
4089                                             bool isIndirect) {
4090   assert(!LHS.get()->getType()->isPlaceholderType() &&
4091          !RHS.get()->getType()->isPlaceholderType() &&
4092          "placeholders should have been weeded out by now");
4093 
4094   // The LHS undergoes lvalue conversions if this is ->*.
4095   if (isIndirect) {
4096     LHS = DefaultLvalueConversion(LHS.take());
4097     if (LHS.isInvalid()) return QualType();
4098   }
4099 
4100   // The RHS always undergoes lvalue conversions.
4101   RHS = DefaultLvalueConversion(RHS.take());
4102   if (RHS.isInvalid()) return QualType();
4103 
4104   const char *OpSpelling = isIndirect ? "->*" : ".*";
4105   // C++ 5.5p2
4106   //   The binary operator .* [p3: ->*] binds its second operand, which shall
4107   //   be of type "pointer to member of T" (where T is a completely-defined
4108   //   class type) [...]
4109   QualType RHSType = RHS.get()->getType();
4110   const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
4111   if (!MemPtr) {
4112     Diag(Loc, diag::err_bad_memptr_rhs)
4113       << OpSpelling << RHSType << RHS.get()->getSourceRange();
4114     return QualType();
4115   }
4116 
4117   QualType Class(MemPtr->getClass(), 0);
4118 
4119   // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4120   // member pointer points must be completely-defined. However, there is no
4121   // reason for this semantic distinction, and the rule is not enforced by
4122   // other compilers. Therefore, we do not check this property, as it is
4123   // likely to be considered a defect.
4124 
4125   // C++ 5.5p2
4126   //   [...] to its first operand, which shall be of class T or of a class of
4127   //   which T is an unambiguous and accessible base class. [p3: a pointer to
4128   //   such a class]
4129   QualType LHSType = LHS.get()->getType();
4130   if (isIndirect) {
4131     if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4132       LHSType = Ptr->getPointeeType();
4133     else {
4134       Diag(Loc, diag::err_bad_memptr_lhs)
4135         << OpSpelling << 1 << LHSType
4136         << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
4137       return QualType();
4138     }
4139   }
4140 
4141   if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
4142     // If we want to check the hierarchy, we need a complete type.
4143     if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4144                             OpSpelling, (int)isIndirect)) {
4145       return QualType();
4146     }
4147     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4148                        /*DetectVirtual=*/false);
4149     // FIXME: Would it be useful to print full ambiguity paths, or is that
4150     // overkill?
4151     if (!IsDerivedFrom(LHSType, Class, Paths) ||
4152         Paths.isAmbiguous(Context.getCanonicalType(Class))) {
4153       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
4154         << (int)isIndirect << LHS.get()->getType();
4155       return QualType();
4156     }
4157     // Cast LHS to type of use.
4158     QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
4159     ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
4160 
4161     CXXCastPath BasePath;
4162     BuildBasePathArray(Paths, BasePath);
4163     LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
4164                             &BasePath);
4165   }
4166 
4167   if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
4168     // Diagnose use of pointer-to-member type which when used as
4169     // the functional cast in a pointer-to-member expression.
4170     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4171      return QualType();
4172   }
4173 
4174   // C++ 5.5p2
4175   //   The result is an object or a function of the type specified by the
4176   //   second operand.
4177   // The cv qualifiers are the union of those in the pointer and the left side,
4178   // in accordance with 5.5p5 and 5.2.5.
4179   QualType Result = MemPtr->getPointeeType();
4180   Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
4181 
4182   // C++0x [expr.mptr.oper]p6:
4183   //   In a .* expression whose object expression is an rvalue, the program is
4184   //   ill-formed if the second operand is a pointer to member function with
4185   //   ref-qualifier &. In a ->* expression or in a .* expression whose object
4186   //   expression is an lvalue, the program is ill-formed if the second operand
4187   //   is a pointer to member function with ref-qualifier &&.
4188   if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4189     switch (Proto->getRefQualifier()) {
4190     case RQ_None:
4191       // Do nothing
4192       break;
4193 
4194     case RQ_LValue:
4195       if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
4196         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4197           << RHSType << 1 << LHS.get()->getSourceRange();
4198       break;
4199 
4200     case RQ_RValue:
4201       if (isIndirect || !LHS.get()->Classify(Context).isRValue())
4202         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4203           << RHSType << 0 << LHS.get()->getSourceRange();
4204       break;
4205     }
4206   }
4207 
4208   // C++ [expr.mptr.oper]p6:
4209   //   The result of a .* expression whose second operand is a pointer
4210   //   to a data member is of the same value category as its
4211   //   first operand. The result of a .* expression whose second
4212   //   operand is a pointer to a member function is a prvalue. The
4213   //   result of an ->* expression is an lvalue if its second operand
4214   //   is a pointer to data member and a prvalue otherwise.
4215   if (Result->isFunctionType()) {
4216     VK = VK_RValue;
4217     return Context.BoundMemberTy;
4218   } else if (isIndirect) {
4219     VK = VK_LValue;
4220   } else {
4221     VK = LHS.get()->getValueKind();
4222   }
4223 
4224   return Result;
4225 }
4226 
4227 /// \brief Try to convert a type to another according to C++0x 5.16p3.
4228 ///
4229 /// This is part of the parameter validation for the ? operator. If either
4230 /// value operand is a class type, the two operands are attempted to be
4231 /// converted to each other. This function does the conversion in one direction.
4232 /// It returns true if the program is ill-formed and has already been diagnosed
4233 /// as such.
4234 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4235                                 SourceLocation QuestionLoc,
4236                                 bool &HaveConversion,
4237                                 QualType &ToType) {
4238   HaveConversion = false;
4239   ToType = To->getType();
4240 
4241   InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
4242                                                            SourceLocation());
4243   // C++0x 5.16p3
4244   //   The process for determining whether an operand expression E1 of type T1
4245   //   can be converted to match an operand expression E2 of type T2 is defined
4246   //   as follows:
4247   //   -- If E2 is an lvalue:
4248   bool ToIsLvalue = To->isLValue();
4249   if (ToIsLvalue) {
4250     //   E1 can be converted to match E2 if E1 can be implicitly converted to
4251     //   type "lvalue reference to T2", subject to the constraint that in the
4252     //   conversion the reference must bind directly to E1.
4253     QualType T = Self.Context.getLValueReferenceType(ToType);
4254     InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4255 
4256     InitializationSequence InitSeq(Self, Entity, Kind, From);
4257     if (InitSeq.isDirectReferenceBinding()) {
4258       ToType = T;
4259       HaveConversion = true;
4260       return false;
4261     }
4262 
4263     if (InitSeq.isAmbiguous())
4264       return InitSeq.Diagnose(Self, Entity, Kind, From);
4265   }
4266 
4267   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
4268   //      -- if E1 and E2 have class type, and the underlying class types are
4269   //         the same or one is a base class of the other:
4270   QualType FTy = From->getType();
4271   QualType TTy = To->getType();
4272   const RecordType *FRec = FTy->getAs<RecordType>();
4273   const RecordType *TRec = TTy->getAs<RecordType>();
4274   bool FDerivedFromT = FRec && TRec && FRec != TRec &&
4275                        Self.IsDerivedFrom(FTy, TTy);
4276   if (FRec && TRec &&
4277       (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
4278     //         E1 can be converted to match E2 if the class of T2 is the
4279     //         same type as, or a base class of, the class of T1, and
4280     //         [cv2 > cv1].
4281     if (FRec == TRec || FDerivedFromT) {
4282       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
4283         InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4284         InitializationSequence InitSeq(Self, Entity, Kind, From);
4285         if (InitSeq) {
4286           HaveConversion = true;
4287           return false;
4288         }
4289 
4290         if (InitSeq.isAmbiguous())
4291           return InitSeq.Diagnose(Self, Entity, Kind, From);
4292       }
4293     }
4294 
4295     return false;
4296   }
4297 
4298   //     -- Otherwise: E1 can be converted to match E2 if E1 can be
4299   //        implicitly converted to the type that expression E2 would have
4300   //        if E2 were converted to an rvalue (or the type it has, if E2 is
4301   //        an rvalue).
4302   //
4303   // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
4304   // to the array-to-pointer or function-to-pointer conversions.
4305   if (!TTy->getAs<TagType>())
4306     TTy = TTy.getUnqualifiedType();
4307 
4308   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4309   InitializationSequence InitSeq(Self, Entity, Kind, From);
4310   HaveConversion = !InitSeq.Failed();
4311   ToType = TTy;
4312   if (InitSeq.isAmbiguous())
4313     return InitSeq.Diagnose(Self, Entity, Kind, From);
4314 
4315   return false;
4316 }
4317 
4318 /// \brief Try to find a common type for two according to C++0x 5.16p5.
4319 ///
4320 /// This is part of the parameter validation for the ? operator. If either
4321 /// value operand is a class type, overload resolution is used to find a
4322 /// conversion to a common type.
4323 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
4324                                     SourceLocation QuestionLoc) {
4325   Expr *Args[2] = { LHS.get(), RHS.get() };
4326   OverloadCandidateSet CandidateSet(QuestionLoc);
4327   Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
4328                                     CandidateSet);
4329 
4330   OverloadCandidateSet::iterator Best;
4331   switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
4332     case OR_Success: {
4333       // We found a match. Perform the conversions on the arguments and move on.
4334       ExprResult LHSRes =
4335         Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4336                                        Best->Conversions[0], Sema::AA_Converting);
4337       if (LHSRes.isInvalid())
4338         break;
4339       LHS = LHSRes;
4340 
4341       ExprResult RHSRes =
4342         Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4343                                        Best->Conversions[1], Sema::AA_Converting);
4344       if (RHSRes.isInvalid())
4345         break;
4346       RHS = RHSRes;
4347       if (Best->Function)
4348         Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
4349       return false;
4350     }
4351 
4352     case OR_No_Viable_Function:
4353 
4354       // Emit a better diagnostic if one of the expressions is a null pointer
4355       // constant and the other is a pointer type. In this case, the user most
4356       // likely forgot to take the address of the other expression.
4357       if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4358         return true;
4359 
4360       Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4361         << LHS.get()->getType() << RHS.get()->getType()
4362         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4363       return true;
4364 
4365     case OR_Ambiguous:
4366       Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
4367         << LHS.get()->getType() << RHS.get()->getType()
4368         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4369       // FIXME: Print the possible common types by printing the return types of
4370       // the viable candidates.
4371       break;
4372 
4373     case OR_Deleted:
4374       llvm_unreachable("Conditional operator has only built-in overloads");
4375   }
4376   return true;
4377 }
4378 
4379 /// \brief Perform an "extended" implicit conversion as returned by
4380 /// TryClassUnification.
4381 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
4382   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4383   InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
4384                                                            SourceLocation());
4385   Expr *Arg = E.take();
4386   InitializationSequence InitSeq(Self, Entity, Kind, Arg);
4387   ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
4388   if (Result.isInvalid())
4389     return true;
4390 
4391   E = Result;
4392   return false;
4393 }
4394 
4395 /// \brief Check the operands of ?: under C++ semantics.
4396 ///
4397 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4398 /// extension. In this case, LHS == Cond. (But they're not aliases.)
4399 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4400                                            ExprResult &RHS, ExprValueKind &VK,
4401                                            ExprObjectKind &OK,
4402                                            SourceLocation QuestionLoc) {
4403   // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4404   // interface pointers.
4405 
4406   // C++11 [expr.cond]p1
4407   //   The first expression is contextually converted to bool.
4408   if (!Cond.get()->isTypeDependent()) {
4409     ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4410     if (CondRes.isInvalid())
4411       return QualType();
4412     Cond = CondRes;
4413   }
4414 
4415   // Assume r-value.
4416   VK = VK_RValue;
4417   OK = OK_Ordinary;
4418 
4419   // Either of the arguments dependent?
4420   if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
4421     return Context.DependentTy;
4422 
4423   // C++11 [expr.cond]p2
4424   //   If either the second or the third operand has type (cv) void, ...
4425   QualType LTy = LHS.get()->getType();
4426   QualType RTy = RHS.get()->getType();
4427   bool LVoid = LTy->isVoidType();
4428   bool RVoid = RTy->isVoidType();
4429   if (LVoid || RVoid) {
4430     //   ... then the [l2r] conversions are performed on the second and third
4431     //   operands ...
4432     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4433     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4434     if (LHS.isInvalid() || RHS.isInvalid())
4435       return QualType();
4436 
4437     // Finish off the lvalue-to-rvalue conversion by copy-initializing a
4438     // temporary if necessary. DefaultFunctionArrayLvalueConversion doesn't
4439     // do this part for us.
4440     ExprResult &NonVoid = LVoid ? RHS : LHS;
4441     if (NonVoid.get()->getType()->isRecordType() &&
4442         NonVoid.get()->isGLValue()) {
4443       if (RequireNonAbstractType(QuestionLoc, NonVoid.get()->getType(),
4444                              diag::err_allocation_of_abstract_type))
4445         return QualType();
4446       InitializedEntity Entity =
4447           InitializedEntity::InitializeTemporary(NonVoid.get()->getType());
4448       NonVoid = PerformCopyInitialization(Entity, SourceLocation(), NonVoid);
4449       if (NonVoid.isInvalid())
4450         return QualType();
4451     }
4452 
4453     LTy = LHS.get()->getType();
4454     RTy = RHS.get()->getType();
4455 
4456     //   ... and one of the following shall hold:
4457     //   -- The second or the third operand (but not both) is a throw-
4458     //      expression; the result is of the type of the other and is a prvalue.
4459     bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenCasts());
4460     bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenCasts());
4461     if (LThrow && !RThrow)
4462       return RTy;
4463     if (RThrow && !LThrow)
4464       return LTy;
4465 
4466     //   -- Both the second and third operands have type void; the result is of
4467     //      type void and is a prvalue.
4468     if (LVoid && RVoid)
4469       return Context.VoidTy;
4470 
4471     // Neither holds, error.
4472     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4473       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
4474       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4475     return QualType();
4476   }
4477 
4478   // Neither is void.
4479 
4480   // C++11 [expr.cond]p3
4481   //   Otherwise, if the second and third operand have different types, and
4482   //   either has (cv) class type [...] an attempt is made to convert each of
4483   //   those operands to the type of the other.
4484   if (!Context.hasSameType(LTy, RTy) &&
4485       (LTy->isRecordType() || RTy->isRecordType())) {
4486     // These return true if a single direction is already ambiguous.
4487     QualType L2RType, R2LType;
4488     bool HaveL2R, HaveR2L;
4489     if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
4490       return QualType();
4491     if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
4492       return QualType();
4493 
4494     //   If both can be converted, [...] the program is ill-formed.
4495     if (HaveL2R && HaveR2L) {
4496       Diag(QuestionLoc, diag::err_conditional_ambiguous)
4497         << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4498       return QualType();
4499     }
4500 
4501     //   If exactly one conversion is possible, that conversion is applied to
4502     //   the chosen operand and the converted operands are used in place of the
4503     //   original operands for the remainder of this section.
4504     if (HaveL2R) {
4505       if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
4506         return QualType();
4507       LTy = LHS.get()->getType();
4508     } else if (HaveR2L) {
4509       if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
4510         return QualType();
4511       RTy = RHS.get()->getType();
4512     }
4513   }
4514 
4515   // C++11 [expr.cond]p3
4516   //   if both are glvalues of the same value category and the same type except
4517   //   for cv-qualification, an attempt is made to convert each of those
4518   //   operands to the type of the other.
4519   ExprValueKind LVK = LHS.get()->getValueKind();
4520   ExprValueKind RVK = RHS.get()->getValueKind();
4521   if (!Context.hasSameType(LTy, RTy) &&
4522       Context.hasSameUnqualifiedType(LTy, RTy) &&
4523       LVK == RVK && LVK != VK_RValue) {
4524     // Since the unqualified types are reference-related and we require the
4525     // result to be as if a reference bound directly, the only conversion
4526     // we can perform is to add cv-qualifiers.
4527     Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
4528     Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
4529     if (RCVR.isStrictSupersetOf(LCVR)) {
4530       LHS = ImpCastExprToType(LHS.take(), RTy, CK_NoOp, LVK);
4531       LTy = LHS.get()->getType();
4532     }
4533     else if (LCVR.isStrictSupersetOf(RCVR)) {
4534       RHS = ImpCastExprToType(RHS.take(), LTy, CK_NoOp, RVK);
4535       RTy = RHS.get()->getType();
4536     }
4537   }
4538 
4539   // C++11 [expr.cond]p4
4540   //   If the second and third operands are glvalues of the same value
4541   //   category and have the same type, the result is of that type and
4542   //   value category and it is a bit-field if the second or the third
4543   //   operand is a bit-field, or if both are bit-fields.
4544   // We only extend this to bitfields, not to the crazy other kinds of
4545   // l-values.
4546   bool Same = Context.hasSameType(LTy, RTy);
4547   if (Same && LVK == RVK && LVK != VK_RValue &&
4548       LHS.get()->isOrdinaryOrBitFieldObject() &&
4549       RHS.get()->isOrdinaryOrBitFieldObject()) {
4550     VK = LHS.get()->getValueKind();
4551     if (LHS.get()->getObjectKind() == OK_BitField ||
4552         RHS.get()->getObjectKind() == OK_BitField)
4553       OK = OK_BitField;
4554     return LTy;
4555   }
4556 
4557   // C++11 [expr.cond]p5
4558   //   Otherwise, the result is a prvalue. If the second and third operands
4559   //   do not have the same type, and either has (cv) class type, ...
4560   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4561     //   ... overload resolution is used to determine the conversions (if any)
4562     //   to be applied to the operands. If the overload resolution fails, the
4563     //   program is ill-formed.
4564     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4565       return QualType();
4566   }
4567 
4568   // C++11 [expr.cond]p6
4569   //   Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
4570   //   conversions are performed on the second and third operands.
4571   LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4572   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4573   if (LHS.isInvalid() || RHS.isInvalid())
4574     return QualType();
4575   LTy = LHS.get()->getType();
4576   RTy = RHS.get()->getType();
4577 
4578   //   After those conversions, one of the following shall hold:
4579   //   -- The second and third operands have the same type; the result
4580   //      is of that type. If the operands have class type, the result
4581   //      is a prvalue temporary of the result type, which is
4582   //      copy-initialized from either the second operand or the third
4583   //      operand depending on the value of the first operand.
4584   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4585     if (LTy->isRecordType()) {
4586       // The operands have class type. Make a temporary copy.
4587       if (RequireNonAbstractType(QuestionLoc, LTy,
4588                                  diag::err_allocation_of_abstract_type))
4589         return QualType();
4590       InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
4591 
4592       ExprResult LHSCopy = PerformCopyInitialization(Entity,
4593                                                      SourceLocation(),
4594                                                      LHS);
4595       if (LHSCopy.isInvalid())
4596         return QualType();
4597 
4598       ExprResult RHSCopy = PerformCopyInitialization(Entity,
4599                                                      SourceLocation(),
4600                                                      RHS);
4601       if (RHSCopy.isInvalid())
4602         return QualType();
4603 
4604       LHS = LHSCopy;
4605       RHS = RHSCopy;
4606     }
4607 
4608     return LTy;
4609   }
4610 
4611   // Extension: conditional operator involving vector types.
4612   if (LTy->isVectorType() || RTy->isVectorType())
4613     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4614 
4615   //   -- The second and third operands have arithmetic or enumeration type;
4616   //      the usual arithmetic conversions are performed to bring them to a
4617   //      common type, and the result is of that type.
4618   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4619     UsualArithmeticConversions(LHS, RHS);
4620     if (LHS.isInvalid() || RHS.isInvalid())
4621       return QualType();
4622     return LHS.get()->getType();
4623   }
4624 
4625   //   -- The second and third operands have pointer type, or one has pointer
4626   //      type and the other is a null pointer constant, or both are null
4627   //      pointer constants, at least one of which is non-integral; pointer
4628   //      conversions and qualification conversions are performed to bring them
4629   //      to their composite pointer type. The result is of the composite
4630   //      pointer type.
4631   //   -- The second and third operands have pointer to member type, or one has
4632   //      pointer to member type and the other is a null pointer constant;
4633   //      pointer to member conversions and qualification conversions are
4634   //      performed to bring them to a common type, whose cv-qualification
4635   //      shall match the cv-qualification of either the second or the third
4636   //      operand. The result is of the common type.
4637   bool NonStandardCompositeType = false;
4638   QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
4639                               isSFINAEContext()? 0 : &NonStandardCompositeType);
4640   if (!Composite.isNull()) {
4641     if (NonStandardCompositeType)
4642       Diag(QuestionLoc,
4643            diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4644         << LTy << RTy << Composite
4645         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4646 
4647     return Composite;
4648   }
4649 
4650   // Similarly, attempt to find composite type of two objective-c pointers.
4651   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4652   if (!Composite.isNull())
4653     return Composite;
4654 
4655   // Check if we are using a null with a non-pointer type.
4656   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4657     return QualType();
4658 
4659   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4660     << LHS.get()->getType() << RHS.get()->getType()
4661     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4662   return QualType();
4663 }
4664 
4665 /// \brief Find a merged pointer type and convert the two expressions to it.
4666 ///
4667 /// This finds the composite pointer type (or member pointer type) for @p E1
4668 /// and @p E2 according to C++11 5.9p2. It converts both expressions to this
4669 /// type and returns it.
4670 /// It does not emit diagnostics.
4671 ///
4672 /// \param Loc The location of the operator requiring these two expressions to
4673 /// be converted to the composite pointer type.
4674 ///
4675 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4676 /// a non-standard (but still sane) composite type to which both expressions
4677 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4678 /// will be set true.
4679 QualType Sema::FindCompositePointerType(SourceLocation Loc,
4680                                         Expr *&E1, Expr *&E2,
4681                                         bool *NonStandardCompositeType) {
4682   if (NonStandardCompositeType)
4683     *NonStandardCompositeType = false;
4684 
4685   assert(getLangOpts().CPlusPlus && "This function assumes C++");
4686   QualType T1 = E1->getType(), T2 = E2->getType();
4687 
4688   // C++11 5.9p2
4689   //   Pointer conversions and qualification conversions are performed on
4690   //   pointer operands to bring them to their composite pointer type. If
4691   //   one operand is a null pointer constant, the composite pointer type is
4692   //   std::nullptr_t if the other operand is also a null pointer constant or,
4693   //   if the other operand is a pointer, the type of the other operand.
4694   if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4695       !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
4696     if (T1->isNullPtrType() &&
4697         E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4698       E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4699       return T1;
4700     }
4701     if (T2->isNullPtrType() &&
4702         E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4703       E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4704       return T2;
4705     }
4706     return QualType();
4707   }
4708 
4709   if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4710     if (T2->isMemberPointerType())
4711       E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
4712     else
4713       E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4714     return T2;
4715   }
4716   if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4717     if (T1->isMemberPointerType())
4718       E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
4719     else
4720       E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4721     return T1;
4722   }
4723 
4724   // Now both have to be pointers or member pointers.
4725   if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4726       (!T2->isPointerType() && !T2->isMemberPointerType()))
4727     return QualType();
4728 
4729   //   Otherwise, of one of the operands has type "pointer to cv1 void," then
4730   //   the other has type "pointer to cv2 T" and the composite pointer type is
4731   //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4732   //   Otherwise, the composite pointer type is a pointer type similar to the
4733   //   type of one of the operands, with a cv-qualification signature that is
4734   //   the union of the cv-qualification signatures of the operand types.
4735   // In practice, the first part here is redundant; it's subsumed by the second.
4736   // What we do here is, we build the two possible composite types, and try the
4737   // conversions in both directions. If only one works, or if the two composite
4738   // types are the same, we have succeeded.
4739   // FIXME: extended qualifiers?
4740   typedef SmallVector<unsigned, 4> QualifierVector;
4741   QualifierVector QualifierUnion;
4742   typedef SmallVector<std::pair<const Type *, const Type *>, 4>
4743       ContainingClassVector;
4744   ContainingClassVector MemberOfClass;
4745   QualType Composite1 = Context.getCanonicalType(T1),
4746            Composite2 = Context.getCanonicalType(T2);
4747   unsigned NeedConstBefore = 0;
4748   do {
4749     const PointerType *Ptr1, *Ptr2;
4750     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4751         (Ptr2 = Composite2->getAs<PointerType>())) {
4752       Composite1 = Ptr1->getPointeeType();
4753       Composite2 = Ptr2->getPointeeType();
4754 
4755       // If we're allowed to create a non-standard composite type, keep track
4756       // of where we need to fill in additional 'const' qualifiers.
4757       if (NonStandardCompositeType &&
4758           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4759         NeedConstBefore = QualifierUnion.size();
4760 
4761       QualifierUnion.push_back(
4762                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4763       MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4764       continue;
4765     }
4766 
4767     const MemberPointerType *MemPtr1, *MemPtr2;
4768     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4769         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4770       Composite1 = MemPtr1->getPointeeType();
4771       Composite2 = MemPtr2->getPointeeType();
4772 
4773       // If we're allowed to create a non-standard composite type, keep track
4774       // of where we need to fill in additional 'const' qualifiers.
4775       if (NonStandardCompositeType &&
4776           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4777         NeedConstBefore = QualifierUnion.size();
4778 
4779       QualifierUnion.push_back(
4780                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4781       MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4782                                              MemPtr2->getClass()));
4783       continue;
4784     }
4785 
4786     // FIXME: block pointer types?
4787 
4788     // Cannot unwrap any more types.
4789     break;
4790   } while (true);
4791 
4792   if (NeedConstBefore && NonStandardCompositeType) {
4793     // Extension: Add 'const' to qualifiers that come before the first qualifier
4794     // mismatch, so that our (non-standard!) composite type meets the
4795     // requirements of C++ [conv.qual]p4 bullet 3.
4796     for (unsigned I = 0; I != NeedConstBefore; ++I) {
4797       if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4798         QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4799         *NonStandardCompositeType = true;
4800       }
4801     }
4802   }
4803 
4804   // Rewrap the composites as pointers or member pointers with the union CVRs.
4805   ContainingClassVector::reverse_iterator MOC
4806     = MemberOfClass.rbegin();
4807   for (QualifierVector::reverse_iterator
4808          I = QualifierUnion.rbegin(),
4809          E = QualifierUnion.rend();
4810        I != E; (void)++I, ++MOC) {
4811     Qualifiers Quals = Qualifiers::fromCVRMask(*I);
4812     if (MOC->first && MOC->second) {
4813       // Rebuild member pointer type
4814       Composite1 = Context.getMemberPointerType(
4815                                     Context.getQualifiedType(Composite1, Quals),
4816                                     MOC->first);
4817       Composite2 = Context.getMemberPointerType(
4818                                     Context.getQualifiedType(Composite2, Quals),
4819                                     MOC->second);
4820     } else {
4821       // Rebuild pointer type
4822       Composite1
4823         = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4824       Composite2
4825         = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
4826     }
4827   }
4828 
4829   // Try to convert to the first composite pointer type.
4830   InitializedEntity Entity1
4831     = InitializedEntity::InitializeTemporary(Composite1);
4832   InitializationKind Kind
4833     = InitializationKind::CreateCopy(Loc, SourceLocation());
4834   InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
4835   InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
4836 
4837   if (E1ToC1 && E2ToC1) {
4838     // Conversion to Composite1 is viable.
4839     if (!Context.hasSameType(Composite1, Composite2)) {
4840       // Composite2 is a different type from Composite1. Check whether
4841       // Composite2 is also viable.
4842       InitializedEntity Entity2
4843         = InitializedEntity::InitializeTemporary(Composite2);
4844       InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4845       InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
4846       if (E1ToC2 && E2ToC2) {
4847         // Both Composite1 and Composite2 are viable and are different;
4848         // this is an ambiguity.
4849         return QualType();
4850       }
4851     }
4852 
4853     // Convert E1 to Composite1
4854     ExprResult E1Result
4855       = E1ToC1.Perform(*this, Entity1, Kind, E1);
4856     if (E1Result.isInvalid())
4857       return QualType();
4858     E1 = E1Result.takeAs<Expr>();
4859 
4860     // Convert E2 to Composite1
4861     ExprResult E2Result
4862       = E2ToC1.Perform(*this, Entity1, Kind, E2);
4863     if (E2Result.isInvalid())
4864       return QualType();
4865     E2 = E2Result.takeAs<Expr>();
4866 
4867     return Composite1;
4868   }
4869 
4870   // Check whether Composite2 is viable.
4871   InitializedEntity Entity2
4872     = InitializedEntity::InitializeTemporary(Composite2);
4873   InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4874   InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
4875   if (!E1ToC2 || !E2ToC2)
4876     return QualType();
4877 
4878   // Convert E1 to Composite2
4879   ExprResult E1Result
4880     = E1ToC2.Perform(*this, Entity2, Kind, E1);
4881   if (E1Result.isInvalid())
4882     return QualType();
4883   E1 = E1Result.takeAs<Expr>();
4884 
4885   // Convert E2 to Composite2
4886   ExprResult E2Result
4887     = E2ToC2.Perform(*this, Entity2, Kind, E2);
4888   if (E2Result.isInvalid())
4889     return QualType();
4890   E2 = E2Result.takeAs<Expr>();
4891 
4892   return Composite2;
4893 }
4894 
4895 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
4896   if (!E)
4897     return ExprError();
4898 
4899   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4900 
4901   // If the result is a glvalue, we shouldn't bind it.
4902   if (!E->isRValue())
4903     return Owned(E);
4904 
4905   // In ARC, calls that return a retainable type can return retained,
4906   // in which case we have to insert a consuming cast.
4907   if (getLangOpts().ObjCAutoRefCount &&
4908       E->getType()->isObjCRetainableType()) {
4909 
4910     bool ReturnsRetained;
4911 
4912     // For actual calls, we compute this by examining the type of the
4913     // called value.
4914     if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4915       Expr *Callee = Call->getCallee()->IgnoreParens();
4916       QualType T = Callee->getType();
4917 
4918       if (T == Context.BoundMemberTy) {
4919         // Handle pointer-to-members.
4920         if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4921           T = BinOp->getRHS()->getType();
4922         else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4923           T = Mem->getMemberDecl()->getType();
4924       }
4925 
4926       if (const PointerType *Ptr = T->getAs<PointerType>())
4927         T = Ptr->getPointeeType();
4928       else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4929         T = Ptr->getPointeeType();
4930       else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4931         T = MemPtr->getPointeeType();
4932 
4933       const FunctionType *FTy = T->getAs<FunctionType>();
4934       assert(FTy && "call to value not of function type?");
4935       ReturnsRetained = FTy->getExtInfo().getProducesResult();
4936 
4937     // ActOnStmtExpr arranges things so that StmtExprs of retainable
4938     // type always produce a +1 object.
4939     } else if (isa<StmtExpr>(E)) {
4940       ReturnsRetained = true;
4941 
4942     // We hit this case with the lambda conversion-to-block optimization;
4943     // we don't want any extra casts here.
4944     } else if (isa<CastExpr>(E) &&
4945                isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4946       return Owned(E);
4947 
4948     // For message sends and property references, we try to find an
4949     // actual method.  FIXME: we should infer retention by selector in
4950     // cases where we don't have an actual method.
4951     } else {
4952       ObjCMethodDecl *D = 0;
4953       if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4954         D = Send->getMethodDecl();
4955       } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4956         D = BoxedExpr->getBoxingMethod();
4957       } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4958         D = ArrayLit->getArrayWithObjectsMethod();
4959       } else if (ObjCDictionaryLiteral *DictLit
4960                                         = dyn_cast<ObjCDictionaryLiteral>(E)) {
4961         D = DictLit->getDictWithObjectsMethod();
4962       }
4963 
4964       ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
4965 
4966       // Don't do reclaims on performSelector calls; despite their
4967       // return type, the invoked method doesn't necessarily actually
4968       // return an object.
4969       if (!ReturnsRetained &&
4970           D && D->getMethodFamily() == OMF_performSelector)
4971         return Owned(E);
4972     }
4973 
4974     // Don't reclaim an object of Class type.
4975     if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4976       return Owned(E);
4977 
4978     ExprNeedsCleanups = true;
4979 
4980     CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4981                                    : CK_ARCReclaimReturnedObject);
4982     return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4983                                           VK_RValue));
4984   }
4985 
4986   if (!getLangOpts().CPlusPlus)
4987     return Owned(E);
4988 
4989   // Search for the base element type (cf. ASTContext::getBaseElementType) with
4990   // a fast path for the common case that the type is directly a RecordType.
4991   const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4992   const RecordType *RT = 0;
4993   while (!RT) {
4994     switch (T->getTypeClass()) {
4995     case Type::Record:
4996       RT = cast<RecordType>(T);
4997       break;
4998     case Type::ConstantArray:
4999     case Type::IncompleteArray:
5000     case Type::VariableArray:
5001     case Type::DependentSizedArray:
5002       T = cast<ArrayType>(T)->getElementType().getTypePtr();
5003       break;
5004     default:
5005       return Owned(E);
5006     }
5007   }
5008 
5009   // That should be enough to guarantee that this type is complete, if we're
5010   // not processing a decltype expression.
5011   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5012   if (RD->isInvalidDecl() || RD->isDependentContext())
5013     return Owned(E);
5014 
5015   bool IsDecltype = ExprEvalContexts.back().IsDecltype;
5016   CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
5017 
5018   if (Destructor) {
5019     MarkFunctionReferenced(E->getExprLoc(), Destructor);
5020     CheckDestructorAccess(E->getExprLoc(), Destructor,
5021                           PDiag(diag::err_access_dtor_temp)
5022                             << E->getType());
5023     if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
5024       return ExprError();
5025 
5026     // If destructor is trivial, we can avoid the extra copy.
5027     if (Destructor->isTrivial())
5028       return Owned(E);
5029 
5030     // We need a cleanup, but we don't need to remember the temporary.
5031     ExprNeedsCleanups = true;
5032   }
5033 
5034   CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
5035   CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
5036 
5037   if (IsDecltype)
5038     ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
5039 
5040   return Owned(Bind);
5041 }
5042 
5043 ExprResult
5044 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
5045   if (SubExpr.isInvalid())
5046     return ExprError();
5047 
5048   return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
5049 }
5050 
5051 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
5052   assert(SubExpr && "sub expression can't be null!");
5053 
5054   CleanupVarDeclMarking();
5055 
5056   unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5057   assert(ExprCleanupObjects.size() >= FirstCleanup);
5058   assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
5059   if (!ExprNeedsCleanups)
5060     return SubExpr;
5061 
5062   ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
5063     = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5064                          ExprCleanupObjects.size() - FirstCleanup);
5065 
5066   Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
5067   DiscardCleanupsInEvaluationContext();
5068 
5069   return E;
5070 }
5071 
5072 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
5073   assert(SubStmt && "sub statement can't be null!");
5074 
5075   CleanupVarDeclMarking();
5076 
5077   if (!ExprNeedsCleanups)
5078     return SubStmt;
5079 
5080   // FIXME: In order to attach the temporaries, wrap the statement into
5081   // a StmtExpr; currently this is only used for asm statements.
5082   // This is hacky, either create a new CXXStmtWithTemporaries statement or
5083   // a new AsmStmtWithTemporaries.
5084   CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
5085                                                       SourceLocation(),
5086                                                       SourceLocation());
5087   Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5088                                    SourceLocation());
5089   return MaybeCreateExprWithCleanups(E);
5090 }
5091 
5092 /// Process the expression contained within a decltype. For such expressions,
5093 /// certain semantic checks on temporaries are delayed until this point, and
5094 /// are omitted for the 'topmost' call in the decltype expression. If the
5095 /// topmost call bound a temporary, strip that temporary off the expression.
5096 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
5097   assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
5098 
5099   // C++11 [expr.call]p11:
5100   //   If a function call is a prvalue of object type,
5101   // -- if the function call is either
5102   //   -- the operand of a decltype-specifier, or
5103   //   -- the right operand of a comma operator that is the operand of a
5104   //      decltype-specifier,
5105   //   a temporary object is not introduced for the prvalue.
5106 
5107   // Recursively rebuild ParenExprs and comma expressions to strip out the
5108   // outermost CXXBindTemporaryExpr, if any.
5109   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5110     ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5111     if (SubExpr.isInvalid())
5112       return ExprError();
5113     if (SubExpr.get() == PE->getSubExpr())
5114       return Owned(E);
5115     return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
5116   }
5117   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5118     if (BO->getOpcode() == BO_Comma) {
5119       ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5120       if (RHS.isInvalid())
5121         return ExprError();
5122       if (RHS.get() == BO->getRHS())
5123         return Owned(E);
5124       return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
5125                                                 BO_Comma, BO->getType(),
5126                                                 BO->getValueKind(),
5127                                                 BO->getObjectKind(),
5128                                                 BO->getOperatorLoc(),
5129                                                 BO->isFPContractable()));
5130     }
5131   }
5132 
5133   CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
5134   if (TopBind)
5135     E = TopBind->getSubExpr();
5136 
5137   // Disable the special decltype handling now.
5138   ExprEvalContexts.back().IsDecltype = false;
5139 
5140   // In MS mode, don't perform any extra checking of call return types within a
5141   // decltype expression.
5142   if (getLangOpts().MicrosoftMode)
5143     return Owned(E);
5144 
5145   // Perform the semantic checks we delayed until this point.
5146   CallExpr *TopCall = dyn_cast<CallExpr>(E);
5147   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5148        I != N; ++I) {
5149     CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
5150     if (Call == TopCall)
5151       continue;
5152 
5153     if (CheckCallReturnType(Call->getCallReturnType(),
5154                             Call->getLocStart(),
5155                             Call, Call->getDirectCallee()))
5156       return ExprError();
5157   }
5158 
5159   // Now all relevant types are complete, check the destructors are accessible
5160   // and non-deleted, and annotate them on the temporaries.
5161   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5162        I != N; ++I) {
5163     CXXBindTemporaryExpr *Bind =
5164       ExprEvalContexts.back().DelayedDecltypeBinds[I];
5165     if (Bind == TopBind)
5166       continue;
5167 
5168     CXXTemporary *Temp = Bind->getTemporary();
5169 
5170     CXXRecordDecl *RD =
5171       Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5172     CXXDestructorDecl *Destructor = LookupDestructor(RD);
5173     Temp->setDestructor(Destructor);
5174 
5175     MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5176     CheckDestructorAccess(Bind->getExprLoc(), Destructor,
5177                           PDiag(diag::err_access_dtor_temp)
5178                             << Bind->getType());
5179     if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5180       return ExprError();
5181 
5182     // We need a cleanup, but we don't need to remember the temporary.
5183     ExprNeedsCleanups = true;
5184   }
5185 
5186   // Possibly strip off the top CXXBindTemporaryExpr.
5187   return Owned(E);
5188 }
5189 
5190 /// Note a set of 'operator->' functions that were used for a member access.
5191 static void noteOperatorArrows(Sema &S,
5192                                llvm::ArrayRef<FunctionDecl *> OperatorArrows) {
5193   unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
5194   // FIXME: Make this configurable?
5195   unsigned Limit = 9;
5196   if (OperatorArrows.size() > Limit) {
5197     // Produce Limit-1 normal notes and one 'skipping' note.
5198     SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
5199     SkipCount = OperatorArrows.size() - (Limit - 1);
5200   }
5201 
5202   for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
5203     if (I == SkipStart) {
5204       S.Diag(OperatorArrows[I]->getLocation(),
5205              diag::note_operator_arrows_suppressed)
5206           << SkipCount;
5207       I += SkipCount;
5208     } else {
5209       S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
5210           << OperatorArrows[I]->getCallResultType();
5211       ++I;
5212     }
5213   }
5214 }
5215 
5216 ExprResult
5217 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
5218                                    tok::TokenKind OpKind, ParsedType &ObjectType,
5219                                    bool &MayBePseudoDestructor) {
5220   // Since this might be a postfix expression, get rid of ParenListExprs.
5221   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
5222   if (Result.isInvalid()) return ExprError();
5223   Base = Result.get();
5224 
5225   Result = CheckPlaceholderExpr(Base);
5226   if (Result.isInvalid()) return ExprError();
5227   Base = Result.take();
5228 
5229   QualType BaseType = Base->getType();
5230   MayBePseudoDestructor = false;
5231   if (BaseType->isDependentType()) {
5232     // If we have a pointer to a dependent type and are using the -> operator,
5233     // the object type is the type that the pointer points to. We might still
5234     // have enough information about that type to do something useful.
5235     if (OpKind == tok::arrow)
5236       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5237         BaseType = Ptr->getPointeeType();
5238 
5239     ObjectType = ParsedType::make(BaseType);
5240     MayBePseudoDestructor = true;
5241     return Owned(Base);
5242   }
5243 
5244   // C++ [over.match.oper]p8:
5245   //   [...] When operator->returns, the operator-> is applied  to the value
5246   //   returned, with the original second operand.
5247   if (OpKind == tok::arrow) {
5248     QualType StartingType = BaseType;
5249     bool NoArrowOperatorFound = false;
5250     bool FirstIteration = true;
5251     FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
5252     // The set of types we've considered so far.
5253     llvm::SmallPtrSet<CanQualType,8> CTypes;
5254     SmallVector<FunctionDecl*, 8> OperatorArrows;
5255     CTypes.insert(Context.getCanonicalType(BaseType));
5256 
5257     while (BaseType->isRecordType()) {
5258       if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
5259         Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
5260           << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
5261         noteOperatorArrows(*this, OperatorArrows);
5262         Diag(OpLoc, diag::note_operator_arrow_depth)
5263           << getLangOpts().ArrowDepth;
5264         return ExprError();
5265       }
5266 
5267       Result = BuildOverloadedArrowExpr(
5268           S, Base, OpLoc,
5269           // When in a template specialization and on the first loop iteration,
5270           // potentially give the default diagnostic (with the fixit in a
5271           // separate note) instead of having the error reported back to here
5272           // and giving a diagnostic with a fixit attached to the error itself.
5273           (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
5274               ? 0
5275               : &NoArrowOperatorFound);
5276       if (Result.isInvalid()) {
5277         if (NoArrowOperatorFound) {
5278           if (FirstIteration) {
5279             Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5280               << BaseType << 1 << Base->getSourceRange()
5281               << FixItHint::CreateReplacement(OpLoc, ".");
5282             OpKind = tok::period;
5283             break;
5284           }
5285           Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5286             << BaseType << Base->getSourceRange();
5287           CallExpr *CE = dyn_cast<CallExpr>(Base);
5288           if (Decl *CD = (CE ? CE->getCalleeDecl() : 0)) {
5289             Diag(CD->getLocStart(),
5290                  diag::note_member_reference_arrow_from_operator_arrow);
5291           }
5292         }
5293         return ExprError();
5294       }
5295       Base = Result.get();
5296       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
5297         OperatorArrows.push_back(OpCall->getDirectCallee());
5298       BaseType = Base->getType();
5299       CanQualType CBaseType = Context.getCanonicalType(BaseType);
5300       if (!CTypes.insert(CBaseType)) {
5301         Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
5302         noteOperatorArrows(*this, OperatorArrows);
5303         return ExprError();
5304       }
5305       FirstIteration = false;
5306     }
5307 
5308     if (OpKind == tok::arrow &&
5309         (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
5310       BaseType = BaseType->getPointeeType();
5311   }
5312 
5313   // Objective-C properties allow "." access on Objective-C pointer types,
5314   // so adjust the base type to the object type itself.
5315   if (BaseType->isObjCObjectPointerType())
5316     BaseType = BaseType->getPointeeType();
5317 
5318   // C++ [basic.lookup.classref]p2:
5319   //   [...] If the type of the object expression is of pointer to scalar
5320   //   type, the unqualified-id is looked up in the context of the complete
5321   //   postfix-expression.
5322   //
5323   // This also indicates that we could be parsing a pseudo-destructor-name.
5324   // Note that Objective-C class and object types can be pseudo-destructor
5325   // expressions or normal member (ivar or property) access expressions.
5326   if (BaseType->isObjCObjectOrInterfaceType()) {
5327     MayBePseudoDestructor = true;
5328   } else if (!BaseType->isRecordType()) {
5329     ObjectType = ParsedType();
5330     MayBePseudoDestructor = true;
5331     return Owned(Base);
5332   }
5333 
5334   // The object type must be complete (or dependent), or
5335   // C++11 [expr.prim.general]p3:
5336   //   Unlike the object expression in other contexts, *this is not required to
5337   //   be of complete type for purposes of class member access (5.2.5) outside
5338   //   the member function body.
5339   if (!BaseType->isDependentType() &&
5340       !isThisOutsideMemberFunctionBody(BaseType) &&
5341       RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
5342     return ExprError();
5343 
5344   // C++ [basic.lookup.classref]p2:
5345   //   If the id-expression in a class member access (5.2.5) is an
5346   //   unqualified-id, and the type of the object expression is of a class
5347   //   type C (or of pointer to a class type C), the unqualified-id is looked
5348   //   up in the scope of class C. [...]
5349   ObjectType = ParsedType::make(BaseType);
5350   return Base;
5351 }
5352 
5353 ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
5354                                                    Expr *MemExpr) {
5355   SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
5356   Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
5357     << isa<CXXPseudoDestructorExpr>(MemExpr)
5358     << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
5359 
5360   return ActOnCallExpr(/*Scope*/ 0,
5361                        MemExpr,
5362                        /*LPLoc*/ ExpectedLParenLoc,
5363                        None,
5364                        /*RPLoc*/ ExpectedLParenLoc);
5365 }
5366 
5367 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
5368                    tok::TokenKind& OpKind, SourceLocation OpLoc) {
5369   if (Base->hasPlaceholderType()) {
5370     ExprResult result = S.CheckPlaceholderExpr(Base);
5371     if (result.isInvalid()) return true;
5372     Base = result.take();
5373   }
5374   ObjectType = Base->getType();
5375 
5376   // C++ [expr.pseudo]p2:
5377   //   The left-hand side of the dot operator shall be of scalar type. The
5378   //   left-hand side of the arrow operator shall be of pointer to scalar type.
5379   //   This scalar type is the object type.
5380   // Note that this is rather different from the normal handling for the
5381   // arrow operator.
5382   if (OpKind == tok::arrow) {
5383     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
5384       ObjectType = Ptr->getPointeeType();
5385     } else if (!Base->isTypeDependent()) {
5386       // The user wrote "p->" when she probably meant "p."; fix it.
5387       S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5388         << ObjectType << true
5389         << FixItHint::CreateReplacement(OpLoc, ".");
5390       if (S.isSFINAEContext())
5391         return true;
5392 
5393       OpKind = tok::period;
5394     }
5395   }
5396 
5397   return false;
5398 }
5399 
5400 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
5401                                            SourceLocation OpLoc,
5402                                            tok::TokenKind OpKind,
5403                                            const CXXScopeSpec &SS,
5404                                            TypeSourceInfo *ScopeTypeInfo,
5405                                            SourceLocation CCLoc,
5406                                            SourceLocation TildeLoc,
5407                                          PseudoDestructorTypeStorage Destructed,
5408                                            bool HasTrailingLParen) {
5409   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
5410 
5411   QualType ObjectType;
5412   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5413     return ExprError();
5414 
5415   if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
5416       !ObjectType->isVectorType()) {
5417     if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
5418       Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
5419     else
5420       Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
5421         << ObjectType << Base->getSourceRange();
5422     return ExprError();
5423   }
5424 
5425   // C++ [expr.pseudo]p2:
5426   //   [...] The cv-unqualified versions of the object type and of the type
5427   //   designated by the pseudo-destructor-name shall be the same type.
5428   if (DestructedTypeInfo) {
5429     QualType DestructedType = DestructedTypeInfo->getType();
5430     SourceLocation DestructedTypeStart
5431       = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
5432     if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
5433       if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
5434         Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
5435           << ObjectType << DestructedType << Base->getSourceRange()
5436           << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5437 
5438         // Recover by setting the destructed type to the object type.
5439         DestructedType = ObjectType;
5440         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5441                                                            DestructedTypeStart);
5442         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5443       } else if (DestructedType.getObjCLifetime() !=
5444                                                 ObjectType.getObjCLifetime()) {
5445 
5446         if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
5447           // Okay: just pretend that the user provided the correctly-qualified
5448           // type.
5449         } else {
5450           Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
5451             << ObjectType << DestructedType << Base->getSourceRange()
5452             << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5453         }
5454 
5455         // Recover by setting the destructed type to the object type.
5456         DestructedType = ObjectType;
5457         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5458                                                            DestructedTypeStart);
5459         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5460       }
5461     }
5462   }
5463 
5464   // C++ [expr.pseudo]p2:
5465   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5466   //   form
5467   //
5468   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
5469   //
5470   //   shall designate the same scalar type.
5471   if (ScopeTypeInfo) {
5472     QualType ScopeType = ScopeTypeInfo->getType();
5473     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
5474         !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
5475 
5476       Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
5477            diag::err_pseudo_dtor_type_mismatch)
5478         << ObjectType << ScopeType << Base->getSourceRange()
5479         << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
5480 
5481       ScopeType = QualType();
5482       ScopeTypeInfo = 0;
5483     }
5484   }
5485 
5486   Expr *Result
5487     = new (Context) CXXPseudoDestructorExpr(Context, Base,
5488                                             OpKind == tok::arrow, OpLoc,
5489                                             SS.getWithLocInContext(Context),
5490                                             ScopeTypeInfo,
5491                                             CCLoc,
5492                                             TildeLoc,
5493                                             Destructed);
5494 
5495   if (HasTrailingLParen)
5496     return Owned(Result);
5497 
5498   return DiagnoseDtorReference(Destructed.getLocation(), Result);
5499 }
5500 
5501 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5502                                            SourceLocation OpLoc,
5503                                            tok::TokenKind OpKind,
5504                                            CXXScopeSpec &SS,
5505                                            UnqualifiedId &FirstTypeName,
5506                                            SourceLocation CCLoc,
5507                                            SourceLocation TildeLoc,
5508                                            UnqualifiedId &SecondTypeName,
5509                                            bool HasTrailingLParen) {
5510   assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5511           FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5512          "Invalid first type name in pseudo-destructor");
5513   assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5514           SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5515          "Invalid second type name in pseudo-destructor");
5516 
5517   QualType ObjectType;
5518   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5519     return ExprError();
5520 
5521   // Compute the object type that we should use for name lookup purposes. Only
5522   // record types and dependent types matter.
5523   ParsedType ObjectTypePtrForLookup;
5524   if (!SS.isSet()) {
5525     if (ObjectType->isRecordType())
5526       ObjectTypePtrForLookup = ParsedType::make(ObjectType);
5527     else if (ObjectType->isDependentType())
5528       ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
5529   }
5530 
5531   // Convert the name of the type being destructed (following the ~) into a
5532   // type (with source-location information).
5533   QualType DestructedType;
5534   TypeSourceInfo *DestructedTypeInfo = 0;
5535   PseudoDestructorTypeStorage Destructed;
5536   if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5537     ParsedType T = getTypeName(*SecondTypeName.Identifier,
5538                                SecondTypeName.StartLocation,
5539                                S, &SS, true, false, ObjectTypePtrForLookup);
5540     if (!T &&
5541         ((SS.isSet() && !computeDeclContext(SS, false)) ||
5542          (!SS.isSet() && ObjectType->isDependentType()))) {
5543       // The name of the type being destroyed is a dependent name, and we
5544       // couldn't find anything useful in scope. Just store the identifier and
5545       // it's location, and we'll perform (qualified) name lookup again at
5546       // template instantiation time.
5547       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5548                                                SecondTypeName.StartLocation);
5549     } else if (!T) {
5550       Diag(SecondTypeName.StartLocation,
5551            diag::err_pseudo_dtor_destructor_non_type)
5552         << SecondTypeName.Identifier << ObjectType;
5553       if (isSFINAEContext())
5554         return ExprError();
5555 
5556       // Recover by assuming we had the right type all along.
5557       DestructedType = ObjectType;
5558     } else
5559       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
5560   } else {
5561     // Resolve the template-id to a type.
5562     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
5563     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5564                                        TemplateId->NumArgs);
5565     TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5566                                        TemplateId->TemplateKWLoc,
5567                                        TemplateId->Template,
5568                                        TemplateId->TemplateNameLoc,
5569                                        TemplateId->LAngleLoc,
5570                                        TemplateArgsPtr,
5571                                        TemplateId->RAngleLoc);
5572     if (T.isInvalid() || !T.get()) {
5573       // Recover by assuming we had the right type all along.
5574       DestructedType = ObjectType;
5575     } else
5576       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
5577   }
5578 
5579   // If we've performed some kind of recovery, (re-)build the type source
5580   // information.
5581   if (!DestructedType.isNull()) {
5582     if (!DestructedTypeInfo)
5583       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
5584                                                   SecondTypeName.StartLocation);
5585     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5586   }
5587 
5588   // Convert the name of the scope type (the type prior to '::') into a type.
5589   TypeSourceInfo *ScopeTypeInfo = 0;
5590   QualType ScopeType;
5591   if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5592       FirstTypeName.Identifier) {
5593     if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
5594       ParsedType T = getTypeName(*FirstTypeName.Identifier,
5595                                  FirstTypeName.StartLocation,
5596                                  S, &SS, true, false, ObjectTypePtrForLookup);
5597       if (!T) {
5598         Diag(FirstTypeName.StartLocation,
5599              diag::err_pseudo_dtor_destructor_non_type)
5600           << FirstTypeName.Identifier << ObjectType;
5601 
5602         if (isSFINAEContext())
5603           return ExprError();
5604 
5605         // Just drop this type. It's unnecessary anyway.
5606         ScopeType = QualType();
5607       } else
5608         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
5609     } else {
5610       // Resolve the template-id to a type.
5611       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
5612       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
5613                                          TemplateId->NumArgs);
5614       TypeResult T = ActOnTemplateIdType(TemplateId->SS,
5615                                          TemplateId->TemplateKWLoc,
5616                                          TemplateId->Template,
5617                                          TemplateId->TemplateNameLoc,
5618                                          TemplateId->LAngleLoc,
5619                                          TemplateArgsPtr,
5620                                          TemplateId->RAngleLoc);
5621       if (T.isInvalid() || !T.get()) {
5622         // Recover by dropping this type.
5623         ScopeType = QualType();
5624       } else
5625         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
5626     }
5627   }
5628 
5629   if (!ScopeType.isNull() && !ScopeTypeInfo)
5630     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5631                                                   FirstTypeName.StartLocation);
5632 
5633 
5634   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
5635                                    ScopeTypeInfo, CCLoc, TildeLoc,
5636                                    Destructed, HasTrailingLParen);
5637 }
5638 
5639 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5640                                            SourceLocation OpLoc,
5641                                            tok::TokenKind OpKind,
5642                                            SourceLocation TildeLoc,
5643                                            const DeclSpec& DS,
5644                                            bool HasTrailingLParen) {
5645   QualType ObjectType;
5646   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5647     return ExprError();
5648 
5649   QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5650 
5651   TypeLocBuilder TLB;
5652   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5653   DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5654   TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5655   PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5656 
5657   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5658                                    0, SourceLocation(), TildeLoc,
5659                                    Destructed, HasTrailingLParen);
5660 }
5661 
5662 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
5663                                         CXXConversionDecl *Method,
5664                                         bool HadMultipleCandidates) {
5665   if (Method->getParent()->isLambda() &&
5666       Method->getConversionType()->isBlockPointerType()) {
5667     // This is a lambda coversion to block pointer; check if the argument
5668     // is a LambdaExpr.
5669     Expr *SubE = E;
5670     CastExpr *CE = dyn_cast<CastExpr>(SubE);
5671     if (CE && CE->getCastKind() == CK_NoOp)
5672       SubE = CE->getSubExpr();
5673     SubE = SubE->IgnoreParens();
5674     if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5675       SubE = BE->getSubExpr();
5676     if (isa<LambdaExpr>(SubE)) {
5677       // For the conversion to block pointer on a lambda expression, we
5678       // construct a special BlockLiteral instead; this doesn't really make
5679       // a difference in ARC, but outside of ARC the resulting block literal
5680       // follows the normal lifetime rules for block literals instead of being
5681       // autoreleased.
5682       DiagnosticErrorTrap Trap(Diags);
5683       ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5684                                                      E->getExprLoc(),
5685                                                      Method, E);
5686       if (Exp.isInvalid())
5687         Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5688       return Exp;
5689     }
5690   }
5691 
5692 
5693   ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5694                                           FoundDecl, Method);
5695   if (Exp.isInvalid())
5696     return true;
5697 
5698   MemberExpr *ME =
5699       new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
5700                                SourceLocation(), Context.BoundMemberTy,
5701                                VK_RValue, OK_Ordinary);
5702   if (HadMultipleCandidates)
5703     ME->setHadMultipleCandidates(true);
5704   MarkMemberReferenced(ME);
5705 
5706   QualType ResultType = Method->getResultType();
5707   ExprValueKind VK = Expr::getValueKindForType(ResultType);
5708   ResultType = ResultType.getNonLValueExprType(Context);
5709 
5710   CXXMemberCallExpr *CE =
5711     new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
5712                                     Exp.get()->getLocEnd());
5713   return CE;
5714 }
5715 
5716 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5717                                       SourceLocation RParen) {
5718   CanThrowResult CanThrow = canThrow(Operand);
5719   return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
5720                                              CanThrow, KeyLoc, RParen));
5721 }
5722 
5723 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5724                                    Expr *Operand, SourceLocation RParen) {
5725   return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
5726 }
5727 
5728 static bool IsSpecialDiscardedValue(Expr *E) {
5729   // In C++11, discarded-value expressions of a certain form are special,
5730   // according to [expr]p10:
5731   //   The lvalue-to-rvalue conversion (4.1) is applied only if the
5732   //   expression is an lvalue of volatile-qualified type and it has
5733   //   one of the following forms:
5734   E = E->IgnoreParens();
5735 
5736   //   - id-expression (5.1.1),
5737   if (isa<DeclRefExpr>(E))
5738     return true;
5739 
5740   //   - subscripting (5.2.1),
5741   if (isa<ArraySubscriptExpr>(E))
5742     return true;
5743 
5744   //   - class member access (5.2.5),
5745   if (isa<MemberExpr>(E))
5746     return true;
5747 
5748   //   - indirection (5.3.1),
5749   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5750     if (UO->getOpcode() == UO_Deref)
5751       return true;
5752 
5753   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5754     //   - pointer-to-member operation (5.5),
5755     if (BO->isPtrMemOp())
5756       return true;
5757 
5758     //   - comma expression (5.18) where the right operand is one of the above.
5759     if (BO->getOpcode() == BO_Comma)
5760       return IsSpecialDiscardedValue(BO->getRHS());
5761   }
5762 
5763   //   - conditional expression (5.16) where both the second and the third
5764   //     operands are one of the above, or
5765   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5766     return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5767            IsSpecialDiscardedValue(CO->getFalseExpr());
5768   // The related edge case of "*x ?: *x".
5769   if (BinaryConditionalOperator *BCO =
5770           dyn_cast<BinaryConditionalOperator>(E)) {
5771     if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5772       return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5773              IsSpecialDiscardedValue(BCO->getFalseExpr());
5774   }
5775 
5776   // Objective-C++ extensions to the rule.
5777   if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5778     return true;
5779 
5780   return false;
5781 }
5782 
5783 /// Perform the conversions required for an expression used in a
5784 /// context that ignores the result.
5785 ExprResult Sema::IgnoredValueConversions(Expr *E) {
5786   if (E->hasPlaceholderType()) {
5787     ExprResult result = CheckPlaceholderExpr(E);
5788     if (result.isInvalid()) return Owned(E);
5789     E = result.take();
5790   }
5791 
5792   // C99 6.3.2.1:
5793   //   [Except in specific positions,] an lvalue that does not have
5794   //   array type is converted to the value stored in the
5795   //   designated object (and is no longer an lvalue).
5796   if (E->isRValue()) {
5797     // In C, function designators (i.e. expressions of function type)
5798     // are r-values, but we still want to do function-to-pointer decay
5799     // on them.  This is both technically correct and convenient for
5800     // some clients.
5801     if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
5802       return DefaultFunctionArrayConversion(E);
5803 
5804     return Owned(E);
5805   }
5806 
5807   if (getLangOpts().CPlusPlus)  {
5808     // The C++11 standard defines the notion of a discarded-value expression;
5809     // normally, we don't need to do anything to handle it, but if it is a
5810     // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5811     // conversion.
5812     if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
5813         E->getType().isVolatileQualified() &&
5814         IsSpecialDiscardedValue(E)) {
5815       ExprResult Res = DefaultLvalueConversion(E);
5816       if (Res.isInvalid())
5817         return Owned(E);
5818       E = Res.take();
5819     }
5820     return Owned(E);
5821   }
5822 
5823   // GCC seems to also exclude expressions of incomplete enum type.
5824   if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5825     if (!T->getDecl()->isComplete()) {
5826       // FIXME: stupid workaround for a codegen bug!
5827       E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5828       return Owned(E);
5829     }
5830   }
5831 
5832   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5833   if (Res.isInvalid())
5834     return Owned(E);
5835   E = Res.take();
5836 
5837   if (!E->getType()->isVoidType())
5838     RequireCompleteType(E->getExprLoc(), E->getType(),
5839                         diag::err_incomplete_type);
5840   return Owned(E);
5841 }
5842 
5843 // If we can unambiguously determine whether Var can never be used
5844 // in a constant expression, return true.
5845 //  - if the variable and its initializer are non-dependent, then
5846 //    we can unambiguously check if the variable is a constant expression.
5847 //  - if the initializer is not value dependent - we can determine whether
5848 //    it can be used to initialize a constant expression.  If Init can not
5849 //    be used to initialize a constant expression we conclude that Var can
5850 //    never be a constant expression.
5851 //  - FXIME: if the initializer is dependent, we can still do some analysis and
5852 //    identify certain cases unambiguously as non-const by using a Visitor:
5853 //      - such as those that involve odr-use of a ParmVarDecl, involve a new
5854 //        delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
5855 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
5856     ASTContext &Context) {
5857   if (isa<ParmVarDecl>(Var)) return true;
5858   const VarDecl *DefVD = 0;
5859 
5860   // If there is no initializer - this can not be a constant expression.
5861   if (!Var->getAnyInitializer(DefVD)) return true;
5862   assert(DefVD);
5863   if (DefVD->isWeak()) return false;
5864   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
5865 
5866   Expr *Init = cast<Expr>(Eval->Value);
5867 
5868   if (Var->getType()->isDependentType() || Init->isValueDependent()) {
5869     if (!Init->isValueDependent())
5870       return !DefVD->checkInitIsICE();
5871     // FIXME: We might still be able to do some analysis of Init here
5872     // to conclude that even in a dependent setting, Init can never
5873     // be a constexpr - but for now admit agnosticity.
5874     return false;
5875   }
5876   return !IsVariableAConstantExpression(Var, Context);
5877 }
5878 
5879 /// \brief Check if the current lambda scope has any potential captures, and
5880 ///  whether they can be captured by any of the enclosing lambdas that are
5881 ///  ready to capture. If there is a lambda that can capture a nested
5882 ///  potential-capture, go ahead and do so.  Also, check to see if any
5883 ///  variables are uncaptureable or do not involve an odr-use so do not
5884 ///  need to be captured.
5885 
5886 static void CheckLambdaCaptures(Expr *const FE,
5887     LambdaScopeInfo *const CurrentLSI, Sema &S) {
5888 
5889   assert(!S.isUnevaluatedContext());
5890   assert(S.CurContext->isDependentContext());
5891   const bool IsFullExprInstantiationDependent =
5892       FE->isInstantiationDependent();
5893   // All the potentially captureable variables in the current nested
5894   // lambda (within a generic outer lambda), must be captured by an
5895   // outer lambda that is enclosed within a non-dependent context.
5896 
5897   for (size_t I = 0, N = CurrentLSI->getNumPotentialVariableCaptures();
5898       I != N; ++I) {
5899     Expr *VarExpr = 0;
5900     VarDecl *Var = 0;
5901     CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
5902     //
5903     if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
5904         !IsFullExprInstantiationDependent)
5905       continue;
5906     // Climb up until we find a lambda that can capture:
5907     //   - a generic-or-non-generic lambda call operator that is enclosed
5908     //     within a non-dependent context.
5909     unsigned FunctionScopeIndexOfCapturableLambda = 0;
5910     if (GetInnermostEnclosingCapturableLambda(
5911             S.FunctionScopes, FunctionScopeIndexOfCapturableLambda,
5912             S.CurContext, Var, S)) {
5913       MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(),
5914           S, &FunctionScopeIndexOfCapturableLambda);
5915     }
5916     const bool IsVarNeverAConstantExpression =
5917         VariableCanNeverBeAConstantExpression(Var, S.Context);
5918     if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
5919       // This full expression is not instantiation dependent or the variable
5920       // can not be used in a constant expression - which means
5921       // this variable must be odr-used here, so diagnose a
5922       // capture violation early, if the variable is un-captureable.
5923       // This is purely for diagnosing errors early.  Otherwise, this
5924       // error would get diagnosed when the lambda becomes capture ready.
5925       QualType CaptureType, DeclRefType;
5926       SourceLocation ExprLoc = VarExpr->getExprLoc();
5927       if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5928                           /*EllipsisLoc*/ SourceLocation(),
5929                           /*BuildAndDiagnose*/false, CaptureType,
5930                           DeclRefType, 0)) {
5931         // We will never be able to capture this variable, and we need
5932         // to be able to in any and all instantiations, so diagnose it.
5933         S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5934                           /*EllipsisLoc*/ SourceLocation(),
5935                           /*BuildAndDiagnose*/true, CaptureType,
5936                           DeclRefType, 0);
5937       }
5938     }
5939   }
5940 
5941   if (CurrentLSI->hasPotentialThisCapture()) {
5942     unsigned FunctionScopeIndexOfCapturableLambda = 0;
5943     if (GetInnermostEnclosingCapturableLambda(
5944             S.FunctionScopes, FunctionScopeIndexOfCapturableLambda,
5945             S.CurContext, /*0 is 'this'*/ 0, S)) {
5946       S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
5947           /*Explicit*/false, /*BuildAndDiagnose*/true,
5948           &FunctionScopeIndexOfCapturableLambda);
5949     }
5950   }
5951   CurrentLSI->clearPotentialCaptures();
5952 }
5953 
5954 
5955 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
5956                                      bool DiscardedValue,
5957                                      bool IsConstexpr,
5958                                      bool IsLambdaInitCaptureInitializer) {
5959   ExprResult FullExpr = Owned(FE);
5960 
5961   if (!FullExpr.get())
5962     return ExprError();
5963 
5964   // If we are an init-expression in a lambdas init-capture, we should not
5965   // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
5966   // containing full-expression is done).
5967   // template<class ... Ts> void test(Ts ... t) {
5968   //   test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
5969   //     return a;
5970   //   }() ...);
5971   // }
5972   // FIXME: This is a hack. It would be better if we pushed the lambda scope
5973   // when we parse the lambda introducer, and teach capturing (but not
5974   // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
5975   // corresponding class yet (that is, have LambdaScopeInfo either represent a
5976   // lambda where we've entered the introducer but not the body, or represent a
5977   // lambda where we've entered the body, depending on where the
5978   // parser/instantiation has got to).
5979   if (!IsLambdaInitCaptureInitializer &&
5980       DiagnoseUnexpandedParameterPack(FullExpr.get()))
5981     return ExprError();
5982 
5983   // Top-level expressions default to 'id' when we're in a debugger.
5984   if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
5985       FullExpr.get()->getType() == Context.UnknownAnyTy) {
5986     FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5987     if (FullExpr.isInvalid())
5988       return ExprError();
5989   }
5990 
5991   if (DiscardedValue) {
5992     FullExpr = CheckPlaceholderExpr(FullExpr.take());
5993     if (FullExpr.isInvalid())
5994       return ExprError();
5995 
5996     FullExpr = IgnoredValueConversions(FullExpr.take());
5997     if (FullExpr.isInvalid())
5998       return ExprError();
5999   }
6000 
6001   CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
6002 
6003   // At the end of this full expression (which could be a deeply nested
6004   // lambda), if there is a potential capture within the nested lambda,
6005   // have the outer capture-able lambda try and capture it.
6006   // Consider the following code:
6007   // void f(int, int);
6008   // void f(const int&, double);
6009   // void foo() {
6010   //  const int x = 10, y = 20;
6011   //  auto L = [=](auto a) {
6012   //      auto M = [=](auto b) {
6013   //         f(x, b); <-- requires x to be captured by L and M
6014   //         f(y, a); <-- requires y to be captured by L, but not all Ms
6015   //      };
6016   //   };
6017   // }
6018 
6019   // FIXME: Also consider what happens for something like this that involves
6020   // the gnu-extension statement-expressions or even lambda-init-captures:
6021   //   void f() {
6022   //     const int n = 0;
6023   //     auto L =  [&](auto a) {
6024   //       +n + ({ 0; a; });
6025   //     };
6026   //   }
6027   //
6028   // Here, we see +n, and then the full-expression 0; ends, so we don't
6029   // capture n (and instead remove it from our list of potential captures),
6030   // and then the full-expression +n + ({ 0; }); ends, but it's too late
6031   // for us to see that we need to capture n after all.
6032 
6033   LambdaScopeInfo *const CurrentLSI = getCurLambda();
6034   // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
6035   // even if CurContext is not a lambda call operator. Refer to that Bug Report
6036   // for an example of the code that might cause this asynchrony.
6037   // By ensuring we are in the context of a lambda's call operator
6038   // we can fix the bug (we only need to check whether we need to capture
6039   // if we are within a lambda's body); but per the comments in that
6040   // PR, a proper fix would entail :
6041   //   "Alternative suggestion:
6042   //   - Add to Sema an integer holding the smallest (outermost) scope
6043   //     index that we are *lexically* within, and save/restore/set to
6044   //     FunctionScopes.size() in InstantiatingTemplate's
6045   //     constructor/destructor.
6046   //  - Teach the handful of places that iterate over FunctionScopes to
6047   //    stop at the outermost enclosing lexical scope."
6048   const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
6049   if (IsInLambdaDeclContext && CurrentLSI &&
6050       CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
6051     CheckLambdaCaptures(FE, CurrentLSI, *this);
6052   return MaybeCreateExprWithCleanups(FullExpr);
6053 }
6054 
6055 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
6056   if (!FullStmt) return StmtError();
6057 
6058   return MaybeCreateStmtWithCleanups(FullStmt);
6059 }
6060 
6061 Sema::IfExistsResult
6062 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
6063                                    CXXScopeSpec &SS,
6064                                    const DeclarationNameInfo &TargetNameInfo) {
6065   DeclarationName TargetName = TargetNameInfo.getName();
6066   if (!TargetName)
6067     return IER_DoesNotExist;
6068 
6069   // If the name itself is dependent, then the result is dependent.
6070   if (TargetName.isDependentName())
6071     return IER_Dependent;
6072 
6073   // Do the redeclaration lookup in the current scope.
6074   LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
6075                  Sema::NotForRedeclaration);
6076   LookupParsedName(R, S, &SS);
6077   R.suppressDiagnostics();
6078 
6079   switch (R.getResultKind()) {
6080   case LookupResult::Found:
6081   case LookupResult::FoundOverloaded:
6082   case LookupResult::FoundUnresolvedValue:
6083   case LookupResult::Ambiguous:
6084     return IER_Exists;
6085 
6086   case LookupResult::NotFound:
6087     return IER_DoesNotExist;
6088 
6089   case LookupResult::NotFoundInCurrentInstantiation:
6090     return IER_Dependent;
6091   }
6092 
6093   llvm_unreachable("Invalid LookupResult Kind!");
6094 }
6095 
6096 Sema::IfExistsResult
6097 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
6098                                    bool IsIfExists, CXXScopeSpec &SS,
6099                                    UnqualifiedId &Name) {
6100   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6101 
6102   // Check for unexpanded parameter packs.
6103   SmallVector<UnexpandedParameterPack, 4> Unexpanded;
6104   collectUnexpandedParameterPacks(SS, Unexpanded);
6105   collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
6106   if (!Unexpanded.empty()) {
6107     DiagnoseUnexpandedParameterPacks(KeywordLoc,
6108                                      IsIfExists? UPPC_IfExists
6109                                                : UPPC_IfNotExists,
6110                                      Unexpanded);
6111     return IER_Error;
6112   }
6113 
6114   return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
6115 }
6116