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