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