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