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         HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
1519         HasAlignValT = !HasSizeT;
1520       }
1521 
1522       // In CUDA, determine how much we'd like / dislike to call this.
1523       if (S.getLangOpts().CUDA)
1524         if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1525           CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1526     }
1527 
1528     explicit operator bool() const { return FD; }
1529 
1530     bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1531                       bool WantAlign) const {
1532       // C++ P0722:
1533       //   A destroying operator delete is preferred over a non-destroying
1534       //   operator delete.
1535       if (Destroying != Other.Destroying)
1536         return Destroying;
1537 
1538       // C++17 [expr.delete]p10:
1539       //   If the type has new-extended alignment, a function with a parameter
1540       //   of type std::align_val_t is preferred; otherwise a function without
1541       //   such a parameter is preferred
1542       if (HasAlignValT != Other.HasAlignValT)
1543         return HasAlignValT == WantAlign;
1544 
1545       if (HasSizeT != Other.HasSizeT)
1546         return HasSizeT == WantSize;
1547 
1548       // Use CUDA call preference as a tiebreaker.
1549       return CUDAPref > Other.CUDAPref;
1550     }
1551 
1552     DeclAccessPair Found;
1553     FunctionDecl *FD;
1554     bool Destroying, HasSizeT, HasAlignValT;
1555     Sema::CUDAFunctionPreference CUDAPref;
1556   };
1557 }
1558 
1559 /// Determine whether a type has new-extended alignment. This may be called when
1560 /// the type is incomplete (for a delete-expression with an incomplete pointee
1561 /// type), in which case it will conservatively return false if the alignment is
1562 /// not known.
1563 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1564   return S.getLangOpts().AlignedAllocation &&
1565          S.getASTContext().getTypeAlignIfKnown(AllocType) >
1566              S.getASTContext().getTargetInfo().getNewAlign();
1567 }
1568 
1569 /// Select the correct "usual" deallocation function to use from a selection of
1570 /// deallocation functions (either global or class-scope).
1571 static UsualDeallocFnInfo resolveDeallocationOverload(
1572     Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1573     llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1574   UsualDeallocFnInfo Best;
1575 
1576   for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1577     UsualDeallocFnInfo Info(S, I.getPair());
1578     if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1579         Info.CUDAPref == Sema::CFP_Never)
1580       continue;
1581 
1582     if (!Best) {
1583       Best = Info;
1584       if (BestFns)
1585         BestFns->push_back(Info);
1586       continue;
1587     }
1588 
1589     if (Best.isBetterThan(Info, WantSize, WantAlign))
1590       continue;
1591 
1592     //   If more than one preferred function is found, all non-preferred
1593     //   functions are eliminated from further consideration.
1594     if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1595       BestFns->clear();
1596 
1597     Best = Info;
1598     if (BestFns)
1599       BestFns->push_back(Info);
1600   }
1601 
1602   return Best;
1603 }
1604 
1605 /// Determine whether a given type is a class for which 'delete[]' would call
1606 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1607 /// we need to store the array size (even if the type is
1608 /// trivially-destructible).
1609 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1610                                          QualType allocType) {
1611   const RecordType *record =
1612     allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1613   if (!record) return false;
1614 
1615   // Try to find an operator delete[] in class scope.
1616 
1617   DeclarationName deleteName =
1618     S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1619   LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1620   S.LookupQualifiedName(ops, record->getDecl());
1621 
1622   // We're just doing this for information.
1623   ops.suppressDiagnostics();
1624 
1625   // Very likely: there's no operator delete[].
1626   if (ops.empty()) return false;
1627 
1628   // If it's ambiguous, it should be illegal to call operator delete[]
1629   // on this thing, so it doesn't matter if we allocate extra space or not.
1630   if (ops.isAmbiguous()) return false;
1631 
1632   // C++17 [expr.delete]p10:
1633   //   If the deallocation functions have class scope, the one without a
1634   //   parameter of type std::size_t is selected.
1635   auto Best = resolveDeallocationOverload(
1636       S, ops, /*WantSize*/false,
1637       /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1638   return Best && Best.HasSizeT;
1639 }
1640 
1641 /// Parsed a C++ 'new' expression (C++ 5.3.4).
1642 ///
1643 /// E.g.:
1644 /// @code new (memory) int[size][4] @endcode
1645 /// or
1646 /// @code ::new Foo(23, "hello") @endcode
1647 ///
1648 /// \param StartLoc The first location of the expression.
1649 /// \param UseGlobal True if 'new' was prefixed with '::'.
1650 /// \param PlacementLParen Opening paren of the placement arguments.
1651 /// \param PlacementArgs Placement new arguments.
1652 /// \param PlacementRParen Closing paren of the placement arguments.
1653 /// \param TypeIdParens If the type is in parens, the source range.
1654 /// \param D The type to be allocated, as well as array dimensions.
1655 /// \param Initializer The initializing expression or initializer-list, or null
1656 ///   if there is none.
1657 ExprResult
1658 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1659                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1660                   SourceLocation PlacementRParen, SourceRange TypeIdParens,
1661                   Declarator &D, Expr *Initializer) {
1662   Expr *ArraySize = nullptr;
1663   // If the specified type is an array, unwrap it and save the expression.
1664   if (D.getNumTypeObjects() > 0 &&
1665       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1666     DeclaratorChunk &Chunk = D.getTypeObject(0);
1667     if (D.getDeclSpec().hasAutoTypeSpec())
1668       return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1669         << D.getSourceRange());
1670     if (Chunk.Arr.hasStatic)
1671       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1672         << D.getSourceRange());
1673     if (!Chunk.Arr.NumElts)
1674       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1675         << D.getSourceRange());
1676 
1677     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1678     D.DropFirstTypeObject();
1679   }
1680 
1681   // Every dimension shall be of constant size.
1682   if (ArraySize) {
1683     for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1684       if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1685         break;
1686 
1687       DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1688       if (Expr *NumElts = (Expr *)Array.NumElts) {
1689         if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1690           if (getLangOpts().CPlusPlus14) {
1691             // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1692             //   shall be a converted constant expression (5.19) of type std::size_t
1693             //   and shall evaluate to a strictly positive value.
1694             unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1695             assert(IntWidth && "Builtin type of size 0?");
1696             llvm::APSInt Value(IntWidth);
1697             Array.NumElts
1698              = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1699                                                 CCEK_NewExpr)
1700                  .get();
1701           } else {
1702             Array.NumElts
1703               = VerifyIntegerConstantExpression(NumElts, nullptr,
1704                                                 diag::err_new_array_nonconst)
1705                   .get();
1706           }
1707           if (!Array.NumElts)
1708             return ExprError();
1709         }
1710       }
1711     }
1712   }
1713 
1714   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1715   QualType AllocType = TInfo->getType();
1716   if (D.isInvalidType())
1717     return ExprError();
1718 
1719   SourceRange DirectInitRange;
1720   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1721     DirectInitRange = List->getSourceRange();
1722 
1723   return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1724                      PlacementLParen, PlacementArgs, PlacementRParen,
1725                      TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1726                      Initializer);
1727 }
1728 
1729 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1730                                        Expr *Init) {
1731   if (!Init)
1732     return true;
1733   if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1734     return PLE->getNumExprs() == 0;
1735   if (isa<ImplicitValueInitExpr>(Init))
1736     return true;
1737   else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1738     return !CCE->isListInitialization() &&
1739            CCE->getConstructor()->isDefaultConstructor();
1740   else if (Style == CXXNewExpr::ListInit) {
1741     assert(isa<InitListExpr>(Init) &&
1742            "Shouldn't create list CXXConstructExprs for arrays.");
1743     return true;
1744   }
1745   return false;
1746 }
1747 
1748 // Emit a diagnostic if an aligned allocation/deallocation function that is not
1749 // implemented in the standard library is selected.
1750 static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1751                                                  SourceLocation Loc, bool IsDelete,
1752                                                  Sema &S) {
1753   if (!S.getLangOpts().AlignedAllocationUnavailable)
1754     return;
1755 
1756   // Return if there is a definition.
1757   if (FD.isDefined())
1758     return;
1759 
1760   bool IsAligned = false;
1761   if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
1762     const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1763     StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1764         S.getASTContext().getTargetInfo().getPlatformName());
1765 
1766     S.Diag(Loc, diag::err_aligned_allocation_unavailable)
1767         << IsDelete << FD.getType().getAsString() << OSName
1768         << alignedAllocMinVersion(T.getOS()).getAsString();
1769     S.Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1770   }
1771 }
1772 
1773 ExprResult
1774 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1775                   SourceLocation PlacementLParen,
1776                   MultiExprArg PlacementArgs,
1777                   SourceLocation PlacementRParen,
1778                   SourceRange TypeIdParens,
1779                   QualType AllocType,
1780                   TypeSourceInfo *AllocTypeInfo,
1781                   Expr *ArraySize,
1782                   SourceRange DirectInitRange,
1783                   Expr *Initializer) {
1784   SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1785   SourceLocation StartLoc = Range.getBegin();
1786 
1787   CXXNewExpr::InitializationStyle initStyle;
1788   if (DirectInitRange.isValid()) {
1789     assert(Initializer && "Have parens but no initializer.");
1790     initStyle = CXXNewExpr::CallInit;
1791   } else if (Initializer && isa<InitListExpr>(Initializer))
1792     initStyle = CXXNewExpr::ListInit;
1793   else {
1794     assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1795             isa<CXXConstructExpr>(Initializer)) &&
1796            "Initializer expression that cannot have been implicitly created.");
1797     initStyle = CXXNewExpr::NoInit;
1798   }
1799 
1800   Expr **Inits = &Initializer;
1801   unsigned NumInits = Initializer ? 1 : 0;
1802   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1803     assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1804     Inits = List->getExprs();
1805     NumInits = List->getNumExprs();
1806   }
1807 
1808   // C++11 [expr.new]p15:
1809   //   A new-expression that creates an object of type T initializes that
1810   //   object as follows:
1811   InitializationKind Kind
1812       //     - If the new-initializer is omitted, the object is default-
1813       //       initialized (8.5); if no initialization is performed,
1814       //       the object has indeterminate value
1815       = initStyle == CXXNewExpr::NoInit
1816             ? InitializationKind::CreateDefault(TypeRange.getBegin())
1817             //     - Otherwise, the new-initializer is interpreted according to
1818             //     the
1819             //       initialization rules of 8.5 for direct-initialization.
1820             : initStyle == CXXNewExpr::ListInit
1821                   ? InitializationKind::CreateDirectList(
1822                         TypeRange.getBegin(), Initializer->getBeginLoc(),
1823                         Initializer->getEndLoc())
1824                   : InitializationKind::CreateDirect(TypeRange.getBegin(),
1825                                                      DirectInitRange.getBegin(),
1826                                                      DirectInitRange.getEnd());
1827 
1828   // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1829   auto *Deduced = AllocType->getContainedDeducedType();
1830   if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1831     if (ArraySize)
1832       return ExprError(Diag(ArraySize->getExprLoc(),
1833                             diag::err_deduced_class_template_compound_type)
1834                        << /*array*/ 2 << ArraySize->getSourceRange());
1835 
1836     InitializedEntity Entity
1837       = InitializedEntity::InitializeNew(StartLoc, AllocType);
1838     AllocType = DeduceTemplateSpecializationFromInitializer(
1839         AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1840     if (AllocType.isNull())
1841       return ExprError();
1842   } else if (Deduced) {
1843     bool Braced = (initStyle == CXXNewExpr::ListInit);
1844     if (NumInits == 1) {
1845       if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1846         Inits = p->getInits();
1847         NumInits = p->getNumInits();
1848         Braced = true;
1849       }
1850     }
1851 
1852     if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1853       return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1854                        << AllocType << TypeRange);
1855     if (NumInits > 1) {
1856       Expr *FirstBad = Inits[1];
1857       return ExprError(Diag(FirstBad->getBeginLoc(),
1858                             diag::err_auto_new_ctor_multiple_expressions)
1859                        << AllocType << TypeRange);
1860     }
1861     if (Braced && !getLangOpts().CPlusPlus17)
1862       Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1863           << AllocType << TypeRange;
1864     Expr *Deduce = Inits[0];
1865     QualType DeducedType;
1866     if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1867       return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1868                        << AllocType << Deduce->getType()
1869                        << TypeRange << Deduce->getSourceRange());
1870     if (DeducedType.isNull())
1871       return ExprError();
1872     AllocType = DeducedType;
1873   }
1874 
1875   // Per C++0x [expr.new]p5, the type being constructed may be a
1876   // typedef of an array type.
1877   if (!ArraySize) {
1878     if (const ConstantArrayType *Array
1879                               = Context.getAsConstantArrayType(AllocType)) {
1880       ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1881                                          Context.getSizeType(),
1882                                          TypeRange.getEnd());
1883       AllocType = Array->getElementType();
1884     }
1885   }
1886 
1887   if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1888     return ExprError();
1889 
1890   // In ARC, infer 'retaining' for the allocated
1891   if (getLangOpts().ObjCAutoRefCount &&
1892       AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1893       AllocType->isObjCLifetimeType()) {
1894     AllocType = Context.getLifetimeQualifiedType(AllocType,
1895                                     AllocType->getObjCARCImplicitLifetime());
1896   }
1897 
1898   QualType ResultType = Context.getPointerType(AllocType);
1899 
1900   if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1901     ExprResult result = CheckPlaceholderExpr(ArraySize);
1902     if (result.isInvalid()) return ExprError();
1903     ArraySize = result.get();
1904   }
1905   // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1906   //   integral or enumeration type with a non-negative value."
1907   // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1908   //   enumeration type, or a class type for which a single non-explicit
1909   //   conversion function to integral or unscoped enumeration type exists.
1910   // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1911   //   std::size_t.
1912   llvm::Optional<uint64_t> KnownArraySize;
1913   if (ArraySize && !ArraySize->isTypeDependent()) {
1914     ExprResult ConvertedSize;
1915     if (getLangOpts().CPlusPlus14) {
1916       assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1917 
1918       ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1919                                                 AA_Converting);
1920 
1921       if (!ConvertedSize.isInvalid() &&
1922           ArraySize->getType()->getAs<RecordType>())
1923         // Diagnose the compatibility of this conversion.
1924         Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1925           << ArraySize->getType() << 0 << "'size_t'";
1926     } else {
1927       class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1928       protected:
1929         Expr *ArraySize;
1930 
1931       public:
1932         SizeConvertDiagnoser(Expr *ArraySize)
1933             : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1934               ArraySize(ArraySize) {}
1935 
1936         SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1937                                              QualType T) override {
1938           return S.Diag(Loc, diag::err_array_size_not_integral)
1939                    << S.getLangOpts().CPlusPlus11 << T;
1940         }
1941 
1942         SemaDiagnosticBuilder diagnoseIncomplete(
1943             Sema &S, SourceLocation Loc, QualType T) override {
1944           return S.Diag(Loc, diag::err_array_size_incomplete_type)
1945                    << T << ArraySize->getSourceRange();
1946         }
1947 
1948         SemaDiagnosticBuilder diagnoseExplicitConv(
1949             Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1950           return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1951         }
1952 
1953         SemaDiagnosticBuilder noteExplicitConv(
1954             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1955           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1956                    << ConvTy->isEnumeralType() << ConvTy;
1957         }
1958 
1959         SemaDiagnosticBuilder diagnoseAmbiguous(
1960             Sema &S, SourceLocation Loc, QualType T) override {
1961           return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1962         }
1963 
1964         SemaDiagnosticBuilder noteAmbiguous(
1965             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1966           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1967                    << ConvTy->isEnumeralType() << ConvTy;
1968         }
1969 
1970         SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1971                                                  QualType T,
1972                                                  QualType ConvTy) override {
1973           return S.Diag(Loc,
1974                         S.getLangOpts().CPlusPlus11
1975                           ? diag::warn_cxx98_compat_array_size_conversion
1976                           : diag::ext_array_size_conversion)
1977                    << T << ConvTy->isEnumeralType() << ConvTy;
1978         }
1979       } SizeDiagnoser(ArraySize);
1980 
1981       ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1982                                                           SizeDiagnoser);
1983     }
1984     if (ConvertedSize.isInvalid())
1985       return ExprError();
1986 
1987     ArraySize = ConvertedSize.get();
1988     QualType SizeType = ArraySize->getType();
1989 
1990     if (!SizeType->isIntegralOrUnscopedEnumerationType())
1991       return ExprError();
1992 
1993     // C++98 [expr.new]p7:
1994     //   The expression in a direct-new-declarator shall have integral type
1995     //   with a non-negative value.
1996     //
1997     // Let's see if this is a constant < 0. If so, we reject it out of hand,
1998     // per CWG1464. Otherwise, if it's not a constant, we must have an
1999     // unparenthesized array type.
2000     if (!ArraySize->isValueDependent()) {
2001       llvm::APSInt Value;
2002       // We've already performed any required implicit conversion to integer or
2003       // unscoped enumeration type.
2004       // FIXME: Per CWG1464, we are required to check the value prior to
2005       // converting to size_t. This will never find a negative array size in
2006       // C++14 onwards, because Value is always unsigned here!
2007       if (ArraySize->isIntegerConstantExpr(Value, Context)) {
2008         if (Value.isSigned() && Value.isNegative()) {
2009           return ExprError(Diag(ArraySize->getBeginLoc(),
2010                                 diag::err_typecheck_negative_array_size)
2011                            << ArraySize->getSourceRange());
2012         }
2013 
2014         if (!AllocType->isDependentType()) {
2015           unsigned ActiveSizeBits =
2016             ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
2017           if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2018             return ExprError(
2019                 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2020                 << Value.toString(10) << ArraySize->getSourceRange());
2021         }
2022 
2023         KnownArraySize = Value.getZExtValue();
2024       } else if (TypeIdParens.isValid()) {
2025         // Can't have dynamic array size when the type-id is in parentheses.
2026         Diag(ArraySize->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2027             << ArraySize->getSourceRange()
2028             << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2029             << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2030 
2031         TypeIdParens = SourceRange();
2032       }
2033     }
2034 
2035     // Note that we do *not* convert the argument in any way.  It can
2036     // be signed, larger than size_t, whatever.
2037   }
2038 
2039   FunctionDecl *OperatorNew = nullptr;
2040   FunctionDecl *OperatorDelete = nullptr;
2041   unsigned Alignment =
2042       AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2043   unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2044   bool PassAlignment = getLangOpts().AlignedAllocation &&
2045                        Alignment > NewAlignment;
2046 
2047   AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
2048   if (!AllocType->isDependentType() &&
2049       !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2050       FindAllocationFunctions(StartLoc,
2051                               SourceRange(PlacementLParen, PlacementRParen),
2052                               Scope, Scope, AllocType, ArraySize, PassAlignment,
2053                               PlacementArgs, OperatorNew, OperatorDelete))
2054     return ExprError();
2055 
2056   // If this is an array allocation, compute whether the usual array
2057   // deallocation function for the type has a size_t parameter.
2058   bool UsualArrayDeleteWantsSize = false;
2059   if (ArraySize && !AllocType->isDependentType())
2060     UsualArrayDeleteWantsSize =
2061         doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2062 
2063   SmallVector<Expr *, 8> AllPlaceArgs;
2064   if (OperatorNew) {
2065     const FunctionProtoType *Proto =
2066         OperatorNew->getType()->getAs<FunctionProtoType>();
2067     VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2068                                                     : VariadicDoesNotApply;
2069 
2070     // We've already converted the placement args, just fill in any default
2071     // arguments. Skip the first parameter because we don't have a corresponding
2072     // argument. Skip the second parameter too if we're passing in the
2073     // alignment; we've already filled it in.
2074     if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2075                                PassAlignment ? 2 : 1, PlacementArgs,
2076                                AllPlaceArgs, CallType))
2077       return ExprError();
2078 
2079     if (!AllPlaceArgs.empty())
2080       PlacementArgs = AllPlaceArgs;
2081 
2082     // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2083     DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2084 
2085     // FIXME: Missing call to CheckFunctionCall or equivalent
2086 
2087     // Warn if the type is over-aligned and is being allocated by (unaligned)
2088     // global operator new.
2089     if (PlacementArgs.empty() && !PassAlignment &&
2090         (OperatorNew->isImplicit() ||
2091          (OperatorNew->getBeginLoc().isValid() &&
2092           getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2093       if (Alignment > NewAlignment)
2094         Diag(StartLoc, diag::warn_overaligned_type)
2095             << AllocType
2096             << unsigned(Alignment / Context.getCharWidth())
2097             << unsigned(NewAlignment / Context.getCharWidth());
2098     }
2099   }
2100 
2101   // Array 'new' can't have any initializers except empty parentheses.
2102   // Initializer lists are also allowed, in C++11. Rely on the parser for the
2103   // dialect distinction.
2104   if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2105     SourceRange InitRange(Inits[0]->getBeginLoc(),
2106                           Inits[NumInits - 1]->getEndLoc());
2107     Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2108     return ExprError();
2109   }
2110 
2111   // If we can perform the initialization, and we've not already done so,
2112   // do it now.
2113   if (!AllocType->isDependentType() &&
2114       !Expr::hasAnyTypeDependentArguments(
2115           llvm::makeArrayRef(Inits, NumInits))) {
2116     // The type we initialize is the complete type, including the array bound.
2117     QualType InitType;
2118     if (KnownArraySize)
2119       InitType = Context.getConstantArrayType(
2120           AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2121                                  *KnownArraySize),
2122           ArrayType::Normal, 0);
2123     else if (ArraySize)
2124       InitType =
2125           Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2126     else
2127       InitType = AllocType;
2128 
2129     InitializedEntity Entity
2130       = InitializedEntity::InitializeNew(StartLoc, InitType);
2131     InitializationSequence InitSeq(*this, Entity, Kind,
2132                                    MultiExprArg(Inits, NumInits));
2133     ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2134                                           MultiExprArg(Inits, NumInits));
2135     if (FullInit.isInvalid())
2136       return ExprError();
2137 
2138     // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2139     // we don't want the initialized object to be destructed.
2140     // FIXME: We should not create these in the first place.
2141     if (CXXBindTemporaryExpr *Binder =
2142             dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2143       FullInit = Binder->getSubExpr();
2144 
2145     Initializer = FullInit.get();
2146   }
2147 
2148   // Mark the new and delete operators as referenced.
2149   if (OperatorNew) {
2150     if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2151       return ExprError();
2152     MarkFunctionReferenced(StartLoc, OperatorNew);
2153     diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
2154   }
2155   if (OperatorDelete) {
2156     if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2157       return ExprError();
2158     MarkFunctionReferenced(StartLoc, OperatorDelete);
2159     diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
2160   }
2161 
2162   // C++0x [expr.new]p17:
2163   //   If the new expression creates an array of objects of class type,
2164   //   access and ambiguity control are done for the destructor.
2165   QualType BaseAllocType = Context.getBaseElementType(AllocType);
2166   if (ArraySize && !BaseAllocType->isDependentType()) {
2167     if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2168       if (CXXDestructorDecl *dtor = LookupDestructor(
2169               cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2170         MarkFunctionReferenced(StartLoc, dtor);
2171         CheckDestructorAccess(StartLoc, dtor,
2172                               PDiag(diag::err_access_dtor)
2173                                 << BaseAllocType);
2174         if (DiagnoseUseOfDecl(dtor, StartLoc))
2175           return ExprError();
2176       }
2177     }
2178   }
2179 
2180   return new (Context)
2181       CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
2182                  UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2183                  ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2184                  Range, DirectInitRange);
2185 }
2186 
2187 /// Checks that a type is suitable as the allocated type
2188 /// in a new-expression.
2189 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2190                               SourceRange R) {
2191   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2192   //   abstract class type or array thereof.
2193   if (AllocType->isFunctionType())
2194     return Diag(Loc, diag::err_bad_new_type)
2195       << AllocType << 0 << R;
2196   else if (AllocType->isReferenceType())
2197     return Diag(Loc, diag::err_bad_new_type)
2198       << AllocType << 1 << R;
2199   else if (!AllocType->isDependentType() &&
2200            RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2201     return true;
2202   else if (RequireNonAbstractType(Loc, AllocType,
2203                                   diag::err_allocation_of_abstract_type))
2204     return true;
2205   else if (AllocType->isVariablyModifiedType())
2206     return Diag(Loc, diag::err_variably_modified_new_type)
2207              << AllocType;
2208   else if (AllocType.getAddressSpace() != LangAS::Default &&
2209            !getLangOpts().OpenCLCPlusPlus)
2210     return Diag(Loc, diag::err_address_space_qualified_new)
2211       << AllocType.getUnqualifiedType()
2212       << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2213   else if (getLangOpts().ObjCAutoRefCount) {
2214     if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2215       QualType BaseAllocType = Context.getBaseElementType(AT);
2216       if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2217           BaseAllocType->isObjCLifetimeType())
2218         return Diag(Loc, diag::err_arc_new_array_without_ownership)
2219           << BaseAllocType;
2220     }
2221   }
2222 
2223   return false;
2224 }
2225 
2226 static bool resolveAllocationOverload(
2227     Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2228     bool &PassAlignment, FunctionDecl *&Operator,
2229     OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2230   OverloadCandidateSet Candidates(R.getNameLoc(),
2231                                   OverloadCandidateSet::CSK_Normal);
2232   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2233        Alloc != AllocEnd; ++Alloc) {
2234     // Even member operator new/delete are implicitly treated as
2235     // static, so don't use AddMemberCandidate.
2236     NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2237 
2238     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2239       S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2240                                      /*ExplicitTemplateArgs=*/nullptr, Args,
2241                                      Candidates,
2242                                      /*SuppressUserConversions=*/false);
2243       continue;
2244     }
2245 
2246     FunctionDecl *Fn = cast<FunctionDecl>(D);
2247     S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2248                            /*SuppressUserConversions=*/false);
2249   }
2250 
2251   // Do the resolution.
2252   OverloadCandidateSet::iterator Best;
2253   switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2254   case OR_Success: {
2255     // Got one!
2256     FunctionDecl *FnDecl = Best->Function;
2257     if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2258                                 Best->FoundDecl) == Sema::AR_inaccessible)
2259       return true;
2260 
2261     Operator = FnDecl;
2262     return false;
2263   }
2264 
2265   case OR_No_Viable_Function:
2266     // C++17 [expr.new]p13:
2267     //   If no matching function is found and the allocated object type has
2268     //   new-extended alignment, the alignment argument is removed from the
2269     //   argument list, and overload resolution is performed again.
2270     if (PassAlignment) {
2271       PassAlignment = false;
2272       AlignArg = Args[1];
2273       Args.erase(Args.begin() + 1);
2274       return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2275                                        Operator, &Candidates, AlignArg,
2276                                        Diagnose);
2277     }
2278 
2279     // MSVC will fall back on trying to find a matching global operator new
2280     // if operator new[] cannot be found.  Also, MSVC will leak by not
2281     // generating a call to operator delete or operator delete[], but we
2282     // will not replicate that bug.
2283     // FIXME: Find out how this interacts with the std::align_val_t fallback
2284     // once MSVC implements it.
2285     if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2286         S.Context.getLangOpts().MSVCCompat) {
2287       R.clear();
2288       R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2289       S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2290       // FIXME: This will give bad diagnostics pointing at the wrong functions.
2291       return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2292                                        Operator, /*Candidates=*/nullptr,
2293                                        /*AlignArg=*/nullptr, Diagnose);
2294     }
2295 
2296     if (Diagnose) {
2297       S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2298           << R.getLookupName() << Range;
2299 
2300       // If we have aligned candidates, only note the align_val_t candidates
2301       // from AlignedCandidates and the non-align_val_t candidates from
2302       // Candidates.
2303       if (AlignedCandidates) {
2304         auto IsAligned = [](OverloadCandidate &C) {
2305           return C.Function->getNumParams() > 1 &&
2306                  C.Function->getParamDecl(1)->getType()->isAlignValT();
2307         };
2308         auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2309 
2310         // This was an overaligned allocation, so list the aligned candidates
2311         // first.
2312         Args.insert(Args.begin() + 1, AlignArg);
2313         AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2314                                           R.getNameLoc(), IsAligned);
2315         Args.erase(Args.begin() + 1);
2316         Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2317                                   IsUnaligned);
2318       } else {
2319         Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2320       }
2321     }
2322     return true;
2323 
2324   case OR_Ambiguous:
2325     if (Diagnose) {
2326       S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2327           << R.getLookupName() << Range;
2328       Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2329     }
2330     return true;
2331 
2332   case OR_Deleted: {
2333     if (Diagnose) {
2334       S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2335           << Best->Function->isDeleted() << R.getLookupName()
2336           << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2337       Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2338     }
2339     return true;
2340   }
2341   }
2342   llvm_unreachable("Unreachable, bad result from BestViableFunction");
2343 }
2344 
2345 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2346                                    AllocationFunctionScope NewScope,
2347                                    AllocationFunctionScope DeleteScope,
2348                                    QualType AllocType, bool IsArray,
2349                                    bool &PassAlignment, MultiExprArg PlaceArgs,
2350                                    FunctionDecl *&OperatorNew,
2351                                    FunctionDecl *&OperatorDelete,
2352                                    bool Diagnose) {
2353   // --- Choosing an allocation function ---
2354   // C++ 5.3.4p8 - 14 & 18
2355   // 1) If looking in AFS_Global scope for allocation functions, only look in
2356   //    the global scope. Else, if AFS_Class, only look in the scope of the
2357   //    allocated class. If AFS_Both, look in both.
2358   // 2) If an array size is given, look for operator new[], else look for
2359   //   operator new.
2360   // 3) The first argument is always size_t. Append the arguments from the
2361   //   placement form.
2362 
2363   SmallVector<Expr*, 8> AllocArgs;
2364   AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2365 
2366   // We don't care about the actual value of these arguments.
2367   // FIXME: Should the Sema create the expression and embed it in the syntax
2368   // tree? Or should the consumer just recalculate the value?
2369   // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2370   IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2371                       Context.getTargetInfo().getPointerWidth(0)),
2372                       Context.getSizeType(),
2373                       SourceLocation());
2374   AllocArgs.push_back(&Size);
2375 
2376   QualType AlignValT = Context.VoidTy;
2377   if (PassAlignment) {
2378     DeclareGlobalNewDelete();
2379     AlignValT = Context.getTypeDeclType(getStdAlignValT());
2380   }
2381   CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2382   if (PassAlignment)
2383     AllocArgs.push_back(&Align);
2384 
2385   AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2386 
2387   // C++ [expr.new]p8:
2388   //   If the allocated type is a non-array type, the allocation
2389   //   function's name is operator new and the deallocation function's
2390   //   name is operator delete. If the allocated type is an array
2391   //   type, the allocation function's name is operator new[] and the
2392   //   deallocation function's name is operator delete[].
2393   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2394       IsArray ? OO_Array_New : OO_New);
2395 
2396   QualType AllocElemType = Context.getBaseElementType(AllocType);
2397 
2398   // Find the allocation function.
2399   {
2400     LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2401 
2402     // C++1z [expr.new]p9:
2403     //   If the new-expression begins with a unary :: operator, the allocation
2404     //   function's name is looked up in the global scope. Otherwise, if the
2405     //   allocated type is a class type T or array thereof, the allocation
2406     //   function's name is looked up in the scope of T.
2407     if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2408       LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2409 
2410     // We can see ambiguity here if the allocation function is found in
2411     // multiple base classes.
2412     if (R.isAmbiguous())
2413       return true;
2414 
2415     //   If this lookup fails to find the name, or if the allocated type is not
2416     //   a class type, the allocation function's name is looked up in the
2417     //   global scope.
2418     if (R.empty()) {
2419       if (NewScope == AFS_Class)
2420         return true;
2421 
2422       LookupQualifiedName(R, Context.getTranslationUnitDecl());
2423     }
2424 
2425     if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2426       Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2427       return true;
2428     }
2429 
2430     assert(!R.empty() && "implicitly declared allocation functions not found");
2431     assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2432 
2433     // We do our own custom access checks below.
2434     R.suppressDiagnostics();
2435 
2436     if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2437                                   OperatorNew, /*Candidates=*/nullptr,
2438                                   /*AlignArg=*/nullptr, Diagnose))
2439       return true;
2440   }
2441 
2442   // We don't need an operator delete if we're running under -fno-exceptions.
2443   if (!getLangOpts().Exceptions) {
2444     OperatorDelete = nullptr;
2445     return false;
2446   }
2447 
2448   // Note, the name of OperatorNew might have been changed from array to
2449   // non-array by resolveAllocationOverload.
2450   DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2451       OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2452           ? OO_Array_Delete
2453           : OO_Delete);
2454 
2455   // C++ [expr.new]p19:
2456   //
2457   //   If the new-expression begins with a unary :: operator, the
2458   //   deallocation function's name is looked up in the global
2459   //   scope. Otherwise, if the allocated type is a class type T or an
2460   //   array thereof, the deallocation function's name is looked up in
2461   //   the scope of T. If this lookup fails to find the name, or if
2462   //   the allocated type is not a class type or array thereof, the
2463   //   deallocation function's name is looked up in the global scope.
2464   LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2465   if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2466     CXXRecordDecl *RD
2467       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2468     LookupQualifiedName(FoundDelete, RD);
2469   }
2470   if (FoundDelete.isAmbiguous())
2471     return true; // FIXME: clean up expressions?
2472 
2473   bool FoundGlobalDelete = FoundDelete.empty();
2474   if (FoundDelete.empty()) {
2475     if (DeleteScope == AFS_Class)
2476       return true;
2477 
2478     DeclareGlobalNewDelete();
2479     LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2480   }
2481 
2482   FoundDelete.suppressDiagnostics();
2483 
2484   SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2485 
2486   // Whether we're looking for a placement operator delete is dictated
2487   // by whether we selected a placement operator new, not by whether
2488   // we had explicit placement arguments.  This matters for things like
2489   //   struct A { void *operator new(size_t, int = 0); ... };
2490   //   A *a = new A()
2491   //
2492   // We don't have any definition for what a "placement allocation function"
2493   // is, but we assume it's any allocation function whose
2494   // parameter-declaration-clause is anything other than (size_t).
2495   //
2496   // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2497   // This affects whether an exception from the constructor of an overaligned
2498   // type uses the sized or non-sized form of aligned operator delete.
2499   bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2500                         OperatorNew->isVariadic();
2501 
2502   if (isPlacementNew) {
2503     // C++ [expr.new]p20:
2504     //   A declaration of a placement deallocation function matches the
2505     //   declaration of a placement allocation function if it has the
2506     //   same number of parameters and, after parameter transformations
2507     //   (8.3.5), all parameter types except the first are
2508     //   identical. [...]
2509     //
2510     // To perform this comparison, we compute the function type that
2511     // the deallocation function should have, and use that type both
2512     // for template argument deduction and for comparison purposes.
2513     QualType ExpectedFunctionType;
2514     {
2515       const FunctionProtoType *Proto
2516         = OperatorNew->getType()->getAs<FunctionProtoType>();
2517 
2518       SmallVector<QualType, 4> ArgTypes;
2519       ArgTypes.push_back(Context.VoidPtrTy);
2520       for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2521         ArgTypes.push_back(Proto->getParamType(I));
2522 
2523       FunctionProtoType::ExtProtoInfo EPI;
2524       // FIXME: This is not part of the standard's rule.
2525       EPI.Variadic = Proto->isVariadic();
2526 
2527       ExpectedFunctionType
2528         = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2529     }
2530 
2531     for (LookupResult::iterator D = FoundDelete.begin(),
2532                              DEnd = FoundDelete.end();
2533          D != DEnd; ++D) {
2534       FunctionDecl *Fn = nullptr;
2535       if (FunctionTemplateDecl *FnTmpl =
2536               dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2537         // Perform template argument deduction to try to match the
2538         // expected function type.
2539         TemplateDeductionInfo Info(StartLoc);
2540         if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2541                                     Info))
2542           continue;
2543       } else
2544         Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2545 
2546       if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2547                                                   ExpectedFunctionType,
2548                                                   /*AdjustExcpetionSpec*/true),
2549                               ExpectedFunctionType))
2550         Matches.push_back(std::make_pair(D.getPair(), Fn));
2551     }
2552 
2553     if (getLangOpts().CUDA)
2554       EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2555   } else {
2556     // C++1y [expr.new]p22:
2557     //   For a non-placement allocation function, the normal deallocation
2558     //   function lookup is used
2559     //
2560     // Per [expr.delete]p10, this lookup prefers a member operator delete
2561     // without a size_t argument, but prefers a non-member operator delete
2562     // with a size_t where possible (which it always is in this case).
2563     llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2564     UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2565         *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2566         /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2567         &BestDeallocFns);
2568     if (Selected)
2569       Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2570     else {
2571       // If we failed to select an operator, all remaining functions are viable
2572       // but ambiguous.
2573       for (auto Fn : BestDeallocFns)
2574         Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2575     }
2576   }
2577 
2578   // C++ [expr.new]p20:
2579   //   [...] If the lookup finds a single matching deallocation
2580   //   function, that function will be called; otherwise, no
2581   //   deallocation function will be called.
2582   if (Matches.size() == 1) {
2583     OperatorDelete = Matches[0].second;
2584 
2585     // C++1z [expr.new]p23:
2586     //   If the lookup finds a usual deallocation function (3.7.4.2)
2587     //   with a parameter of type std::size_t and that function, considered
2588     //   as a placement deallocation function, would have been
2589     //   selected as a match for the allocation function, the program
2590     //   is ill-formed.
2591     if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2592         isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2593       UsualDeallocFnInfo Info(*this,
2594                               DeclAccessPair::make(OperatorDelete, AS_public));
2595       // Core issue, per mail to core reflector, 2016-10-09:
2596       //   If this is a member operator delete, and there is a corresponding
2597       //   non-sized member operator delete, this isn't /really/ a sized
2598       //   deallocation function, it just happens to have a size_t parameter.
2599       bool IsSizedDelete = Info.HasSizeT;
2600       if (IsSizedDelete && !FoundGlobalDelete) {
2601         auto NonSizedDelete =
2602             resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2603                                         /*WantAlign*/Info.HasAlignValT);
2604         if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2605             NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2606           IsSizedDelete = false;
2607       }
2608 
2609       if (IsSizedDelete) {
2610         SourceRange R = PlaceArgs.empty()
2611                             ? SourceRange()
2612                             : SourceRange(PlaceArgs.front()->getBeginLoc(),
2613                                           PlaceArgs.back()->getEndLoc());
2614         Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2615         if (!OperatorDelete->isImplicit())
2616           Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2617               << DeleteName;
2618       }
2619     }
2620 
2621     CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2622                           Matches[0].first);
2623   } else if (!Matches.empty()) {
2624     // We found multiple suitable operators. Per [expr.new]p20, that means we
2625     // call no 'operator delete' function, but we should at least warn the user.
2626     // FIXME: Suppress this warning if the construction cannot throw.
2627     Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2628       << DeleteName << AllocElemType;
2629 
2630     for (auto &Match : Matches)
2631       Diag(Match.second->getLocation(),
2632            diag::note_member_declared_here) << DeleteName;
2633   }
2634 
2635   return false;
2636 }
2637 
2638 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2639 /// delete. These are:
2640 /// @code
2641 ///   // C++03:
2642 ///   void* operator new(std::size_t) throw(std::bad_alloc);
2643 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
2644 ///   void operator delete(void *) throw();
2645 ///   void operator delete[](void *) throw();
2646 ///   // C++11:
2647 ///   void* operator new(std::size_t);
2648 ///   void* operator new[](std::size_t);
2649 ///   void operator delete(void *) noexcept;
2650 ///   void operator delete[](void *) noexcept;
2651 ///   // C++1y:
2652 ///   void* operator new(std::size_t);
2653 ///   void* operator new[](std::size_t);
2654 ///   void operator delete(void *) noexcept;
2655 ///   void operator delete[](void *) noexcept;
2656 ///   void operator delete(void *, std::size_t) noexcept;
2657 ///   void operator delete[](void *, std::size_t) noexcept;
2658 /// @endcode
2659 /// Note that the placement and nothrow forms of new are *not* implicitly
2660 /// declared. Their use requires including \<new\>.
2661 void Sema::DeclareGlobalNewDelete() {
2662   if (GlobalNewDeleteDeclared)
2663     return;
2664 
2665   // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2666   // are not supported.
2667   if (getLangOpts().OpenCLCPlusPlus)
2668     return;
2669 
2670   // C++ [basic.std.dynamic]p2:
2671   //   [...] The following allocation and deallocation functions (18.4) are
2672   //   implicitly declared in global scope in each translation unit of a
2673   //   program
2674   //
2675   //     C++03:
2676   //     void* operator new(std::size_t) throw(std::bad_alloc);
2677   //     void* operator new[](std::size_t) throw(std::bad_alloc);
2678   //     void  operator delete(void*) throw();
2679   //     void  operator delete[](void*) throw();
2680   //     C++11:
2681   //     void* operator new(std::size_t);
2682   //     void* operator new[](std::size_t);
2683   //     void  operator delete(void*) noexcept;
2684   //     void  operator delete[](void*) noexcept;
2685   //     C++1y:
2686   //     void* operator new(std::size_t);
2687   //     void* operator new[](std::size_t);
2688   //     void  operator delete(void*) noexcept;
2689   //     void  operator delete[](void*) noexcept;
2690   //     void  operator delete(void*, std::size_t) noexcept;
2691   //     void  operator delete[](void*, std::size_t) noexcept;
2692   //
2693   //   These implicit declarations introduce only the function names operator
2694   //   new, operator new[], operator delete, operator delete[].
2695   //
2696   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2697   // "std" or "bad_alloc" as necessary to form the exception specification.
2698   // However, we do not make these implicit declarations visible to name
2699   // lookup.
2700   if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2701     // The "std::bad_alloc" class has not yet been declared, so build it
2702     // implicitly.
2703     StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2704                                         getOrCreateStdNamespace(),
2705                                         SourceLocation(), SourceLocation(),
2706                                       &PP.getIdentifierTable().get("bad_alloc"),
2707                                         nullptr);
2708     getStdBadAlloc()->setImplicit(true);
2709   }
2710   if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2711     // The "std::align_val_t" enum class has not yet been declared, so build it
2712     // implicitly.
2713     auto *AlignValT = EnumDecl::Create(
2714         Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2715         &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2716     AlignValT->setIntegerType(Context.getSizeType());
2717     AlignValT->setPromotionType(Context.getSizeType());
2718     AlignValT->setImplicit(true);
2719     StdAlignValT = AlignValT;
2720   }
2721 
2722   GlobalNewDeleteDeclared = true;
2723 
2724   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2725   QualType SizeT = Context.getSizeType();
2726 
2727   auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2728                                               QualType Return, QualType Param) {
2729     llvm::SmallVector<QualType, 3> Params;
2730     Params.push_back(Param);
2731 
2732     // Create up to four variants of the function (sized/aligned).
2733     bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2734                            (Kind == OO_Delete || Kind == OO_Array_Delete);
2735     bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2736 
2737     int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2738     int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2739     for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2740       if (Sized)
2741         Params.push_back(SizeT);
2742 
2743       for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2744         if (Aligned)
2745           Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2746 
2747         DeclareGlobalAllocationFunction(
2748             Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2749 
2750         if (Aligned)
2751           Params.pop_back();
2752       }
2753     }
2754   };
2755 
2756   DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2757   DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2758   DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2759   DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2760 }
2761 
2762 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2763 /// allocation function if it doesn't already exist.
2764 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2765                                            QualType Return,
2766                                            ArrayRef<QualType> Params) {
2767   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2768 
2769   // Check if this function is already declared.
2770   DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2771   for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2772        Alloc != AllocEnd; ++Alloc) {
2773     // Only look at non-template functions, as it is the predefined,
2774     // non-templated allocation function we are trying to declare here.
2775     if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2776       if (Func->getNumParams() == Params.size()) {
2777         llvm::SmallVector<QualType, 3> FuncParams;
2778         for (auto *P : Func->parameters())
2779           FuncParams.push_back(
2780               Context.getCanonicalType(P->getType().getUnqualifiedType()));
2781         if (llvm::makeArrayRef(FuncParams) == Params) {
2782           // Make the function visible to name lookup, even if we found it in
2783           // an unimported module. It either is an implicitly-declared global
2784           // allocation function, or is suppressing that function.
2785           Func->setVisibleDespiteOwningModule();
2786           return;
2787         }
2788       }
2789     }
2790   }
2791 
2792   FunctionProtoType::ExtProtoInfo EPI;
2793 
2794   QualType BadAllocType;
2795   bool HasBadAllocExceptionSpec
2796     = (Name.getCXXOverloadedOperator() == OO_New ||
2797        Name.getCXXOverloadedOperator() == OO_Array_New);
2798   if (HasBadAllocExceptionSpec) {
2799     if (!getLangOpts().CPlusPlus11) {
2800       BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2801       assert(StdBadAlloc && "Must have std::bad_alloc declared");
2802       EPI.ExceptionSpec.Type = EST_Dynamic;
2803       EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2804     }
2805   } else {
2806     EPI.ExceptionSpec =
2807         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2808   }
2809 
2810   auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2811     QualType FnType = Context.getFunctionType(Return, Params, EPI);
2812     FunctionDecl *Alloc = FunctionDecl::Create(
2813         Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2814         FnType, /*TInfo=*/nullptr, SC_None, false, true);
2815     Alloc->setImplicit();
2816     // Global allocation functions should always be visible.
2817     Alloc->setVisibleDespiteOwningModule();
2818 
2819     Alloc->addAttr(VisibilityAttr::CreateImplicit(
2820         Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2821                      ? VisibilityAttr::Hidden
2822                      : 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 =
4276         ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4277 
4278     CastKind CK = CK_NoOp;
4279 
4280     if (ToType->isReferenceType() &&
4281         ToType->getPointeeType().getAddressSpace() !=
4282             From->getType().getAddressSpace())
4283       CK = CK_AddressSpaceConversion;
4284 
4285     if (ToType->isPointerType() &&
4286         ToType->getPointeeType().getAddressSpace() !=
4287             From->getType()->getPointeeType().getAddressSpace())
4288       CK = CK_AddressSpaceConversion;
4289 
4290     From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4291                              /*BasePath=*/nullptr, CCK)
4292                .get();
4293 
4294     if (SCS.DeprecatedStringLiteralToCharPtr &&
4295         !getLangOpts().WritableStrings) {
4296       Diag(From->getBeginLoc(),
4297            getLangOpts().CPlusPlus11
4298                ? diag::ext_deprecated_string_literal_conversion
4299                : diag::warn_deprecated_string_literal_conversion)
4300           << ToType.getNonReferenceType();
4301     }
4302 
4303     break;
4304   }
4305 
4306   default:
4307     llvm_unreachable("Improper third standard conversion");
4308   }
4309 
4310   // If this conversion sequence involved a scalar -> atomic conversion, perform
4311   // that conversion now.
4312   if (!ToAtomicType.isNull()) {
4313     assert(Context.hasSameType(
4314         ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4315     From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4316                              VK_RValue, nullptr, CCK).get();
4317   }
4318 
4319   // If this conversion sequence succeeded and involved implicitly converting a
4320   // _Nullable type to a _Nonnull one, complain.
4321   if (!isCast(CCK))
4322     diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4323                                         From->getBeginLoc());
4324 
4325   return From;
4326 }
4327 
4328 /// Check the completeness of a type in a unary type trait.
4329 ///
4330 /// If the particular type trait requires a complete type, tries to complete
4331 /// it. If completing the type fails, a diagnostic is emitted and false
4332 /// returned. If completing the type succeeds or no completion was required,
4333 /// returns true.
4334 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4335                                                 SourceLocation Loc,
4336                                                 QualType ArgTy) {
4337   // C++0x [meta.unary.prop]p3:
4338   //   For all of the class templates X declared in this Clause, instantiating
4339   //   that template with a template argument that is a class template
4340   //   specialization may result in the implicit instantiation of the template
4341   //   argument if and only if the semantics of X require that the argument
4342   //   must be a complete type.
4343   // We apply this rule to all the type trait expressions used to implement
4344   // these class templates. We also try to follow any GCC documented behavior
4345   // in these expressions to ensure portability of standard libraries.
4346   switch (UTT) {
4347   default: llvm_unreachable("not a UTT");
4348     // is_complete_type somewhat obviously cannot require a complete type.
4349   case UTT_IsCompleteType:
4350     // Fall-through
4351 
4352     // These traits are modeled on the type predicates in C++0x
4353     // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4354     // requiring a complete type, as whether or not they return true cannot be
4355     // impacted by the completeness of the type.
4356   case UTT_IsVoid:
4357   case UTT_IsIntegral:
4358   case UTT_IsFloatingPoint:
4359   case UTT_IsArray:
4360   case UTT_IsPointer:
4361   case UTT_IsLvalueReference:
4362   case UTT_IsRvalueReference:
4363   case UTT_IsMemberFunctionPointer:
4364   case UTT_IsMemberObjectPointer:
4365   case UTT_IsEnum:
4366   case UTT_IsUnion:
4367   case UTT_IsClass:
4368   case UTT_IsFunction:
4369   case UTT_IsReference:
4370   case UTT_IsArithmetic:
4371   case UTT_IsFundamental:
4372   case UTT_IsObject:
4373   case UTT_IsScalar:
4374   case UTT_IsCompound:
4375   case UTT_IsMemberPointer:
4376     // Fall-through
4377 
4378     // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4379     // which requires some of its traits to have the complete type. However,
4380     // the completeness of the type cannot impact these traits' semantics, and
4381     // so they don't require it. This matches the comments on these traits in
4382     // Table 49.
4383   case UTT_IsConst:
4384   case UTT_IsVolatile:
4385   case UTT_IsSigned:
4386   case UTT_IsUnsigned:
4387 
4388   // This type trait always returns false, checking the type is moot.
4389   case UTT_IsInterfaceClass:
4390     return true;
4391 
4392   // C++14 [meta.unary.prop]:
4393   //   If T is a non-union class type, T shall be a complete type.
4394   case UTT_IsEmpty:
4395   case UTT_IsPolymorphic:
4396   case UTT_IsAbstract:
4397     if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4398       if (!RD->isUnion())
4399         return !S.RequireCompleteType(
4400             Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4401     return true;
4402 
4403   // C++14 [meta.unary.prop]:
4404   //   If T is a class type, T shall be a complete type.
4405   case UTT_IsFinal:
4406   case UTT_IsSealed:
4407     if (ArgTy->getAsCXXRecordDecl())
4408       return !S.RequireCompleteType(
4409           Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4410     return true;
4411 
4412   // C++1z [meta.unary.prop]:
4413   //   remove_all_extents_t<T> shall be a complete type or cv void.
4414   case UTT_IsAggregate:
4415   case UTT_IsTrivial:
4416   case UTT_IsTriviallyCopyable:
4417   case UTT_IsStandardLayout:
4418   case UTT_IsPOD:
4419   case UTT_IsLiteral:
4420   // Per the GCC type traits documentation, T shall be a complete type, cv void,
4421   // or an array of unknown bound. But GCC actually imposes the same constraints
4422   // as above.
4423   case UTT_HasNothrowAssign:
4424   case UTT_HasNothrowMoveAssign:
4425   case UTT_HasNothrowConstructor:
4426   case UTT_HasNothrowCopy:
4427   case UTT_HasTrivialAssign:
4428   case UTT_HasTrivialMoveAssign:
4429   case UTT_HasTrivialDefaultConstructor:
4430   case UTT_HasTrivialMoveConstructor:
4431   case UTT_HasTrivialCopy:
4432   case UTT_HasTrivialDestructor:
4433   case UTT_HasVirtualDestructor:
4434     ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4435     LLVM_FALLTHROUGH;
4436 
4437   // C++1z [meta.unary.prop]:
4438   //   T shall be a complete type, cv void, or an array of unknown bound.
4439   case UTT_IsDestructible:
4440   case UTT_IsNothrowDestructible:
4441   case UTT_IsTriviallyDestructible:
4442   case UTT_HasUniqueObjectRepresentations:
4443     if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4444       return true;
4445 
4446     return !S.RequireCompleteType(
4447         Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4448   }
4449 }
4450 
4451 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4452                                Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4453                                bool (CXXRecordDecl::*HasTrivial)() const,
4454                                bool (CXXRecordDecl::*HasNonTrivial)() const,
4455                                bool (CXXMethodDecl::*IsDesiredOp)() const)
4456 {
4457   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4458   if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4459     return true;
4460 
4461   DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4462   DeclarationNameInfo NameInfo(Name, KeyLoc);
4463   LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4464   if (Self.LookupQualifiedName(Res, RD)) {
4465     bool FoundOperator = false;
4466     Res.suppressDiagnostics();
4467     for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4468          Op != OpEnd; ++Op) {
4469       if (isa<FunctionTemplateDecl>(*Op))
4470         continue;
4471 
4472       CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4473       if((Operator->*IsDesiredOp)()) {
4474         FoundOperator = true;
4475         const FunctionProtoType *CPT =
4476           Operator->getType()->getAs<FunctionProtoType>();
4477         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4478         if (!CPT || !CPT->isNothrow())
4479           return false;
4480       }
4481     }
4482     return FoundOperator;
4483   }
4484   return false;
4485 }
4486 
4487 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4488                                    SourceLocation KeyLoc, QualType T) {
4489   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4490 
4491   ASTContext &C = Self.Context;
4492   switch(UTT) {
4493   default: llvm_unreachable("not a UTT");
4494     // Type trait expressions corresponding to the primary type category
4495     // predicates in C++0x [meta.unary.cat].
4496   case UTT_IsVoid:
4497     return T->isVoidType();
4498   case UTT_IsIntegral:
4499     return T->isIntegralType(C);
4500   case UTT_IsFloatingPoint:
4501     return T->isFloatingType();
4502   case UTT_IsArray:
4503     return T->isArrayType();
4504   case UTT_IsPointer:
4505     return T->isPointerType();
4506   case UTT_IsLvalueReference:
4507     return T->isLValueReferenceType();
4508   case UTT_IsRvalueReference:
4509     return T->isRValueReferenceType();
4510   case UTT_IsMemberFunctionPointer:
4511     return T->isMemberFunctionPointerType();
4512   case UTT_IsMemberObjectPointer:
4513     return T->isMemberDataPointerType();
4514   case UTT_IsEnum:
4515     return T->isEnumeralType();
4516   case UTT_IsUnion:
4517     return T->isUnionType();
4518   case UTT_IsClass:
4519     return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4520   case UTT_IsFunction:
4521     return T->isFunctionType();
4522 
4523     // Type trait expressions which correspond to the convenient composition
4524     // predicates in C++0x [meta.unary.comp].
4525   case UTT_IsReference:
4526     return T->isReferenceType();
4527   case UTT_IsArithmetic:
4528     return T->isArithmeticType() && !T->isEnumeralType();
4529   case UTT_IsFundamental:
4530     return T->isFundamentalType();
4531   case UTT_IsObject:
4532     return T->isObjectType();
4533   case UTT_IsScalar:
4534     // Note: semantic analysis depends on Objective-C lifetime types to be
4535     // considered scalar types. However, such types do not actually behave
4536     // like scalar types at run time (since they may require retain/release
4537     // operations), so we report them as non-scalar.
4538     if (T->isObjCLifetimeType()) {
4539       switch (T.getObjCLifetime()) {
4540       case Qualifiers::OCL_None:
4541       case Qualifiers::OCL_ExplicitNone:
4542         return true;
4543 
4544       case Qualifiers::OCL_Strong:
4545       case Qualifiers::OCL_Weak:
4546       case Qualifiers::OCL_Autoreleasing:
4547         return false;
4548       }
4549     }
4550 
4551     return T->isScalarType();
4552   case UTT_IsCompound:
4553     return T->isCompoundType();
4554   case UTT_IsMemberPointer:
4555     return T->isMemberPointerType();
4556 
4557     // Type trait expressions which correspond to the type property predicates
4558     // in C++0x [meta.unary.prop].
4559   case UTT_IsConst:
4560     return T.isConstQualified();
4561   case UTT_IsVolatile:
4562     return T.isVolatileQualified();
4563   case UTT_IsTrivial:
4564     return T.isTrivialType(C);
4565   case UTT_IsTriviallyCopyable:
4566     return T.isTriviallyCopyableType(C);
4567   case UTT_IsStandardLayout:
4568     return T->isStandardLayoutType();
4569   case UTT_IsPOD:
4570     return T.isPODType(C);
4571   case UTT_IsLiteral:
4572     return T->isLiteralType(C);
4573   case UTT_IsEmpty:
4574     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4575       return !RD->isUnion() && RD->isEmpty();
4576     return false;
4577   case UTT_IsPolymorphic:
4578     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4579       return !RD->isUnion() && RD->isPolymorphic();
4580     return false;
4581   case UTT_IsAbstract:
4582     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4583       return !RD->isUnion() && RD->isAbstract();
4584     return false;
4585   case UTT_IsAggregate:
4586     // Report vector extensions and complex types as aggregates because they
4587     // support aggregate initialization. GCC mirrors this behavior for vectors
4588     // but not _Complex.
4589     return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4590            T->isAnyComplexType();
4591   // __is_interface_class only returns true when CL is invoked in /CLR mode and
4592   // even then only when it is used with the 'interface struct ...' syntax
4593   // Clang doesn't support /CLR which makes this type trait moot.
4594   case UTT_IsInterfaceClass:
4595     return false;
4596   case UTT_IsFinal:
4597   case UTT_IsSealed:
4598     if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4599       return RD->hasAttr<FinalAttr>();
4600     return false;
4601   case UTT_IsSigned:
4602     return T->isSignedIntegerType();
4603   case UTT_IsUnsigned:
4604     return T->isUnsignedIntegerType();
4605 
4606     // Type trait expressions which query classes regarding their construction,
4607     // destruction, and copying. Rather than being based directly on the
4608     // related type predicates in the standard, they are specified by both
4609     // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4610     // specifications.
4611     //
4612     //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4613     //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4614     //
4615     // Note that these builtins do not behave as documented in g++: if a class
4616     // has both a trivial and a non-trivial special member of a particular kind,
4617     // they return false! For now, we emulate this behavior.
4618     // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4619     // does not correctly compute triviality in the presence of multiple special
4620     // members of the same kind. Revisit this once the g++ bug is fixed.
4621   case UTT_HasTrivialDefaultConstructor:
4622     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4623     //   If __is_pod (type) is true then the trait is true, else if type is
4624     //   a cv class or union type (or array thereof) with a trivial default
4625     //   constructor ([class.ctor]) then the trait is true, else it is false.
4626     if (T.isPODType(C))
4627       return true;
4628     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4629       return RD->hasTrivialDefaultConstructor() &&
4630              !RD->hasNonTrivialDefaultConstructor();
4631     return false;
4632   case UTT_HasTrivialMoveConstructor:
4633     //  This trait is implemented by MSVC 2012 and needed to parse the
4634     //  standard library headers. Specifically this is used as the logic
4635     //  behind std::is_trivially_move_constructible (20.9.4.3).
4636     if (T.isPODType(C))
4637       return true;
4638     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4639       return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4640     return false;
4641   case UTT_HasTrivialCopy:
4642     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4643     //   If __is_pod (type) is true or type is a reference type then
4644     //   the trait is true, else if type is a cv class or union type
4645     //   with a trivial copy constructor ([class.copy]) then the trait
4646     //   is true, else it is false.
4647     if (T.isPODType(C) || T->isReferenceType())
4648       return true;
4649     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4650       return RD->hasTrivialCopyConstructor() &&
4651              !RD->hasNonTrivialCopyConstructor();
4652     return false;
4653   case UTT_HasTrivialMoveAssign:
4654     //  This trait is implemented by MSVC 2012 and needed to parse the
4655     //  standard library headers. Specifically it is used as the logic
4656     //  behind std::is_trivially_move_assignable (20.9.4.3)
4657     if (T.isPODType(C))
4658       return true;
4659     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4660       return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4661     return false;
4662   case UTT_HasTrivialAssign:
4663     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4664     //   If type is const qualified or is a reference type then the
4665     //   trait is false. Otherwise if __is_pod (type) is true then the
4666     //   trait is true, else if type is a cv class or union type with
4667     //   a trivial copy assignment ([class.copy]) then the trait is
4668     //   true, else it is false.
4669     // Note: the const and reference restrictions are interesting,
4670     // given that const and reference members don't prevent a class
4671     // from having a trivial copy assignment operator (but do cause
4672     // errors if the copy assignment operator is actually used, q.v.
4673     // [class.copy]p12).
4674 
4675     if (T.isConstQualified())
4676       return false;
4677     if (T.isPODType(C))
4678       return true;
4679     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4680       return RD->hasTrivialCopyAssignment() &&
4681              !RD->hasNonTrivialCopyAssignment();
4682     return false;
4683   case UTT_IsDestructible:
4684   case UTT_IsTriviallyDestructible:
4685   case UTT_IsNothrowDestructible:
4686     // C++14 [meta.unary.prop]:
4687     //   For reference types, is_destructible<T>::value is true.
4688     if (T->isReferenceType())
4689       return true;
4690 
4691     // Objective-C++ ARC: autorelease types don't require destruction.
4692     if (T->isObjCLifetimeType() &&
4693         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4694       return true;
4695 
4696     // C++14 [meta.unary.prop]:
4697     //   For incomplete types and function types, is_destructible<T>::value is
4698     //   false.
4699     if (T->isIncompleteType() || T->isFunctionType())
4700       return false;
4701 
4702     // A type that requires destruction (via a non-trivial destructor or ARC
4703     // lifetime semantics) is not trivially-destructible.
4704     if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4705       return false;
4706 
4707     // C++14 [meta.unary.prop]:
4708     //   For object types and given U equal to remove_all_extents_t<T>, if the
4709     //   expression std::declval<U&>().~U() is well-formed when treated as an
4710     //   unevaluated operand (Clause 5), then is_destructible<T>::value is true
4711     if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4712       CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4713       if (!Destructor)
4714         return false;
4715       //  C++14 [dcl.fct.def.delete]p2:
4716       //    A program that refers to a deleted function implicitly or
4717       //    explicitly, other than to declare it, is ill-formed.
4718       if (Destructor->isDeleted())
4719         return false;
4720       if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4721         return false;
4722       if (UTT == UTT_IsNothrowDestructible) {
4723         const FunctionProtoType *CPT =
4724             Destructor->getType()->getAs<FunctionProtoType>();
4725         CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4726         if (!CPT || !CPT->isNothrow())
4727           return false;
4728       }
4729     }
4730     return true;
4731 
4732   case UTT_HasTrivialDestructor:
4733     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4734     //   If __is_pod (type) is true or type is a reference type
4735     //   then the trait is true, else if type is a cv class or union
4736     //   type (or array thereof) with a trivial destructor
4737     //   ([class.dtor]) then the trait is true, else it is
4738     //   false.
4739     if (T.isPODType(C) || T->isReferenceType())
4740       return true;
4741 
4742     // Objective-C++ ARC: autorelease types don't require destruction.
4743     if (T->isObjCLifetimeType() &&
4744         T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4745       return true;
4746 
4747     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4748       return RD->hasTrivialDestructor();
4749     return false;
4750   // TODO: Propagate nothrowness for implicitly declared special members.
4751   case UTT_HasNothrowAssign:
4752     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4753     //   If type is const qualified or is a reference type then the
4754     //   trait is false. Otherwise if __has_trivial_assign (type)
4755     //   is true then the trait is true, else if type is a cv class
4756     //   or union type with copy assignment operators that are known
4757     //   not to throw an exception then the trait is true, else it is
4758     //   false.
4759     if (C.getBaseElementType(T).isConstQualified())
4760       return false;
4761     if (T->isReferenceType())
4762       return false;
4763     if (T.isPODType(C) || T->isObjCLifetimeType())
4764       return true;
4765 
4766     if (const RecordType *RT = T->getAs<RecordType>())
4767       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4768                                 &CXXRecordDecl::hasTrivialCopyAssignment,
4769                                 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4770                                 &CXXMethodDecl::isCopyAssignmentOperator);
4771     return false;
4772   case UTT_HasNothrowMoveAssign:
4773     //  This trait is implemented by MSVC 2012 and needed to parse the
4774     //  standard library headers. Specifically this is used as the logic
4775     //  behind std::is_nothrow_move_assignable (20.9.4.3).
4776     if (T.isPODType(C))
4777       return true;
4778 
4779     if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4780       return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4781                                 &CXXRecordDecl::hasTrivialMoveAssignment,
4782                                 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4783                                 &CXXMethodDecl::isMoveAssignmentOperator);
4784     return false;
4785   case UTT_HasNothrowCopy:
4786     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4787     //   If __has_trivial_copy (type) is true then the trait is true, else
4788     //   if type is a cv class or union type with copy constructors that are
4789     //   known not to throw an exception then the trait is true, else it is
4790     //   false.
4791     if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4792       return true;
4793     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4794       if (RD->hasTrivialCopyConstructor() &&
4795           !RD->hasNonTrivialCopyConstructor())
4796         return true;
4797 
4798       bool FoundConstructor = false;
4799       unsigned FoundTQs;
4800       for (const auto *ND : Self.LookupConstructors(RD)) {
4801         // A template constructor is never a copy constructor.
4802         // FIXME: However, it may actually be selected at the actual overload
4803         // resolution point.
4804         if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4805           continue;
4806         // UsingDecl itself is not a constructor
4807         if (isa<UsingDecl>(ND))
4808           continue;
4809         auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4810         if (Constructor->isCopyConstructor(FoundTQs)) {
4811           FoundConstructor = true;
4812           const FunctionProtoType *CPT
4813               = Constructor->getType()->getAs<FunctionProtoType>();
4814           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4815           if (!CPT)
4816             return false;
4817           // TODO: check whether evaluating default arguments can throw.
4818           // For now, we'll be conservative and assume that they can throw.
4819           if (!CPT->isNothrow() || CPT->getNumParams() > 1)
4820             return false;
4821         }
4822       }
4823 
4824       return FoundConstructor;
4825     }
4826     return false;
4827   case UTT_HasNothrowConstructor:
4828     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4829     //   If __has_trivial_constructor (type) is true then the trait is
4830     //   true, else if type is a cv class or union type (or array
4831     //   thereof) with a default constructor that is known not to
4832     //   throw an exception then the trait is true, else it is false.
4833     if (T.isPODType(C) || T->isObjCLifetimeType())
4834       return true;
4835     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4836       if (RD->hasTrivialDefaultConstructor() &&
4837           !RD->hasNonTrivialDefaultConstructor())
4838         return true;
4839 
4840       bool FoundConstructor = false;
4841       for (const auto *ND : Self.LookupConstructors(RD)) {
4842         // FIXME: In C++0x, a constructor template can be a default constructor.
4843         if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4844           continue;
4845         // UsingDecl itself is not a constructor
4846         if (isa<UsingDecl>(ND))
4847           continue;
4848         auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4849         if (Constructor->isDefaultConstructor()) {
4850           FoundConstructor = true;
4851           const FunctionProtoType *CPT
4852               = Constructor->getType()->getAs<FunctionProtoType>();
4853           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4854           if (!CPT)
4855             return false;
4856           // FIXME: check whether evaluating default arguments can throw.
4857           // For now, we'll be conservative and assume that they can throw.
4858           if (!CPT->isNothrow() || CPT->getNumParams() > 0)
4859             return false;
4860         }
4861       }
4862       return FoundConstructor;
4863     }
4864     return false;
4865   case UTT_HasVirtualDestructor:
4866     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4867     //   If type is a class type with a virtual destructor ([class.dtor])
4868     //   then the trait is true, else it is false.
4869     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4870       if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4871         return Destructor->isVirtual();
4872     return false;
4873 
4874     // These type trait expressions are modeled on the specifications for the
4875     // Embarcadero C++0x type trait functions:
4876     //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4877   case UTT_IsCompleteType:
4878     // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4879     //   Returns True if and only if T is a complete type at the point of the
4880     //   function call.
4881     return !T->isIncompleteType();
4882   case UTT_HasUniqueObjectRepresentations:
4883     return C.hasUniqueObjectRepresentations(T);
4884   }
4885 }
4886 
4887 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4888                                     QualType RhsT, SourceLocation KeyLoc);
4889 
4890 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4891                               ArrayRef<TypeSourceInfo *> Args,
4892                               SourceLocation RParenLoc) {
4893   if (Kind <= UTT_Last)
4894     return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4895 
4896   // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4897   // traits to avoid duplication.
4898   if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4899     return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4900                                    Args[1]->getType(), RParenLoc);
4901 
4902   switch (Kind) {
4903   case clang::BTT_ReferenceBindsToTemporary:
4904   case clang::TT_IsConstructible:
4905   case clang::TT_IsNothrowConstructible:
4906   case clang::TT_IsTriviallyConstructible: {
4907     // C++11 [meta.unary.prop]:
4908     //   is_trivially_constructible is defined as:
4909     //
4910     //     is_constructible<T, Args...>::value is true and the variable
4911     //     definition for is_constructible, as defined below, is known to call
4912     //     no operation that is not trivial.
4913     //
4914     //   The predicate condition for a template specialization
4915     //   is_constructible<T, Args...> shall be satisfied if and only if the
4916     //   following variable definition would be well-formed for some invented
4917     //   variable t:
4918     //
4919     //     T t(create<Args>()...);
4920     assert(!Args.empty());
4921 
4922     // Precondition: T and all types in the parameter pack Args shall be
4923     // complete types, (possibly cv-qualified) void, or arrays of
4924     // unknown bound.
4925     for (const auto *TSI : Args) {
4926       QualType ArgTy = TSI->getType();
4927       if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4928         continue;
4929 
4930       if (S.RequireCompleteType(KWLoc, ArgTy,
4931           diag::err_incomplete_type_used_in_type_trait_expr))
4932         return false;
4933     }
4934 
4935     // Make sure the first argument is not incomplete nor a function type.
4936     QualType T = Args[0]->getType();
4937     if (T->isIncompleteType() || T->isFunctionType())
4938       return false;
4939 
4940     // Make sure the first argument is not an abstract type.
4941     CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4942     if (RD && RD->isAbstract())
4943       return false;
4944 
4945     SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4946     SmallVector<Expr *, 2> ArgExprs;
4947     ArgExprs.reserve(Args.size() - 1);
4948     for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4949       QualType ArgTy = Args[I]->getType();
4950       if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4951         ArgTy = S.Context.getRValueReferenceType(ArgTy);
4952       OpaqueArgExprs.push_back(
4953           OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
4954                           ArgTy.getNonLValueExprType(S.Context),
4955                           Expr::getValueKindForType(ArgTy)));
4956     }
4957     for (Expr &E : OpaqueArgExprs)
4958       ArgExprs.push_back(&E);
4959 
4960     // Perform the initialization in an unevaluated context within a SFINAE
4961     // trap at translation unit scope.
4962     EnterExpressionEvaluationContext Unevaluated(
4963         S, Sema::ExpressionEvaluationContext::Unevaluated);
4964     Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4965     Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4966     InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4967     InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4968                                                                  RParenLoc));
4969     InitializationSequence Init(S, To, InitKind, ArgExprs);
4970     if (Init.Failed())
4971       return false;
4972 
4973     ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4974     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4975       return false;
4976 
4977     if (Kind == clang::TT_IsConstructible)
4978       return true;
4979 
4980     if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4981       if (!T->isReferenceType())
4982         return false;
4983 
4984       return !Init.isDirectReferenceBinding();
4985     }
4986 
4987     if (Kind == clang::TT_IsNothrowConstructible)
4988       return S.canThrow(Result.get()) == CT_Cannot;
4989 
4990     if (Kind == clang::TT_IsTriviallyConstructible) {
4991       // Under Objective-C ARC and Weak, if the destination has non-trivial
4992       // Objective-C lifetime, this is a non-trivial construction.
4993       if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
4994         return false;
4995 
4996       // The initialization succeeded; now make sure there are no non-trivial
4997       // calls.
4998       return !Result.get()->hasNonTrivialCall(S.Context);
4999     }
5000 
5001     llvm_unreachable("unhandled type trait");
5002     return false;
5003   }
5004     default: llvm_unreachable("not a TT");
5005   }
5006 
5007   return false;
5008 }
5009 
5010 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5011                                 ArrayRef<TypeSourceInfo *> Args,
5012                                 SourceLocation RParenLoc) {
5013   QualType ResultType = Context.getLogicalOperationType();
5014 
5015   if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5016                                *this, Kind, KWLoc, Args[0]->getType()))
5017     return ExprError();
5018 
5019   bool Dependent = false;
5020   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5021     if (Args[I]->getType()->isDependentType()) {
5022       Dependent = true;
5023       break;
5024     }
5025   }
5026 
5027   bool Result = false;
5028   if (!Dependent)
5029     Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5030 
5031   return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5032                                RParenLoc, Result);
5033 }
5034 
5035 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5036                                 ArrayRef<ParsedType> Args,
5037                                 SourceLocation RParenLoc) {
5038   SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5039   ConvertedArgs.reserve(Args.size());
5040 
5041   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5042     TypeSourceInfo *TInfo;
5043     QualType T = GetTypeFromParser(Args[I], &TInfo);
5044     if (!TInfo)
5045       TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5046 
5047     ConvertedArgs.push_back(TInfo);
5048   }
5049 
5050   return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5051 }
5052 
5053 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5054                                     QualType RhsT, SourceLocation KeyLoc) {
5055   assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5056          "Cannot evaluate traits of dependent types");
5057 
5058   switch(BTT) {
5059   case BTT_IsBaseOf: {
5060     // C++0x [meta.rel]p2
5061     // Base is a base class of Derived without regard to cv-qualifiers or
5062     // Base and Derived are not unions and name the same class type without
5063     // regard to cv-qualifiers.
5064 
5065     const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5066     const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5067     if (!rhsRecord || !lhsRecord) {
5068       const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5069       const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5070       if (!LHSObjTy || !RHSObjTy)
5071         return false;
5072 
5073       ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5074       ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5075       if (!BaseInterface || !DerivedInterface)
5076         return false;
5077 
5078       if (Self.RequireCompleteType(
5079               KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5080         return false;
5081 
5082       return BaseInterface->isSuperClassOf(DerivedInterface);
5083     }
5084 
5085     assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5086              == (lhsRecord == rhsRecord));
5087 
5088     if (lhsRecord == rhsRecord)
5089       return !lhsRecord->getDecl()->isUnion();
5090 
5091     // C++0x [meta.rel]p2:
5092     //   If Base and Derived are class types and are different types
5093     //   (ignoring possible cv-qualifiers) then Derived shall be a
5094     //   complete type.
5095     if (Self.RequireCompleteType(KeyLoc, RhsT,
5096                           diag::err_incomplete_type_used_in_type_trait_expr))
5097       return false;
5098 
5099     return cast<CXXRecordDecl>(rhsRecord->getDecl())
5100       ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5101   }
5102   case BTT_IsSame:
5103     return Self.Context.hasSameType(LhsT, RhsT);
5104   case BTT_TypeCompatible: {
5105     // GCC ignores cv-qualifiers on arrays for this builtin.
5106     Qualifiers LhsQuals, RhsQuals;
5107     QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5108     QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5109     return Self.Context.typesAreCompatible(Lhs, Rhs);
5110   }
5111   case BTT_IsConvertible:
5112   case BTT_IsConvertibleTo: {
5113     // C++0x [meta.rel]p4:
5114     //   Given the following function prototype:
5115     //
5116     //     template <class T>
5117     //       typename add_rvalue_reference<T>::type create();
5118     //
5119     //   the predicate condition for a template specialization
5120     //   is_convertible<From, To> shall be satisfied if and only if
5121     //   the return expression in the following code would be
5122     //   well-formed, including any implicit conversions to the return
5123     //   type of the function:
5124     //
5125     //     To test() {
5126     //       return create<From>();
5127     //     }
5128     //
5129     //   Access checking is performed as if in a context unrelated to To and
5130     //   From. Only the validity of the immediate context of the expression
5131     //   of the return-statement (including conversions to the return type)
5132     //   is considered.
5133     //
5134     // We model the initialization as a copy-initialization of a temporary
5135     // of the appropriate type, which for this expression is identical to the
5136     // return statement (since NRVO doesn't apply).
5137 
5138     // Functions aren't allowed to return function or array types.
5139     if (RhsT->isFunctionType() || RhsT->isArrayType())
5140       return false;
5141 
5142     // A return statement in a void function must have void type.
5143     if (RhsT->isVoidType())
5144       return LhsT->isVoidType();
5145 
5146     // A function definition requires a complete, non-abstract return type.
5147     if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5148       return false;
5149 
5150     // Compute the result of add_rvalue_reference.
5151     if (LhsT->isObjectType() || LhsT->isFunctionType())
5152       LhsT = Self.Context.getRValueReferenceType(LhsT);
5153 
5154     // Build a fake source and destination for initialization.
5155     InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5156     OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5157                          Expr::getValueKindForType(LhsT));
5158     Expr *FromPtr = &From;
5159     InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
5160                                                            SourceLocation()));
5161 
5162     // Perform the initialization in an unevaluated context within a SFINAE
5163     // trap at translation unit scope.
5164     EnterExpressionEvaluationContext Unevaluated(
5165         Self, Sema::ExpressionEvaluationContext::Unevaluated);
5166     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5167     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5168     InitializationSequence Init(Self, To, Kind, FromPtr);
5169     if (Init.Failed())
5170       return false;
5171 
5172     ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5173     return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5174   }
5175 
5176   case BTT_IsAssignable:
5177   case BTT_IsNothrowAssignable:
5178   case BTT_IsTriviallyAssignable: {
5179     // C++11 [meta.unary.prop]p3:
5180     //   is_trivially_assignable is defined as:
5181     //     is_assignable<T, U>::value is true and the assignment, as defined by
5182     //     is_assignable, is known to call no operation that is not trivial
5183     //
5184     //   is_assignable is defined as:
5185     //     The expression declval<T>() = declval<U>() is well-formed when
5186     //     treated as an unevaluated operand (Clause 5).
5187     //
5188     //   For both, T and U shall be complete types, (possibly cv-qualified)
5189     //   void, or arrays of unknown bound.
5190     if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5191         Self.RequireCompleteType(KeyLoc, LhsT,
5192           diag::err_incomplete_type_used_in_type_trait_expr))
5193       return false;
5194     if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5195         Self.RequireCompleteType(KeyLoc, RhsT,
5196           diag::err_incomplete_type_used_in_type_trait_expr))
5197       return false;
5198 
5199     // cv void is never assignable.
5200     if (LhsT->isVoidType() || RhsT->isVoidType())
5201       return false;
5202 
5203     // Build expressions that emulate the effect of declval<T>() and
5204     // declval<U>().
5205     if (LhsT->isObjectType() || LhsT->isFunctionType())
5206       LhsT = Self.Context.getRValueReferenceType(LhsT);
5207     if (RhsT->isObjectType() || RhsT->isFunctionType())
5208       RhsT = Self.Context.getRValueReferenceType(RhsT);
5209     OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5210                         Expr::getValueKindForType(LhsT));
5211     OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5212                         Expr::getValueKindForType(RhsT));
5213 
5214     // Attempt the assignment in an unevaluated context within a SFINAE
5215     // trap at translation unit scope.
5216     EnterExpressionEvaluationContext Unevaluated(
5217         Self, Sema::ExpressionEvaluationContext::Unevaluated);
5218     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5219     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5220     ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5221                                         &Rhs);
5222     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5223       return false;
5224 
5225     if (BTT == BTT_IsAssignable)
5226       return true;
5227 
5228     if (BTT == BTT_IsNothrowAssignable)
5229       return Self.canThrow(Result.get()) == CT_Cannot;
5230 
5231     if (BTT == BTT_IsTriviallyAssignable) {
5232       // Under Objective-C ARC and Weak, if the destination has non-trivial
5233       // Objective-C lifetime, this is a non-trivial assignment.
5234       if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5235         return false;
5236 
5237       return !Result.get()->hasNonTrivialCall(Self.Context);
5238     }
5239 
5240     llvm_unreachable("unhandled type trait");
5241     return false;
5242   }
5243     default: llvm_unreachable("not a BTT");
5244   }
5245   llvm_unreachable("Unknown type trait or not implemented");
5246 }
5247 
5248 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5249                                      SourceLocation KWLoc,
5250                                      ParsedType Ty,
5251                                      Expr* DimExpr,
5252                                      SourceLocation RParen) {
5253   TypeSourceInfo *TSInfo;
5254   QualType T = GetTypeFromParser(Ty, &TSInfo);
5255   if (!TSInfo)
5256     TSInfo = Context.getTrivialTypeSourceInfo(T);
5257 
5258   return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5259 }
5260 
5261 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5262                                            QualType T, Expr *DimExpr,
5263                                            SourceLocation KeyLoc) {
5264   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5265 
5266   switch(ATT) {
5267   case ATT_ArrayRank:
5268     if (T->isArrayType()) {
5269       unsigned Dim = 0;
5270       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5271         ++Dim;
5272         T = AT->getElementType();
5273       }
5274       return Dim;
5275     }
5276     return 0;
5277 
5278   case ATT_ArrayExtent: {
5279     llvm::APSInt Value;
5280     uint64_t Dim;
5281     if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5282           diag::err_dimension_expr_not_constant_integer,
5283           false).isInvalid())
5284       return 0;
5285     if (Value.isSigned() && Value.isNegative()) {
5286       Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5287         << DimExpr->getSourceRange();
5288       return 0;
5289     }
5290     Dim = Value.getLimitedValue();
5291 
5292     if (T->isArrayType()) {
5293       unsigned D = 0;
5294       bool Matched = false;
5295       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5296         if (Dim == D) {
5297           Matched = true;
5298           break;
5299         }
5300         ++D;
5301         T = AT->getElementType();
5302       }
5303 
5304       if (Matched && T->isArrayType()) {
5305         if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5306           return CAT->getSize().getLimitedValue();
5307       }
5308     }
5309     return 0;
5310   }
5311   }
5312   llvm_unreachable("Unknown type trait or not implemented");
5313 }
5314 
5315 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5316                                      SourceLocation KWLoc,
5317                                      TypeSourceInfo *TSInfo,
5318                                      Expr* DimExpr,
5319                                      SourceLocation RParen) {
5320   QualType T = TSInfo->getType();
5321 
5322   // FIXME: This should likely be tracked as an APInt to remove any host
5323   // assumptions about the width of size_t on the target.
5324   uint64_t Value = 0;
5325   if (!T->isDependentType())
5326     Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5327 
5328   // While the specification for these traits from the Embarcadero C++
5329   // compiler's documentation says the return type is 'unsigned int', Clang
5330   // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5331   // compiler, there is no difference. On several other platforms this is an
5332   // important distinction.
5333   return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5334                                           RParen, Context.getSizeType());
5335 }
5336 
5337 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5338                                       SourceLocation KWLoc,
5339                                       Expr *Queried,
5340                                       SourceLocation RParen) {
5341   // If error parsing the expression, ignore.
5342   if (!Queried)
5343     return ExprError();
5344 
5345   ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5346 
5347   return Result;
5348 }
5349 
5350 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5351   switch (ET) {
5352   case ET_IsLValueExpr: return E->isLValue();
5353   case ET_IsRValueExpr: return E->isRValue();
5354   }
5355   llvm_unreachable("Expression trait not covered by switch");
5356 }
5357 
5358 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5359                                       SourceLocation KWLoc,
5360                                       Expr *Queried,
5361                                       SourceLocation RParen) {
5362   if (Queried->isTypeDependent()) {
5363     // Delay type-checking for type-dependent expressions.
5364   } else if (Queried->getType()->isPlaceholderType()) {
5365     ExprResult PE = CheckPlaceholderExpr(Queried);
5366     if (PE.isInvalid()) return ExprError();
5367     return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5368   }
5369 
5370   bool Value = EvaluateExpressionTrait(ET, Queried);
5371 
5372   return new (Context)
5373       ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5374 }
5375 
5376 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5377                                             ExprValueKind &VK,
5378                                             SourceLocation Loc,
5379                                             bool isIndirect) {
5380   assert(!LHS.get()->getType()->isPlaceholderType() &&
5381          !RHS.get()->getType()->isPlaceholderType() &&
5382          "placeholders should have been weeded out by now");
5383 
5384   // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5385   // temporary materialization conversion otherwise.
5386   if (isIndirect)
5387     LHS = DefaultLvalueConversion(LHS.get());
5388   else if (LHS.get()->isRValue())
5389     LHS = TemporaryMaterializationConversion(LHS.get());
5390   if (LHS.isInvalid())
5391     return QualType();
5392 
5393   // The RHS always undergoes lvalue conversions.
5394   RHS = DefaultLvalueConversion(RHS.get());
5395   if (RHS.isInvalid()) return QualType();
5396 
5397   const char *OpSpelling = isIndirect ? "->*" : ".*";
5398   // C++ 5.5p2
5399   //   The binary operator .* [p3: ->*] binds its second operand, which shall
5400   //   be of type "pointer to member of T" (where T is a completely-defined
5401   //   class type) [...]
5402   QualType RHSType = RHS.get()->getType();
5403   const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5404   if (!MemPtr) {
5405     Diag(Loc, diag::err_bad_memptr_rhs)
5406       << OpSpelling << RHSType << RHS.get()->getSourceRange();
5407     return QualType();
5408   }
5409 
5410   QualType Class(MemPtr->getClass(), 0);
5411 
5412   // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5413   // member pointer points must be completely-defined. However, there is no
5414   // reason for this semantic distinction, and the rule is not enforced by
5415   // other compilers. Therefore, we do not check this property, as it is
5416   // likely to be considered a defect.
5417 
5418   // C++ 5.5p2
5419   //   [...] to its first operand, which shall be of class T or of a class of
5420   //   which T is an unambiguous and accessible base class. [p3: a pointer to
5421   //   such a class]
5422   QualType LHSType = LHS.get()->getType();
5423   if (isIndirect) {
5424     if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5425       LHSType = Ptr->getPointeeType();
5426     else {
5427       Diag(Loc, diag::err_bad_memptr_lhs)
5428         << OpSpelling << 1 << LHSType
5429         << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5430       return QualType();
5431     }
5432   }
5433 
5434   if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5435     // If we want to check the hierarchy, we need a complete type.
5436     if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5437                             OpSpelling, (int)isIndirect)) {
5438       return QualType();
5439     }
5440 
5441     if (!IsDerivedFrom(Loc, LHSType, Class)) {
5442       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5443         << (int)isIndirect << LHS.get()->getType();
5444       return QualType();
5445     }
5446 
5447     CXXCastPath BasePath;
5448     if (CheckDerivedToBaseConversion(
5449             LHSType, Class, Loc,
5450             SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5451             &BasePath))
5452       return QualType();
5453 
5454     // Cast LHS to type of use.
5455     QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5456     if (isIndirect)
5457       UseType = Context.getPointerType(UseType);
5458     ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5459     LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5460                             &BasePath);
5461   }
5462 
5463   if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5464     // Diagnose use of pointer-to-member type which when used as
5465     // the functional cast in a pointer-to-member expression.
5466     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5467      return QualType();
5468   }
5469 
5470   // C++ 5.5p2
5471   //   The result is an object or a function of the type specified by the
5472   //   second operand.
5473   // The cv qualifiers are the union of those in the pointer and the left side,
5474   // in accordance with 5.5p5 and 5.2.5.
5475   QualType Result = MemPtr->getPointeeType();
5476   Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5477 
5478   // C++0x [expr.mptr.oper]p6:
5479   //   In a .* expression whose object expression is an rvalue, the program is
5480   //   ill-formed if the second operand is a pointer to member function with
5481   //   ref-qualifier &. In a ->* expression or in a .* expression whose object
5482   //   expression is an lvalue, the program is ill-formed if the second operand
5483   //   is a pointer to member function with ref-qualifier &&.
5484   if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5485     switch (Proto->getRefQualifier()) {
5486     case RQ_None:
5487       // Do nothing
5488       break;
5489 
5490     case RQ_LValue:
5491       if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5492         // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5493         // is (exactly) 'const'.
5494         if (Proto->isConst() && !Proto->isVolatile())
5495           Diag(Loc, getLangOpts().CPlusPlus2a
5496                         ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5497                         : diag::ext_pointer_to_const_ref_member_on_rvalue);
5498         else
5499           Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5500               << RHSType << 1 << LHS.get()->getSourceRange();
5501       }
5502       break;
5503 
5504     case RQ_RValue:
5505       if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5506         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5507           << RHSType << 0 << LHS.get()->getSourceRange();
5508       break;
5509     }
5510   }
5511 
5512   // C++ [expr.mptr.oper]p6:
5513   //   The result of a .* expression whose second operand is a pointer
5514   //   to a data member is of the same value category as its
5515   //   first operand. The result of a .* expression whose second
5516   //   operand is a pointer to a member function is a prvalue. The
5517   //   result of an ->* expression is an lvalue if its second operand
5518   //   is a pointer to data member and a prvalue otherwise.
5519   if (Result->isFunctionType()) {
5520     VK = VK_RValue;
5521     return Context.BoundMemberTy;
5522   } else if (isIndirect) {
5523     VK = VK_LValue;
5524   } else {
5525     VK = LHS.get()->getValueKind();
5526   }
5527 
5528   return Result;
5529 }
5530 
5531 /// Try to convert a type to another according to C++11 5.16p3.
5532 ///
5533 /// This is part of the parameter validation for the ? operator. If either
5534 /// value operand is a class type, the two operands are attempted to be
5535 /// converted to each other. This function does the conversion in one direction.
5536 /// It returns true if the program is ill-formed and has already been diagnosed
5537 /// as such.
5538 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5539                                 SourceLocation QuestionLoc,
5540                                 bool &HaveConversion,
5541                                 QualType &ToType) {
5542   HaveConversion = false;
5543   ToType = To->getType();
5544 
5545   InitializationKind Kind =
5546       InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
5547   // C++11 5.16p3
5548   //   The process for determining whether an operand expression E1 of type T1
5549   //   can be converted to match an operand expression E2 of type T2 is defined
5550   //   as follows:
5551   //   -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5552   //      implicitly converted to type "lvalue reference to T2", subject to the
5553   //      constraint that in the conversion the reference must bind directly to
5554   //      an lvalue.
5555   //   -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5556   //      implicitly converted to the type "rvalue reference to R2", subject to
5557   //      the constraint that the reference must bind directly.
5558   if (To->isLValue() || To->isXValue()) {
5559     QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5560                                 : Self.Context.getRValueReferenceType(ToType);
5561 
5562     InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5563 
5564     InitializationSequence InitSeq(Self, Entity, Kind, From);
5565     if (InitSeq.isDirectReferenceBinding()) {
5566       ToType = T;
5567       HaveConversion = true;
5568       return false;
5569     }
5570 
5571     if (InitSeq.isAmbiguous())
5572       return InitSeq.Diagnose(Self, Entity, Kind, From);
5573   }
5574 
5575   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
5576   //      -- if E1 and E2 have class type, and the underlying class types are
5577   //         the same or one is a base class of the other:
5578   QualType FTy = From->getType();
5579   QualType TTy = To->getType();
5580   const RecordType *FRec = FTy->getAs<RecordType>();
5581   const RecordType *TRec = TTy->getAs<RecordType>();
5582   bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5583                        Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5584   if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5585                        Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5586     //         E1 can be converted to match E2 if the class of T2 is the
5587     //         same type as, or a base class of, the class of T1, and
5588     //         [cv2 > cv1].
5589     if (FRec == TRec || FDerivedFromT) {
5590       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5591         InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5592         InitializationSequence InitSeq(Self, Entity, Kind, From);
5593         if (InitSeq) {
5594           HaveConversion = true;
5595           return false;
5596         }
5597 
5598         if (InitSeq.isAmbiguous())
5599           return InitSeq.Diagnose(Self, Entity, Kind, From);
5600       }
5601     }
5602 
5603     return false;
5604   }
5605 
5606   //     -- Otherwise: E1 can be converted to match E2 if E1 can be
5607   //        implicitly converted to the type that expression E2 would have
5608   //        if E2 were converted to an rvalue (or the type it has, if E2 is
5609   //        an rvalue).
5610   //
5611   // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5612   // to the array-to-pointer or function-to-pointer conversions.
5613   TTy = TTy.getNonLValueExprType(Self.Context);
5614 
5615   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5616   InitializationSequence InitSeq(Self, Entity, Kind, From);
5617   HaveConversion = !InitSeq.Failed();
5618   ToType = TTy;
5619   if (InitSeq.isAmbiguous())
5620     return InitSeq.Diagnose(Self, Entity, Kind, From);
5621 
5622   return false;
5623 }
5624 
5625 /// Try to find a common type for two according to C++0x 5.16p5.
5626 ///
5627 /// This is part of the parameter validation for the ? operator. If either
5628 /// value operand is a class type, overload resolution is used to find a
5629 /// conversion to a common type.
5630 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5631                                     SourceLocation QuestionLoc) {
5632   Expr *Args[2] = { LHS.get(), RHS.get() };
5633   OverloadCandidateSet CandidateSet(QuestionLoc,
5634                                     OverloadCandidateSet::CSK_Operator);
5635   Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5636                                     CandidateSet);
5637 
5638   OverloadCandidateSet::iterator Best;
5639   switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5640     case OR_Success: {
5641       // We found a match. Perform the conversions on the arguments and move on.
5642       ExprResult LHSRes = Self.PerformImplicitConversion(
5643           LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5644           Sema::AA_Converting);
5645       if (LHSRes.isInvalid())
5646         break;
5647       LHS = LHSRes;
5648 
5649       ExprResult RHSRes = Self.PerformImplicitConversion(
5650           RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5651           Sema::AA_Converting);
5652       if (RHSRes.isInvalid())
5653         break;
5654       RHS = RHSRes;
5655       if (Best->Function)
5656         Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5657       return false;
5658     }
5659 
5660     case OR_No_Viable_Function:
5661 
5662       // Emit a better diagnostic if one of the expressions is a null pointer
5663       // constant and the other is a pointer type. In this case, the user most
5664       // likely forgot to take the address of the other expression.
5665       if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5666         return true;
5667 
5668       Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5669         << LHS.get()->getType() << RHS.get()->getType()
5670         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5671       return true;
5672 
5673     case OR_Ambiguous:
5674       Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5675         << LHS.get()->getType() << RHS.get()->getType()
5676         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5677       // FIXME: Print the possible common types by printing the return types of
5678       // the viable candidates.
5679       break;
5680 
5681     case OR_Deleted:
5682       llvm_unreachable("Conditional operator has only built-in overloads");
5683   }
5684   return true;
5685 }
5686 
5687 /// Perform an "extended" implicit conversion as returned by
5688 /// TryClassUnification.
5689 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5690   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5691   InitializationKind Kind =
5692       InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
5693   Expr *Arg = E.get();
5694   InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5695   ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5696   if (Result.isInvalid())
5697     return true;
5698 
5699   E = Result;
5700   return false;
5701 }
5702 
5703 /// Check the operands of ?: under C++ semantics.
5704 ///
5705 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5706 /// extension. In this case, LHS == Cond. (But they're not aliases.)
5707 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5708                                            ExprResult &RHS, ExprValueKind &VK,
5709                                            ExprObjectKind &OK,
5710                                            SourceLocation QuestionLoc) {
5711   // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5712   // interface pointers.
5713 
5714   // C++11 [expr.cond]p1
5715   //   The first expression is contextually converted to bool.
5716   //
5717   // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5718   //        a is that of a integer vector with the same number of elements and
5719   //        size as the vectors of b and c. If one of either b or c is a scalar
5720   //        it is implicitly converted to match the type of the vector.
5721   //        Otherwise the expression is ill-formed. If both b and c are scalars,
5722   //        then b and c are checked and converted to the type of a if possible.
5723   //        Unlike the OpenCL ?: operator, the expression is evaluated as
5724   //        (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5725   if (!Cond.get()->isTypeDependent()) {
5726     ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5727     if (CondRes.isInvalid())
5728       return QualType();
5729     Cond = CondRes;
5730   }
5731 
5732   // Assume r-value.
5733   VK = VK_RValue;
5734   OK = OK_Ordinary;
5735 
5736   // Either of the arguments dependent?
5737   if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5738     return Context.DependentTy;
5739 
5740   // C++11 [expr.cond]p2
5741   //   If either the second or the third operand has type (cv) void, ...
5742   QualType LTy = LHS.get()->getType();
5743   QualType RTy = RHS.get()->getType();
5744   bool LVoid = LTy->isVoidType();
5745   bool RVoid = RTy->isVoidType();
5746   if (LVoid || RVoid) {
5747     //   ... one of the following shall hold:
5748     //   -- The second or the third operand (but not both) is a (possibly
5749     //      parenthesized) throw-expression; the result is of the type
5750     //      and value category of the other.
5751     bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5752     bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5753     if (LThrow != RThrow) {
5754       Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5755       VK = NonThrow->getValueKind();
5756       // DR (no number yet): the result is a bit-field if the
5757       // non-throw-expression operand is a bit-field.
5758       OK = NonThrow->getObjectKind();
5759       return NonThrow->getType();
5760     }
5761 
5762     //   -- Both the second and third operands have type void; the result is of
5763     //      type void and is a prvalue.
5764     if (LVoid && RVoid)
5765       return Context.VoidTy;
5766 
5767     // Neither holds, error.
5768     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5769       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5770       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5771     return QualType();
5772   }
5773 
5774   // Neither is void.
5775 
5776   // C++11 [expr.cond]p3
5777   //   Otherwise, if the second and third operand have different types, and
5778   //   either has (cv) class type [...] an attempt is made to convert each of
5779   //   those operands to the type of the other.
5780   if (!Context.hasSameType(LTy, RTy) &&
5781       (LTy->isRecordType() || RTy->isRecordType())) {
5782     // These return true if a single direction is already ambiguous.
5783     QualType L2RType, R2LType;
5784     bool HaveL2R, HaveR2L;
5785     if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5786       return QualType();
5787     if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5788       return QualType();
5789 
5790     //   If both can be converted, [...] the program is ill-formed.
5791     if (HaveL2R && HaveR2L) {
5792       Diag(QuestionLoc, diag::err_conditional_ambiguous)
5793         << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5794       return QualType();
5795     }
5796 
5797     //   If exactly one conversion is possible, that conversion is applied to
5798     //   the chosen operand and the converted operands are used in place of the
5799     //   original operands for the remainder of this section.
5800     if (HaveL2R) {
5801       if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5802         return QualType();
5803       LTy = LHS.get()->getType();
5804     } else if (HaveR2L) {
5805       if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5806         return QualType();
5807       RTy = RHS.get()->getType();
5808     }
5809   }
5810 
5811   // C++11 [expr.cond]p3
5812   //   if both are glvalues of the same value category and the same type except
5813   //   for cv-qualification, an attempt is made to convert each of those
5814   //   operands to the type of the other.
5815   // FIXME:
5816   //   Resolving a defect in P0012R1: we extend this to cover all cases where
5817   //   one of the operands is reference-compatible with the other, in order
5818   //   to support conditionals between functions differing in noexcept.
5819   ExprValueKind LVK = LHS.get()->getValueKind();
5820   ExprValueKind RVK = RHS.get()->getValueKind();
5821   if (!Context.hasSameType(LTy, RTy) &&
5822       LVK == RVK && LVK != VK_RValue) {
5823     // DerivedToBase was already handled by the class-specific case above.
5824     // FIXME: Should we allow ObjC conversions here?
5825     bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5826     if (CompareReferenceRelationship(
5827             QuestionLoc, LTy, RTy, DerivedToBase,
5828             ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5829         !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5830         // [...] subject to the constraint that the reference must bind
5831         // directly [...]
5832         !RHS.get()->refersToBitField() &&
5833         !RHS.get()->refersToVectorElement()) {
5834       RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5835       RTy = RHS.get()->getType();
5836     } else if (CompareReferenceRelationship(
5837                    QuestionLoc, RTy, LTy, DerivedToBase,
5838                    ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5839                !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5840                !LHS.get()->refersToBitField() &&
5841                !LHS.get()->refersToVectorElement()) {
5842       LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5843       LTy = LHS.get()->getType();
5844     }
5845   }
5846 
5847   // C++11 [expr.cond]p4
5848   //   If the second and third operands are glvalues of the same value
5849   //   category and have the same type, the result is of that type and
5850   //   value category and it is a bit-field if the second or the third
5851   //   operand is a bit-field, or if both are bit-fields.
5852   // We only extend this to bitfields, not to the crazy other kinds of
5853   // l-values.
5854   bool Same = Context.hasSameType(LTy, RTy);
5855   if (Same && LVK == RVK && LVK != VK_RValue &&
5856       LHS.get()->isOrdinaryOrBitFieldObject() &&
5857       RHS.get()->isOrdinaryOrBitFieldObject()) {
5858     VK = LHS.get()->getValueKind();
5859     if (LHS.get()->getObjectKind() == OK_BitField ||
5860         RHS.get()->getObjectKind() == OK_BitField)
5861       OK = OK_BitField;
5862 
5863     // If we have function pointer types, unify them anyway to unify their
5864     // exception specifications, if any.
5865     if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5866       Qualifiers Qs = LTy.getQualifiers();
5867       LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
5868                                      /*ConvertArgs*/false);
5869       LTy = Context.getQualifiedType(LTy, Qs);
5870 
5871       assert(!LTy.isNull() && "failed to find composite pointer type for "
5872                               "canonically equivalent function ptr types");
5873       assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5874     }
5875 
5876     return LTy;
5877   }
5878 
5879   // C++11 [expr.cond]p5
5880   //   Otherwise, the result is a prvalue. If the second and third operands
5881   //   do not have the same type, and either has (cv) class type, ...
5882   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5883     //   ... overload resolution is used to determine the conversions (if any)
5884     //   to be applied to the operands. If the overload resolution fails, the
5885     //   program is ill-formed.
5886     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5887       return QualType();
5888   }
5889 
5890   // C++11 [expr.cond]p6
5891   //   Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5892   //   conversions are performed on the second and third operands.
5893   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5894   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5895   if (LHS.isInvalid() || RHS.isInvalid())
5896     return QualType();
5897   LTy = LHS.get()->getType();
5898   RTy = RHS.get()->getType();
5899 
5900   //   After those conversions, one of the following shall hold:
5901   //   -- The second and third operands have the same type; the result
5902   //      is of that type. If the operands have class type, the result
5903   //      is a prvalue temporary of the result type, which is
5904   //      copy-initialized from either the second operand or the third
5905   //      operand depending on the value of the first operand.
5906   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5907     if (LTy->isRecordType()) {
5908       // The operands have class type. Make a temporary copy.
5909       InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
5910 
5911       ExprResult LHSCopy = PerformCopyInitialization(Entity,
5912                                                      SourceLocation(),
5913                                                      LHS);
5914       if (LHSCopy.isInvalid())
5915         return QualType();
5916 
5917       ExprResult RHSCopy = PerformCopyInitialization(Entity,
5918                                                      SourceLocation(),
5919                                                      RHS);
5920       if (RHSCopy.isInvalid())
5921         return QualType();
5922 
5923       LHS = LHSCopy;
5924       RHS = RHSCopy;
5925     }
5926 
5927     // If we have function pointer types, unify them anyway to unify their
5928     // exception specifications, if any.
5929     if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5930       LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5931       assert(!LTy.isNull() && "failed to find composite pointer type for "
5932                               "canonically equivalent function ptr types");
5933     }
5934 
5935     return LTy;
5936   }
5937 
5938   // Extension: conditional operator involving vector types.
5939   if (LTy->isVectorType() || RTy->isVectorType())
5940     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5941                                /*AllowBothBool*/true,
5942                                /*AllowBoolConversions*/false);
5943 
5944   //   -- The second and third operands have arithmetic or enumeration type;
5945   //      the usual arithmetic conversions are performed to bring them to a
5946   //      common type, and the result is of that type.
5947   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5948     QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5949     if (LHS.isInvalid() || RHS.isInvalid())
5950       return QualType();
5951     if (ResTy.isNull()) {
5952       Diag(QuestionLoc,
5953            diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5954         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5955       return QualType();
5956     }
5957 
5958     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5959     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5960 
5961     return ResTy;
5962   }
5963 
5964   //   -- The second and third operands have pointer type, or one has pointer
5965   //      type and the other is a null pointer constant, or both are null
5966   //      pointer constants, at least one of which is non-integral; pointer
5967   //      conversions and qualification conversions are performed to bring them
5968   //      to their composite pointer type. The result is of the composite
5969   //      pointer type.
5970   //   -- The second and third operands have pointer to member type, or one has
5971   //      pointer to member type and the other is a null pointer constant;
5972   //      pointer to member conversions and qualification conversions are
5973   //      performed to bring them to a common type, whose cv-qualification
5974   //      shall match the cv-qualification of either the second or the third
5975   //      operand. The result is of the common type.
5976   QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5977   if (!Composite.isNull())
5978     return Composite;
5979 
5980   // Similarly, attempt to find composite type of two objective-c pointers.
5981   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5982   if (!Composite.isNull())
5983     return Composite;
5984 
5985   // Check if we are using a null with a non-pointer type.
5986   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5987     return QualType();
5988 
5989   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5990     << LHS.get()->getType() << RHS.get()->getType()
5991     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5992   return QualType();
5993 }
5994 
5995 static FunctionProtoType::ExceptionSpecInfo
5996 mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5997                     FunctionProtoType::ExceptionSpecInfo ESI2,
5998                     SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5999   ExceptionSpecificationType EST1 = ESI1.Type;
6000   ExceptionSpecificationType EST2 = ESI2.Type;
6001 
6002   // If either of them can throw anything, that is the result.
6003   if (EST1 == EST_None) return ESI1;
6004   if (EST2 == EST_None) return ESI2;
6005   if (EST1 == EST_MSAny) return ESI1;
6006   if (EST2 == EST_MSAny) return ESI2;
6007   if (EST1 == EST_NoexceptFalse) return ESI1;
6008   if (EST2 == EST_NoexceptFalse) return ESI2;
6009 
6010   // If either of them is non-throwing, the result is the other.
6011   if (EST1 == EST_DynamicNone) return ESI2;
6012   if (EST2 == EST_DynamicNone) return ESI1;
6013   if (EST1 == EST_BasicNoexcept) return ESI2;
6014   if (EST2 == EST_BasicNoexcept) return ESI1;
6015   if (EST1 == EST_NoexceptTrue) return ESI2;
6016   if (EST2 == EST_NoexceptTrue) return ESI1;
6017 
6018   // If we're left with value-dependent computed noexcept expressions, we're
6019   // stuck. Before C++17, we can just drop the exception specification entirely,
6020   // since it's not actually part of the canonical type. And this should never
6021   // happen in C++17, because it would mean we were computing the composite
6022   // pointer type of dependent types, which should never happen.
6023   if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
6024     assert(!S.getLangOpts().CPlusPlus17 &&
6025            "computing composite pointer type of dependent types");
6026     return FunctionProtoType::ExceptionSpecInfo();
6027   }
6028 
6029   // Switch over the possibilities so that people adding new values know to
6030   // update this function.
6031   switch (EST1) {
6032   case EST_None:
6033   case EST_DynamicNone:
6034   case EST_MSAny:
6035   case EST_BasicNoexcept:
6036   case EST_DependentNoexcept:
6037   case EST_NoexceptFalse:
6038   case EST_NoexceptTrue:
6039     llvm_unreachable("handled above");
6040 
6041   case EST_Dynamic: {
6042     // This is the fun case: both exception specifications are dynamic. Form
6043     // the union of the two lists.
6044     assert(EST2 == EST_Dynamic && "other cases should already be handled");
6045     llvm::SmallPtrSet<QualType, 8> Found;
6046     for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6047       for (QualType E : Exceptions)
6048         if (Found.insert(S.Context.getCanonicalType(E)).second)
6049           ExceptionTypeStorage.push_back(E);
6050 
6051     FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6052     Result.Exceptions = ExceptionTypeStorage;
6053     return Result;
6054   }
6055 
6056   case EST_Unevaluated:
6057   case EST_Uninstantiated:
6058   case EST_Unparsed:
6059     llvm_unreachable("shouldn't see unresolved exception specifications here");
6060   }
6061 
6062   llvm_unreachable("invalid ExceptionSpecificationType");
6063 }
6064 
6065 /// Find a merged pointer type and convert the two expressions to it.
6066 ///
6067 /// This finds the composite pointer type (or member pointer type) for @p E1
6068 /// and @p E2 according to C++1z 5p14. It converts both expressions to this
6069 /// type and returns it.
6070 /// It does not emit diagnostics.
6071 ///
6072 /// \param Loc The location of the operator requiring these two expressions to
6073 /// be converted to the composite pointer type.
6074 ///
6075 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
6076 QualType Sema::FindCompositePointerType(SourceLocation Loc,
6077                                         Expr *&E1, Expr *&E2,
6078                                         bool ConvertArgs) {
6079   assert(getLangOpts().CPlusPlus && "This function assumes C++");
6080 
6081   // C++1z [expr]p14:
6082   //   The composite pointer type of two operands p1 and p2 having types T1
6083   //   and T2
6084   QualType T1 = E1->getType(), T2 = E2->getType();
6085 
6086   //   where at least one is a pointer or pointer to member type or
6087   //   std::nullptr_t is:
6088   bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6089                          T1->isNullPtrType();
6090   bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6091                          T2->isNullPtrType();
6092   if (!T1IsPointerLike && !T2IsPointerLike)
6093     return QualType();
6094 
6095   //   - if both p1 and p2 are null pointer constants, std::nullptr_t;
6096   // This can't actually happen, following the standard, but we also use this
6097   // to implement the end of [expr.conv], which hits this case.
6098   //
6099   //   - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6100   if (T1IsPointerLike &&
6101       E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6102     if (ConvertArgs)
6103       E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6104                                          ? CK_NullToMemberPointer
6105                                          : CK_NullToPointer).get();
6106     return T1;
6107   }
6108   if (T2IsPointerLike &&
6109       E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6110     if (ConvertArgs)
6111       E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6112                                          ? CK_NullToMemberPointer
6113                                          : CK_NullToPointer).get();
6114     return T2;
6115   }
6116 
6117   // Now both have to be pointers or member pointers.
6118   if (!T1IsPointerLike || !T2IsPointerLike)
6119     return QualType();
6120   assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6121          "nullptr_t should be a null pointer constant");
6122 
6123   //  - if T1 or T2 is "pointer to cv1 void" and the other type is
6124   //    "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6125   //    the union of cv1 and cv2;
6126   //  - if T1 or T2 is "pointer to noexcept function" and the other type is
6127   //    "pointer to function", where the function types are otherwise the same,
6128   //    "pointer to function";
6129   //     FIXME: This rule is defective: it should also permit removing noexcept
6130   //     from a pointer to member function.  As a Clang extension, we also
6131   //     permit removing 'noreturn', so we generalize this rule to;
6132   //     - [Clang] If T1 and T2 are both of type "pointer to function" or
6133   //       "pointer to member function" and the pointee types can be unified
6134   //       by a function pointer conversion, that conversion is applied
6135   //       before checking the following rules.
6136   //  - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6137   //    is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6138   //    the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6139   //    respectively;
6140   //  - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6141   //    to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6142   //    C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6143   //    T1 or the cv-combined type of T1 and T2, respectively;
6144   //  - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6145   //    T2;
6146   //
6147   // If looked at in the right way, these bullets all do the same thing.
6148   // What we do here is, we build the two possible cv-combined types, and try
6149   // the conversions in both directions. If only one works, or if the two
6150   // composite types are the same, we have succeeded.
6151   // FIXME: extended qualifiers?
6152   //
6153   // Note that this will fail to find a composite pointer type for "pointer
6154   // to void" and "pointer to function". We can't actually perform the final
6155   // conversion in this case, even though a composite pointer type formally
6156   // exists.
6157   SmallVector<unsigned, 4> QualifierUnion;
6158   SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
6159   QualType Composite1 = T1;
6160   QualType Composite2 = T2;
6161   unsigned NeedConstBefore = 0;
6162   while (true) {
6163     const PointerType *Ptr1, *Ptr2;
6164     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6165         (Ptr2 = Composite2->getAs<PointerType>())) {
6166       Composite1 = Ptr1->getPointeeType();
6167       Composite2 = Ptr2->getPointeeType();
6168 
6169       // If we're allowed to create a non-standard composite type, keep track
6170       // of where we need to fill in additional 'const' qualifiers.
6171       if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
6172         NeedConstBefore = QualifierUnion.size();
6173 
6174       QualifierUnion.push_back(
6175                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6176       MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
6177       continue;
6178     }
6179 
6180     const MemberPointerType *MemPtr1, *MemPtr2;
6181     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6182         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6183       Composite1 = MemPtr1->getPointeeType();
6184       Composite2 = MemPtr2->getPointeeType();
6185 
6186       // If we're allowed to create a non-standard composite type, keep track
6187       // of where we need to fill in additional 'const' qualifiers.
6188       if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
6189         NeedConstBefore = QualifierUnion.size();
6190 
6191       QualifierUnion.push_back(
6192                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6193       MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6194                                              MemPtr2->getClass()));
6195       continue;
6196     }
6197 
6198     // FIXME: block pointer types?
6199 
6200     // Cannot unwrap any more types.
6201     break;
6202   }
6203 
6204   // Apply the function pointer conversion to unify the types. We've already
6205   // unwrapped down to the function types, and we want to merge rather than
6206   // just convert, so do this ourselves rather than calling
6207   // IsFunctionConversion.
6208   //
6209   // FIXME: In order to match the standard wording as closely as possible, we
6210   // currently only do this under a single level of pointers. Ideally, we would
6211   // allow this in general, and set NeedConstBefore to the relevant depth on
6212   // the side(s) where we changed anything.
6213   if (QualifierUnion.size() == 1) {
6214     if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6215       if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6216         FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6217         FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6218 
6219         // The result is noreturn if both operands are.
6220         bool Noreturn =
6221             EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6222         EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6223         EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6224 
6225         // The result is nothrow if both operands are.
6226         SmallVector<QualType, 8> ExceptionTypeStorage;
6227         EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6228             mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6229                                 ExceptionTypeStorage);
6230 
6231         Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6232                                              FPT1->getParamTypes(), EPI1);
6233         Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6234                                              FPT2->getParamTypes(), EPI2);
6235       }
6236     }
6237   }
6238 
6239   if (NeedConstBefore) {
6240     // Extension: Add 'const' to qualifiers that come before the first qualifier
6241     // mismatch, so that our (non-standard!) composite type meets the
6242     // requirements of C++ [conv.qual]p4 bullet 3.
6243     for (unsigned I = 0; I != NeedConstBefore; ++I)
6244       if ((QualifierUnion[I] & Qualifiers::Const) == 0)
6245         QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
6246   }
6247 
6248   // Rewrap the composites as pointers or member pointers with the union CVRs.
6249   auto MOC = MemberOfClass.rbegin();
6250   for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6251     Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6252     auto Classes = *MOC++;
6253     if (Classes.first && Classes.second) {
6254       // Rebuild member pointer type
6255       Composite1 = Context.getMemberPointerType(
6256           Context.getQualifiedType(Composite1, Quals), Classes.first);
6257       Composite2 = Context.getMemberPointerType(
6258           Context.getQualifiedType(Composite2, Quals), Classes.second);
6259     } else {
6260       // Rebuild pointer type
6261       Composite1 =
6262           Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6263       Composite2 =
6264           Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
6265     }
6266   }
6267 
6268   struct Conversion {
6269     Sema &S;
6270     Expr *&E1, *&E2;
6271     QualType Composite;
6272     InitializedEntity Entity;
6273     InitializationKind Kind;
6274     InitializationSequence E1ToC, E2ToC;
6275     bool Viable;
6276 
6277     Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6278                QualType Composite)
6279         : S(S), E1(E1), E2(E2), Composite(Composite),
6280           Entity(InitializedEntity::InitializeTemporary(Composite)),
6281           Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6282           E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6283           Viable(E1ToC && E2ToC) {}
6284 
6285     bool perform() {
6286       ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6287       if (E1Result.isInvalid())
6288         return true;
6289       E1 = E1Result.getAs<Expr>();
6290 
6291       ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6292       if (E2Result.isInvalid())
6293         return true;
6294       E2 = E2Result.getAs<Expr>();
6295 
6296       return false;
6297     }
6298   };
6299 
6300   // Try to convert to each composite pointer type.
6301   Conversion C1(*this, Loc, E1, E2, Composite1);
6302   if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6303     if (ConvertArgs && C1.perform())
6304       return QualType();
6305     return C1.Composite;
6306   }
6307   Conversion C2(*this, Loc, E1, E2, Composite2);
6308 
6309   if (C1.Viable == C2.Viable) {
6310     // Either Composite1 and Composite2 are viable and are different, or
6311     // neither is viable.
6312     // FIXME: How both be viable and different?
6313     return QualType();
6314   }
6315 
6316   // Convert to the chosen type.
6317   if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6318     return QualType();
6319 
6320   return C1.Viable ? C1.Composite : C2.Composite;
6321 }
6322 
6323 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
6324   if (!E)
6325     return ExprError();
6326 
6327   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6328 
6329   // If the result is a glvalue, we shouldn't bind it.
6330   if (!E->isRValue())
6331     return E;
6332 
6333   // In ARC, calls that return a retainable type can return retained,
6334   // in which case we have to insert a consuming cast.
6335   if (getLangOpts().ObjCAutoRefCount &&
6336       E->getType()->isObjCRetainableType()) {
6337 
6338     bool ReturnsRetained;
6339 
6340     // For actual calls, we compute this by examining the type of the
6341     // called value.
6342     if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6343       Expr *Callee = Call->getCallee()->IgnoreParens();
6344       QualType T = Callee->getType();
6345 
6346       if (T == Context.BoundMemberTy) {
6347         // Handle pointer-to-members.
6348         if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6349           T = BinOp->getRHS()->getType();
6350         else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6351           T = Mem->getMemberDecl()->getType();
6352       }
6353 
6354       if (const PointerType *Ptr = T->getAs<PointerType>())
6355         T = Ptr->getPointeeType();
6356       else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6357         T = Ptr->getPointeeType();
6358       else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6359         T = MemPtr->getPointeeType();
6360 
6361       const FunctionType *FTy = T->getAs<FunctionType>();
6362       assert(FTy && "call to value not of function type?");
6363       ReturnsRetained = FTy->getExtInfo().getProducesResult();
6364 
6365     // ActOnStmtExpr arranges things so that StmtExprs of retainable
6366     // type always produce a +1 object.
6367     } else if (isa<StmtExpr>(E)) {
6368       ReturnsRetained = true;
6369 
6370     // We hit this case with the lambda conversion-to-block optimization;
6371     // we don't want any extra casts here.
6372     } else if (isa<CastExpr>(E) &&
6373                isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6374       return E;
6375 
6376     // For message sends and property references, we try to find an
6377     // actual method.  FIXME: we should infer retention by selector in
6378     // cases where we don't have an actual method.
6379     } else {
6380       ObjCMethodDecl *D = nullptr;
6381       if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6382         D = Send->getMethodDecl();
6383       } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6384         D = BoxedExpr->getBoxingMethod();
6385       } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6386         // Don't do reclaims if we're using the zero-element array
6387         // constant.
6388         if (ArrayLit->getNumElements() == 0 &&
6389             Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6390           return E;
6391 
6392         D = ArrayLit->getArrayWithObjectsMethod();
6393       } else if (ObjCDictionaryLiteral *DictLit
6394                                         = dyn_cast<ObjCDictionaryLiteral>(E)) {
6395         // Don't do reclaims if we're using the zero-element dictionary
6396         // constant.
6397         if (DictLit->getNumElements() == 0 &&
6398             Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6399           return E;
6400 
6401         D = DictLit->getDictWithObjectsMethod();
6402       }
6403 
6404       ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6405 
6406       // Don't do reclaims on performSelector calls; despite their
6407       // return type, the invoked method doesn't necessarily actually
6408       // return an object.
6409       if (!ReturnsRetained &&
6410           D && D->getMethodFamily() == OMF_performSelector)
6411         return E;
6412     }
6413 
6414     // Don't reclaim an object of Class type.
6415     if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6416       return E;
6417 
6418     Cleanup.setExprNeedsCleanups(true);
6419 
6420     CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6421                                    : CK_ARCReclaimReturnedObject);
6422     return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6423                                     VK_RValue);
6424   }
6425 
6426   if (!getLangOpts().CPlusPlus)
6427     return E;
6428 
6429   // Search for the base element type (cf. ASTContext::getBaseElementType) with
6430   // a fast path for the common case that the type is directly a RecordType.
6431   const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6432   const RecordType *RT = nullptr;
6433   while (!RT) {
6434     switch (T->getTypeClass()) {
6435     case Type::Record:
6436       RT = cast<RecordType>(T);
6437       break;
6438     case Type::ConstantArray:
6439     case Type::IncompleteArray:
6440     case Type::VariableArray:
6441     case Type::DependentSizedArray:
6442       T = cast<ArrayType>(T)->getElementType().getTypePtr();
6443       break;
6444     default:
6445       return E;
6446     }
6447   }
6448 
6449   // That should be enough to guarantee that this type is complete, if we're
6450   // not processing a decltype expression.
6451   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6452   if (RD->isInvalidDecl() || RD->isDependentContext())
6453     return E;
6454 
6455   bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6456                     ExpressionEvaluationContextRecord::EK_Decltype;
6457   CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6458 
6459   if (Destructor) {
6460     MarkFunctionReferenced(E->getExprLoc(), Destructor);
6461     CheckDestructorAccess(E->getExprLoc(), Destructor,
6462                           PDiag(diag::err_access_dtor_temp)
6463                             << E->getType());
6464     if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6465       return ExprError();
6466 
6467     // If destructor is trivial, we can avoid the extra copy.
6468     if (Destructor->isTrivial())
6469       return E;
6470 
6471     // We need a cleanup, but we don't need to remember the temporary.
6472     Cleanup.setExprNeedsCleanups(true);
6473   }
6474 
6475   CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
6476   CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6477 
6478   if (IsDecltype)
6479     ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6480 
6481   return Bind;
6482 }
6483 
6484 ExprResult
6485 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
6486   if (SubExpr.isInvalid())
6487     return ExprError();
6488 
6489   return MaybeCreateExprWithCleanups(SubExpr.get());
6490 }
6491 
6492 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
6493   assert(SubExpr && "subexpression can't be null!");
6494 
6495   CleanupVarDeclMarking();
6496 
6497   unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6498   assert(ExprCleanupObjects.size() >= FirstCleanup);
6499   assert(Cleanup.exprNeedsCleanups() ||
6500          ExprCleanupObjects.size() == FirstCleanup);
6501   if (!Cleanup.exprNeedsCleanups())
6502     return SubExpr;
6503 
6504   auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6505                                      ExprCleanupObjects.size() - FirstCleanup);
6506 
6507   auto *E = ExprWithCleanups::Create(
6508       Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6509   DiscardCleanupsInEvaluationContext();
6510 
6511   return E;
6512 }
6513 
6514 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
6515   assert(SubStmt && "sub-statement can't be null!");
6516 
6517   CleanupVarDeclMarking();
6518 
6519   if (!Cleanup.exprNeedsCleanups())
6520     return SubStmt;
6521 
6522   // FIXME: In order to attach the temporaries, wrap the statement into
6523   // a StmtExpr; currently this is only used for asm statements.
6524   // This is hacky, either create a new CXXStmtWithTemporaries statement or
6525   // a new AsmStmtWithTemporaries.
6526   CompoundStmt *CompStmt = CompoundStmt::Create(
6527       Context, SubStmt, SourceLocation(), SourceLocation());
6528   Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6529                                    SourceLocation());
6530   return MaybeCreateExprWithCleanups(E);
6531 }
6532 
6533 /// Process the expression contained within a decltype. For such expressions,
6534 /// certain semantic checks on temporaries are delayed until this point, and
6535 /// are omitted for the 'topmost' call in the decltype expression. If the
6536 /// topmost call bound a temporary, strip that temporary off the expression.
6537 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
6538   assert(ExprEvalContexts.back().ExprContext ==
6539              ExpressionEvaluationContextRecord::EK_Decltype &&
6540          "not in a decltype expression");
6541 
6542   // C++11 [expr.call]p11:
6543   //   If a function call is a prvalue of object type,
6544   // -- if the function call is either
6545   //   -- the operand of a decltype-specifier, or
6546   //   -- the right operand of a comma operator that is the operand of a
6547   //      decltype-specifier,
6548   //   a temporary object is not introduced for the prvalue.
6549 
6550   // Recursively rebuild ParenExprs and comma expressions to strip out the
6551   // outermost CXXBindTemporaryExpr, if any.
6552   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6553     ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6554     if (SubExpr.isInvalid())
6555       return ExprError();
6556     if (SubExpr.get() == PE->getSubExpr())
6557       return E;
6558     return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6559   }
6560   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6561     if (BO->getOpcode() == BO_Comma) {
6562       ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6563       if (RHS.isInvalid())
6564         return ExprError();
6565       if (RHS.get() == BO->getRHS())
6566         return E;
6567       return new (Context) BinaryOperator(
6568           BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6569           BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
6570     }
6571   }
6572 
6573   CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6574   CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6575                               : nullptr;
6576   if (TopCall)
6577     E = TopCall;
6578   else
6579     TopBind = nullptr;
6580 
6581   // Disable the special decltype handling now.
6582   ExprEvalContexts.back().ExprContext =
6583       ExpressionEvaluationContextRecord::EK_Other;
6584 
6585   // In MS mode, don't perform any extra checking of call return types within a
6586   // decltype expression.
6587   if (getLangOpts().MSVCCompat)
6588     return E;
6589 
6590   // Perform the semantic checks we delayed until this point.
6591   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6592        I != N; ++I) {
6593     CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6594     if (Call == TopCall)
6595       continue;
6596 
6597     if (CheckCallReturnType(Call->getCallReturnType(Context),
6598                             Call->getBeginLoc(), Call, Call->getDirectCallee()))
6599       return ExprError();
6600   }
6601 
6602   // Now all relevant types are complete, check the destructors are accessible
6603   // and non-deleted, and annotate them on the temporaries.
6604   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6605        I != N; ++I) {
6606     CXXBindTemporaryExpr *Bind =
6607       ExprEvalContexts.back().DelayedDecltypeBinds[I];
6608     if (Bind == TopBind)
6609       continue;
6610 
6611     CXXTemporary *Temp = Bind->getTemporary();
6612 
6613     CXXRecordDecl *RD =
6614       Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6615     CXXDestructorDecl *Destructor = LookupDestructor(RD);
6616     Temp->setDestructor(Destructor);
6617 
6618     MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6619     CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6620                           PDiag(diag::err_access_dtor_temp)
6621                             << Bind->getType());
6622     if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6623       return ExprError();
6624 
6625     // We need a cleanup, but we don't need to remember the temporary.
6626     Cleanup.setExprNeedsCleanups(true);
6627   }
6628 
6629   // Possibly strip off the top CXXBindTemporaryExpr.
6630   return E;
6631 }
6632 
6633 /// Note a set of 'operator->' functions that were used for a member access.
6634 static void noteOperatorArrows(Sema &S,
6635                                ArrayRef<FunctionDecl *> OperatorArrows) {
6636   unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6637   // FIXME: Make this configurable?
6638   unsigned Limit = 9;
6639   if (OperatorArrows.size() > Limit) {
6640     // Produce Limit-1 normal notes and one 'skipping' note.
6641     SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6642     SkipCount = OperatorArrows.size() - (Limit - 1);
6643   }
6644 
6645   for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6646     if (I == SkipStart) {
6647       S.Diag(OperatorArrows[I]->getLocation(),
6648              diag::note_operator_arrows_suppressed)
6649           << SkipCount;
6650       I += SkipCount;
6651     } else {
6652       S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6653           << OperatorArrows[I]->getCallResultType();
6654       ++I;
6655     }
6656   }
6657 }
6658 
6659 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6660                                               SourceLocation OpLoc,
6661                                               tok::TokenKind OpKind,
6662                                               ParsedType &ObjectType,
6663                                               bool &MayBePseudoDestructor) {
6664   // Since this might be a postfix expression, get rid of ParenListExprs.
6665   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
6666   if (Result.isInvalid()) return ExprError();
6667   Base = Result.get();
6668 
6669   Result = CheckPlaceholderExpr(Base);
6670   if (Result.isInvalid()) return ExprError();
6671   Base = Result.get();
6672 
6673   QualType BaseType = Base->getType();
6674   MayBePseudoDestructor = false;
6675   if (BaseType->isDependentType()) {
6676     // If we have a pointer to a dependent type and are using the -> operator,
6677     // the object type is the type that the pointer points to. We might still
6678     // have enough information about that type to do something useful.
6679     if (OpKind == tok::arrow)
6680       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6681         BaseType = Ptr->getPointeeType();
6682 
6683     ObjectType = ParsedType::make(BaseType);
6684     MayBePseudoDestructor = true;
6685     return Base;
6686   }
6687 
6688   // C++ [over.match.oper]p8:
6689   //   [...] When operator->returns, the operator-> is applied  to the value
6690   //   returned, with the original second operand.
6691   if (OpKind == tok::arrow) {
6692     QualType StartingType = BaseType;
6693     bool NoArrowOperatorFound = false;
6694     bool FirstIteration = true;
6695     FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6696     // The set of types we've considered so far.
6697     llvm::SmallPtrSet<CanQualType,8> CTypes;
6698     SmallVector<FunctionDecl*, 8> OperatorArrows;
6699     CTypes.insert(Context.getCanonicalType(BaseType));
6700 
6701     while (BaseType->isRecordType()) {
6702       if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6703         Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6704           << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6705         noteOperatorArrows(*this, OperatorArrows);
6706         Diag(OpLoc, diag::note_operator_arrow_depth)
6707           << getLangOpts().ArrowDepth;
6708         return ExprError();
6709       }
6710 
6711       Result = BuildOverloadedArrowExpr(
6712           S, Base, OpLoc,
6713           // When in a template specialization and on the first loop iteration,
6714           // potentially give the default diagnostic (with the fixit in a
6715           // separate note) instead of having the error reported back to here
6716           // and giving a diagnostic with a fixit attached to the error itself.
6717           (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
6718               ? nullptr
6719               : &NoArrowOperatorFound);
6720       if (Result.isInvalid()) {
6721         if (NoArrowOperatorFound) {
6722           if (FirstIteration) {
6723             Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6724               << BaseType << 1 << Base->getSourceRange()
6725               << FixItHint::CreateReplacement(OpLoc, ".");
6726             OpKind = tok::period;
6727             break;
6728           }
6729           Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6730             << BaseType << Base->getSourceRange();
6731           CallExpr *CE = dyn_cast<CallExpr>(Base);
6732           if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
6733             Diag(CD->getBeginLoc(),
6734                  diag::note_member_reference_arrow_from_operator_arrow);
6735           }
6736         }
6737         return ExprError();
6738       }
6739       Base = Result.get();
6740       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
6741         OperatorArrows.push_back(OpCall->getDirectCallee());
6742       BaseType = Base->getType();
6743       CanQualType CBaseType = Context.getCanonicalType(BaseType);
6744       if (!CTypes.insert(CBaseType).second) {
6745         Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6746         noteOperatorArrows(*this, OperatorArrows);
6747         return ExprError();
6748       }
6749       FirstIteration = false;
6750     }
6751 
6752     if (OpKind == tok::arrow &&
6753         (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
6754       BaseType = BaseType->getPointeeType();
6755   }
6756 
6757   // Objective-C properties allow "." access on Objective-C pointer types,
6758   // so adjust the base type to the object type itself.
6759   if (BaseType->isObjCObjectPointerType())
6760     BaseType = BaseType->getPointeeType();
6761 
6762   // C++ [basic.lookup.classref]p2:
6763   //   [...] If the type of the object expression is of pointer to scalar
6764   //   type, the unqualified-id is looked up in the context of the complete
6765   //   postfix-expression.
6766   //
6767   // This also indicates that we could be parsing a pseudo-destructor-name.
6768   // Note that Objective-C class and object types can be pseudo-destructor
6769   // expressions or normal member (ivar or property) access expressions, and
6770   // it's legal for the type to be incomplete if this is a pseudo-destructor
6771   // call.  We'll do more incomplete-type checks later in the lookup process,
6772   // so just skip this check for ObjC types.
6773   if (BaseType->isObjCObjectOrInterfaceType()) {
6774     ObjectType = ParsedType::make(BaseType);
6775     MayBePseudoDestructor = true;
6776     return Base;
6777   } else if (!BaseType->isRecordType()) {
6778     ObjectType = nullptr;
6779     MayBePseudoDestructor = true;
6780     return Base;
6781   }
6782 
6783   // The object type must be complete (or dependent), or
6784   // C++11 [expr.prim.general]p3:
6785   //   Unlike the object expression in other contexts, *this is not required to
6786   //   be of complete type for purposes of class member access (5.2.5) outside
6787   //   the member function body.
6788   if (!BaseType->isDependentType() &&
6789       !isThisOutsideMemberFunctionBody(BaseType) &&
6790       RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
6791     return ExprError();
6792 
6793   // C++ [basic.lookup.classref]p2:
6794   //   If the id-expression in a class member access (5.2.5) is an
6795   //   unqualified-id, and the type of the object expression is of a class
6796   //   type C (or of pointer to a class type C), the unqualified-id is looked
6797   //   up in the scope of class C. [...]
6798   ObjectType = ParsedType::make(BaseType);
6799   return Base;
6800 }
6801 
6802 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
6803                    tok::TokenKind& OpKind, SourceLocation OpLoc) {
6804   if (Base->hasPlaceholderType()) {
6805     ExprResult result = S.CheckPlaceholderExpr(Base);
6806     if (result.isInvalid()) return true;
6807     Base = result.get();
6808   }
6809   ObjectType = Base->getType();
6810 
6811   // C++ [expr.pseudo]p2:
6812   //   The left-hand side of the dot operator shall be of scalar type. The
6813   //   left-hand side of the arrow operator shall be of pointer to scalar type.
6814   //   This scalar type is the object type.
6815   // Note that this is rather different from the normal handling for the
6816   // arrow operator.
6817   if (OpKind == tok::arrow) {
6818     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6819       ObjectType = Ptr->getPointeeType();
6820     } else if (!Base->isTypeDependent()) {
6821       // The user wrote "p->" when they probably meant "p."; fix it.
6822       S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6823         << ObjectType << true
6824         << FixItHint::CreateReplacement(OpLoc, ".");
6825       if (S.isSFINAEContext())
6826         return true;
6827 
6828       OpKind = tok::period;
6829     }
6830   }
6831 
6832   return false;
6833 }
6834 
6835 /// Check if it's ok to try and recover dot pseudo destructor calls on
6836 /// pointer objects.
6837 static bool
6838 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6839                                                    QualType DestructedType) {
6840   // If this is a record type, check if its destructor is callable.
6841   if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6842     if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6843       return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6844     return false;
6845   }
6846 
6847   // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6848   return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6849          DestructedType->isVectorType();
6850 }
6851 
6852 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
6853                                            SourceLocation OpLoc,
6854                                            tok::TokenKind OpKind,
6855                                            const CXXScopeSpec &SS,
6856                                            TypeSourceInfo *ScopeTypeInfo,
6857                                            SourceLocation CCLoc,
6858                                            SourceLocation TildeLoc,
6859                                          PseudoDestructorTypeStorage Destructed) {
6860   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
6861 
6862   QualType ObjectType;
6863   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6864     return ExprError();
6865 
6866   if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6867       !ObjectType->isVectorType()) {
6868     if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
6869       Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
6870     else {
6871       Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6872         << ObjectType << Base->getSourceRange();
6873       return ExprError();
6874     }
6875   }
6876 
6877   // C++ [expr.pseudo]p2:
6878   //   [...] The cv-unqualified versions of the object type and of the type
6879   //   designated by the pseudo-destructor-name shall be the same type.
6880   if (DestructedTypeInfo) {
6881     QualType DestructedType = DestructedTypeInfo->getType();
6882     SourceLocation DestructedTypeStart
6883       = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
6884     if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6885       if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6886         // Detect dot pseudo destructor calls on pointer objects, e.g.:
6887         //   Foo *foo;
6888         //   foo.~Foo();
6889         if (OpKind == tok::period && ObjectType->isPointerType() &&
6890             Context.hasSameUnqualifiedType(DestructedType,
6891                                            ObjectType->getPointeeType())) {
6892           auto Diagnostic =
6893               Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6894               << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
6895 
6896           // Issue a fixit only when the destructor is valid.
6897           if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6898                   *this, DestructedType))
6899             Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6900 
6901           // Recover by setting the object type to the destructed type and the
6902           // operator to '->'.
6903           ObjectType = DestructedType;
6904           OpKind = tok::arrow;
6905         } else {
6906           Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6907               << ObjectType << DestructedType << Base->getSourceRange()
6908               << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6909 
6910           // Recover by setting the destructed type to the object type.
6911           DestructedType = ObjectType;
6912           DestructedTypeInfo =
6913               Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6914           Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6915         }
6916       } else if (DestructedType.getObjCLifetime() !=
6917                                                 ObjectType.getObjCLifetime()) {
6918 
6919         if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6920           // Okay: just pretend that the user provided the correctly-qualified
6921           // type.
6922         } else {
6923           Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6924             << ObjectType << DestructedType << Base->getSourceRange()
6925             << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6926         }
6927 
6928         // Recover by setting the destructed type to the object type.
6929         DestructedType = ObjectType;
6930         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6931                                                            DestructedTypeStart);
6932         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6933       }
6934     }
6935   }
6936 
6937   // C++ [expr.pseudo]p2:
6938   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6939   //   form
6940   //
6941   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
6942   //
6943   //   shall designate the same scalar type.
6944   if (ScopeTypeInfo) {
6945     QualType ScopeType = ScopeTypeInfo->getType();
6946     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
6947         !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
6948 
6949       Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
6950            diag::err_pseudo_dtor_type_mismatch)
6951         << ObjectType << ScopeType << Base->getSourceRange()
6952         << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
6953 
6954       ScopeType = QualType();
6955       ScopeTypeInfo = nullptr;
6956     }
6957   }
6958 
6959   Expr *Result
6960     = new (Context) CXXPseudoDestructorExpr(Context, Base,
6961                                             OpKind == tok::arrow, OpLoc,
6962                                             SS.getWithLocInContext(Context),
6963                                             ScopeTypeInfo,
6964                                             CCLoc,
6965                                             TildeLoc,
6966                                             Destructed);
6967 
6968   return Result;
6969 }
6970 
6971 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6972                                            SourceLocation OpLoc,
6973                                            tok::TokenKind OpKind,
6974                                            CXXScopeSpec &SS,
6975                                            UnqualifiedId &FirstTypeName,
6976                                            SourceLocation CCLoc,
6977                                            SourceLocation TildeLoc,
6978                                            UnqualifiedId &SecondTypeName) {
6979   assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6980           FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
6981          "Invalid first type name in pseudo-destructor");
6982   assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6983           SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
6984          "Invalid second type name in pseudo-destructor");
6985 
6986   QualType ObjectType;
6987   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6988     return ExprError();
6989 
6990   // Compute the object type that we should use for name lookup purposes. Only
6991   // record types and dependent types matter.
6992   ParsedType ObjectTypePtrForLookup;
6993   if (!SS.isSet()) {
6994     if (ObjectType->isRecordType())
6995       ObjectTypePtrForLookup = ParsedType::make(ObjectType);
6996     else if (ObjectType->isDependentType())
6997       ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
6998   }
6999 
7000   // Convert the name of the type being destructed (following the ~) into a
7001   // type (with source-location information).
7002   QualType DestructedType;
7003   TypeSourceInfo *DestructedTypeInfo = nullptr;
7004   PseudoDestructorTypeStorage Destructed;
7005   if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7006     ParsedType T = getTypeName(*SecondTypeName.Identifier,
7007                                SecondTypeName.StartLocation,
7008                                S, &SS, true, false, ObjectTypePtrForLookup,
7009                                /*IsCtorOrDtorName*/true);
7010     if (!T &&
7011         ((SS.isSet() && !computeDeclContext(SS, false)) ||
7012          (!SS.isSet() && ObjectType->isDependentType()))) {
7013       // The name of the type being destroyed is a dependent name, and we
7014       // couldn't find anything useful in scope. Just store the identifier and
7015       // it's location, and we'll perform (qualified) name lookup again at
7016       // template instantiation time.
7017       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7018                                                SecondTypeName.StartLocation);
7019     } else if (!T) {
7020       Diag(SecondTypeName.StartLocation,
7021            diag::err_pseudo_dtor_destructor_non_type)
7022         << SecondTypeName.Identifier << ObjectType;
7023       if (isSFINAEContext())
7024         return ExprError();
7025 
7026       // Recover by assuming we had the right type all along.
7027       DestructedType = ObjectType;
7028     } else
7029       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7030   } else {
7031     // Resolve the template-id to a type.
7032     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7033     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7034                                        TemplateId->NumArgs);
7035     TypeResult T = ActOnTemplateIdType(TemplateId->SS,
7036                                        TemplateId->TemplateKWLoc,
7037                                        TemplateId->Template,
7038                                        TemplateId->Name,
7039                                        TemplateId->TemplateNameLoc,
7040                                        TemplateId->LAngleLoc,
7041                                        TemplateArgsPtr,
7042                                        TemplateId->RAngleLoc,
7043                                        /*IsCtorOrDtorName*/true);
7044     if (T.isInvalid() || !T.get()) {
7045       // Recover by assuming we had the right type all along.
7046       DestructedType = ObjectType;
7047     } else
7048       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7049   }
7050 
7051   // If we've performed some kind of recovery, (re-)build the type source
7052   // information.
7053   if (!DestructedType.isNull()) {
7054     if (!DestructedTypeInfo)
7055       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7056                                                   SecondTypeName.StartLocation);
7057     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7058   }
7059 
7060   // Convert the name of the scope type (the type prior to '::') into a type.
7061   TypeSourceInfo *ScopeTypeInfo = nullptr;
7062   QualType ScopeType;
7063   if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7064       FirstTypeName.Identifier) {
7065     if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7066       ParsedType T = getTypeName(*FirstTypeName.Identifier,
7067                                  FirstTypeName.StartLocation,
7068                                  S, &SS, true, false, ObjectTypePtrForLookup,
7069                                  /*IsCtorOrDtorName*/true);
7070       if (!T) {
7071         Diag(FirstTypeName.StartLocation,
7072              diag::err_pseudo_dtor_destructor_non_type)
7073           << FirstTypeName.Identifier << ObjectType;
7074 
7075         if (isSFINAEContext())
7076           return ExprError();
7077 
7078         // Just drop this type. It's unnecessary anyway.
7079         ScopeType = QualType();
7080       } else
7081         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7082     } else {
7083       // Resolve the template-id to a type.
7084       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7085       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7086                                          TemplateId->NumArgs);
7087       TypeResult T = ActOnTemplateIdType(TemplateId->SS,
7088                                          TemplateId->TemplateKWLoc,
7089                                          TemplateId->Template,
7090                                          TemplateId->Name,
7091                                          TemplateId->TemplateNameLoc,
7092                                          TemplateId->LAngleLoc,
7093                                          TemplateArgsPtr,
7094                                          TemplateId->RAngleLoc,
7095                                          /*IsCtorOrDtorName*/true);
7096       if (T.isInvalid() || !T.get()) {
7097         // Recover by dropping this type.
7098         ScopeType = QualType();
7099       } else
7100         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7101     }
7102   }
7103 
7104   if (!ScopeType.isNull() && !ScopeTypeInfo)
7105     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7106                                                   FirstTypeName.StartLocation);
7107 
7108 
7109   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7110                                    ScopeTypeInfo, CCLoc, TildeLoc,
7111                                    Destructed);
7112 }
7113 
7114 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7115                                            SourceLocation OpLoc,
7116                                            tok::TokenKind OpKind,
7117                                            SourceLocation TildeLoc,
7118                                            const DeclSpec& DS) {
7119   QualType ObjectType;
7120   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7121     return ExprError();
7122 
7123   QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7124                                  false);
7125 
7126   TypeLocBuilder TLB;
7127   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7128   DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7129   TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7130   PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7131 
7132   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7133                                    nullptr, SourceLocation(), TildeLoc,
7134                                    Destructed);
7135 }
7136 
7137 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
7138                                         CXXConversionDecl *Method,
7139                                         bool HadMultipleCandidates) {
7140   // Convert the expression to match the conversion function's implicit object
7141   // parameter.
7142   ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7143                                           FoundDecl, Method);
7144   if (Exp.isInvalid())
7145     return true;
7146 
7147   if (Method->getParent()->isLambda() &&
7148       Method->getConversionType()->isBlockPointerType()) {
7149     // This is a lambda coversion to block pointer; check if the argument
7150     // was a LambdaExpr.
7151     Expr *SubE = E;
7152     CastExpr *CE = dyn_cast<CastExpr>(SubE);
7153     if (CE && CE->getCastKind() == CK_NoOp)
7154       SubE = CE->getSubExpr();
7155     SubE = SubE->IgnoreParens();
7156     if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7157       SubE = BE->getSubExpr();
7158     if (isa<LambdaExpr>(SubE)) {
7159       // For the conversion to block pointer on a lambda expression, we
7160       // construct a special BlockLiteral instead; this doesn't really make
7161       // a difference in ARC, but outside of ARC the resulting block literal
7162       // follows the normal lifetime rules for block literals instead of being
7163       // autoreleased.
7164       DiagnosticErrorTrap Trap(Diags);
7165       PushExpressionEvaluationContext(
7166           ExpressionEvaluationContext::PotentiallyEvaluated);
7167       ExprResult BlockExp = BuildBlockForLambdaConversion(
7168           Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
7169       PopExpressionEvaluationContext();
7170 
7171       if (BlockExp.isInvalid())
7172         Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7173       return BlockExp;
7174     }
7175   }
7176 
7177   MemberExpr *ME = new (Context) MemberExpr(
7178       Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
7179       Context.BoundMemberTy, VK_RValue, OK_Ordinary);
7180   if (HadMultipleCandidates)
7181     ME->setHadMultipleCandidates(true);
7182   MarkMemberReferenced(ME);
7183 
7184   QualType ResultType = Method->getReturnType();
7185   ExprValueKind VK = Expr::getValueKindForType(ResultType);
7186   ResultType = ResultType.getNonLValueExprType(Context);
7187 
7188   CXXMemberCallExpr *CE = new (Context) CXXMemberCallExpr(
7189       Context, ME, None, ResultType, VK, Exp.get()->getEndLoc());
7190 
7191   if (CheckFunctionCall(Method, CE,
7192                         Method->getType()->castAs<FunctionProtoType>()))
7193     return ExprError();
7194 
7195   return CE;
7196 }
7197 
7198 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7199                                       SourceLocation RParen) {
7200   // If the operand is an unresolved lookup expression, the expression is ill-
7201   // formed per [over.over]p1, because overloaded function names cannot be used
7202   // without arguments except in explicit contexts.
7203   ExprResult R = CheckPlaceholderExpr(Operand);
7204   if (R.isInvalid())
7205     return R;
7206 
7207   // The operand may have been modified when checking the placeholder type.
7208   Operand = R.get();
7209 
7210   if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
7211     // The expression operand for noexcept is in an unevaluated expression
7212     // context, so side effects could result in unintended consequences.
7213     Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7214   }
7215 
7216   CanThrowResult CanThrow = canThrow(Operand);
7217   return new (Context)
7218       CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
7219 }
7220 
7221 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7222                                    Expr *Operand, SourceLocation RParen) {
7223   return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
7224 }
7225 
7226 static bool IsSpecialDiscardedValue(Expr *E) {
7227   // In C++11, discarded-value expressions of a certain form are special,
7228   // according to [expr]p10:
7229   //   The lvalue-to-rvalue conversion (4.1) is applied only if the
7230   //   expression is an lvalue of volatile-qualified type and it has
7231   //   one of the following forms:
7232   E = E->IgnoreParens();
7233 
7234   //   - id-expression (5.1.1),
7235   if (isa<DeclRefExpr>(E))
7236     return true;
7237 
7238   //   - subscripting (5.2.1),
7239   if (isa<ArraySubscriptExpr>(E))
7240     return true;
7241 
7242   //   - class member access (5.2.5),
7243   if (isa<MemberExpr>(E))
7244     return true;
7245 
7246   //   - indirection (5.3.1),
7247   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7248     if (UO->getOpcode() == UO_Deref)
7249       return true;
7250 
7251   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7252     //   - pointer-to-member operation (5.5),
7253     if (BO->isPtrMemOp())
7254       return true;
7255 
7256     //   - comma expression (5.18) where the right operand is one of the above.
7257     if (BO->getOpcode() == BO_Comma)
7258       return IsSpecialDiscardedValue(BO->getRHS());
7259   }
7260 
7261   //   - conditional expression (5.16) where both the second and the third
7262   //     operands are one of the above, or
7263   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7264     return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7265            IsSpecialDiscardedValue(CO->getFalseExpr());
7266   // The related edge case of "*x ?: *x".
7267   if (BinaryConditionalOperator *BCO =
7268           dyn_cast<BinaryConditionalOperator>(E)) {
7269     if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7270       return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7271              IsSpecialDiscardedValue(BCO->getFalseExpr());
7272   }
7273 
7274   // Objective-C++ extensions to the rule.
7275   if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7276     return true;
7277 
7278   return false;
7279 }
7280 
7281 /// Perform the conversions required for an expression used in a
7282 /// context that ignores the result.
7283 ExprResult Sema::IgnoredValueConversions(Expr *E) {
7284   if (E->hasPlaceholderType()) {
7285     ExprResult result = CheckPlaceholderExpr(E);
7286     if (result.isInvalid()) return E;
7287     E = result.get();
7288   }
7289 
7290   // C99 6.3.2.1:
7291   //   [Except in specific positions,] an lvalue that does not have
7292   //   array type is converted to the value stored in the
7293   //   designated object (and is no longer an lvalue).
7294   if (E->isRValue()) {
7295     // In C, function designators (i.e. expressions of function type)
7296     // are r-values, but we still want to do function-to-pointer decay
7297     // on them.  This is both technically correct and convenient for
7298     // some clients.
7299     if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7300       return DefaultFunctionArrayConversion(E);
7301 
7302     return E;
7303   }
7304 
7305   if (getLangOpts().CPlusPlus)  {
7306     // The C++11 standard defines the notion of a discarded-value expression;
7307     // normally, we don't need to do anything to handle it, but if it is a
7308     // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7309     // conversion.
7310     if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
7311         E->getType().isVolatileQualified() &&
7312         IsSpecialDiscardedValue(E)) {
7313       ExprResult Res = DefaultLvalueConversion(E);
7314       if (Res.isInvalid())
7315         return E;
7316       E = Res.get();
7317     }
7318 
7319     // C++1z:
7320     //   If the expression is a prvalue after this optional conversion, the
7321     //   temporary materialization conversion is applied.
7322     //
7323     // We skip this step: IR generation is able to synthesize the storage for
7324     // itself in the aggregate case, and adding the extra node to the AST is
7325     // just clutter.
7326     // FIXME: We don't emit lifetime markers for the temporaries due to this.
7327     // FIXME: Do any other AST consumers care about this?
7328     return E;
7329   }
7330 
7331   // GCC seems to also exclude expressions of incomplete enum type.
7332   if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7333     if (!T->getDecl()->isComplete()) {
7334       // FIXME: stupid workaround for a codegen bug!
7335       E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
7336       return E;
7337     }
7338   }
7339 
7340   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7341   if (Res.isInvalid())
7342     return E;
7343   E = Res.get();
7344 
7345   if (!E->getType()->isVoidType())
7346     RequireCompleteType(E->getExprLoc(), E->getType(),
7347                         diag::err_incomplete_type);
7348   return E;
7349 }
7350 
7351 // If we can unambiguously determine whether Var can never be used
7352 // in a constant expression, return true.
7353 //  - if the variable and its initializer are non-dependent, then
7354 //    we can unambiguously check if the variable is a constant expression.
7355 //  - if the initializer is not value dependent - we can determine whether
7356 //    it can be used to initialize a constant expression.  If Init can not
7357 //    be used to initialize a constant expression we conclude that Var can
7358 //    never be a constant expression.
7359 //  - FXIME: if the initializer is dependent, we can still do some analysis and
7360 //    identify certain cases unambiguously as non-const by using a Visitor:
7361 //      - such as those that involve odr-use of a ParmVarDecl, involve a new
7362 //        delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7363 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
7364     ASTContext &Context) {
7365   if (isa<ParmVarDecl>(Var)) return true;
7366   const VarDecl *DefVD = nullptr;
7367 
7368   // If there is no initializer - this can not be a constant expression.
7369   if (!Var->getAnyInitializer(DefVD)) return true;
7370   assert(DefVD);
7371   if (DefVD->isWeak()) return false;
7372   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
7373 
7374   Expr *Init = cast<Expr>(Eval->Value);
7375 
7376   if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7377     // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7378     // of value-dependent expressions, and use it here to determine whether the
7379     // initializer is a potential constant expression.
7380     return false;
7381   }
7382 
7383   return !IsVariableAConstantExpression(Var, Context);
7384 }
7385 
7386 /// Check if the current lambda has any potential captures
7387 /// that must be captured by any of its enclosing lambdas that are ready to
7388 /// capture. If there is a lambda that can capture a nested
7389 /// potential-capture, go ahead and do so.  Also, check to see if any
7390 /// variables are uncaptureable or do not involve an odr-use so do not
7391 /// need to be captured.
7392 
7393 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7394     Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7395 
7396   assert(!S.isUnevaluatedContext());
7397   assert(S.CurContext->isDependentContext());
7398 #ifndef NDEBUG
7399   DeclContext *DC = S.CurContext;
7400   while (DC && isa<CapturedDecl>(DC))
7401     DC = DC->getParent();
7402   assert(
7403       CurrentLSI->CallOperator == DC &&
7404       "The current call operator must be synchronized with Sema's CurContext");
7405 #endif // NDEBUG
7406 
7407   const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7408 
7409   // All the potentially captureable variables in the current nested
7410   // lambda (within a generic outer lambda), must be captured by an
7411   // outer lambda that is enclosed within a non-dependent context.
7412   const unsigned NumPotentialCaptures =
7413       CurrentLSI->getNumPotentialVariableCaptures();
7414   for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
7415     Expr *VarExpr = nullptr;
7416     VarDecl *Var = nullptr;
7417     CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
7418     // If the variable is clearly identified as non-odr-used and the full
7419     // expression is not instantiation dependent, only then do we not
7420     // need to check enclosing lambda's for speculative captures.
7421     // For e.g.:
7422     // Even though 'x' is not odr-used, it should be captured.
7423     // int test() {
7424     //   const int x = 10;
7425     //   auto L = [=](auto a) {
7426     //     (void) +x + a;
7427     //   };
7428     // }
7429     if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7430         !IsFullExprInstantiationDependent)
7431       continue;
7432 
7433     // If we have a capture-capable lambda for the variable, go ahead and
7434     // capture the variable in that lambda (and all its enclosing lambdas).
7435     if (const Optional<unsigned> Index =
7436             getStackIndexOfNearestEnclosingCaptureCapableLambda(
7437                 S.FunctionScopes, Var, S)) {
7438       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7439       MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7440                          &FunctionScopeIndexOfCapturableLambda);
7441     }
7442     const bool IsVarNeverAConstantExpression =
7443         VariableCanNeverBeAConstantExpression(Var, S.Context);
7444     if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7445       // This full expression is not instantiation dependent or the variable
7446       // can not be used in a constant expression - which means
7447       // this variable must be odr-used here, so diagnose a
7448       // capture violation early, if the variable is un-captureable.
7449       // This is purely for diagnosing errors early.  Otherwise, this
7450       // error would get diagnosed when the lambda becomes capture ready.
7451       QualType CaptureType, DeclRefType;
7452       SourceLocation ExprLoc = VarExpr->getExprLoc();
7453       if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7454                           /*EllipsisLoc*/ SourceLocation(),
7455                           /*BuildAndDiagnose*/false, CaptureType,
7456                           DeclRefType, nullptr)) {
7457         // We will never be able to capture this variable, and we need
7458         // to be able to in any and all instantiations, so diagnose it.
7459         S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7460                           /*EllipsisLoc*/ SourceLocation(),
7461                           /*BuildAndDiagnose*/true, CaptureType,
7462                           DeclRefType, nullptr);
7463       }
7464     }
7465   }
7466 
7467   // Check if 'this' needs to be captured.
7468   if (CurrentLSI->hasPotentialThisCapture()) {
7469     // If we have a capture-capable lambda for 'this', go ahead and capture
7470     // 'this' in that lambda (and all its enclosing lambdas).
7471     if (const Optional<unsigned> Index =
7472             getStackIndexOfNearestEnclosingCaptureCapableLambda(
7473                 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
7474       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7475       S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7476                             /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7477                             &FunctionScopeIndexOfCapturableLambda);
7478     }
7479   }
7480 
7481   // Reset all the potential captures at the end of each full-expression.
7482   CurrentLSI->clearPotentialCaptures();
7483 }
7484 
7485 static ExprResult attemptRecovery(Sema &SemaRef,
7486                                   const TypoCorrectionConsumer &Consumer,
7487                                   const TypoCorrection &TC) {
7488   LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7489                  Consumer.getLookupResult().getLookupKind());
7490   const CXXScopeSpec *SS = Consumer.getSS();
7491   CXXScopeSpec NewSS;
7492 
7493   // Use an approprate CXXScopeSpec for building the expr.
7494   if (auto *NNS = TC.getCorrectionSpecifier())
7495     NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7496   else if (SS && !TC.WillReplaceSpecifier())
7497     NewSS = *SS;
7498 
7499   if (auto *ND = TC.getFoundDecl()) {
7500     R.setLookupName(ND->getDeclName());
7501     R.addDecl(ND);
7502     if (ND->isCXXClassMember()) {
7503       // Figure out the correct naming class to add to the LookupResult.
7504       CXXRecordDecl *Record = nullptr;
7505       if (auto *NNS = TC.getCorrectionSpecifier())
7506         Record = NNS->getAsType()->getAsCXXRecordDecl();
7507       if (!Record)
7508         Record =
7509             dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7510       if (Record)
7511         R.setNamingClass(Record);
7512 
7513       // Detect and handle the case where the decl might be an implicit
7514       // member.
7515       bool MightBeImplicitMember;
7516       if (!Consumer.isAddressOfOperand())
7517         MightBeImplicitMember = true;
7518       else if (!NewSS.isEmpty())
7519         MightBeImplicitMember = false;
7520       else if (R.isOverloadedResult())
7521         MightBeImplicitMember = false;
7522       else if (R.isUnresolvableResult())
7523         MightBeImplicitMember = true;
7524       else
7525         MightBeImplicitMember = isa<FieldDecl>(ND) ||
7526                                 isa<IndirectFieldDecl>(ND) ||
7527                                 isa<MSPropertyDecl>(ND);
7528 
7529       if (MightBeImplicitMember)
7530         return SemaRef.BuildPossibleImplicitMemberExpr(
7531             NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
7532             /*TemplateArgs*/ nullptr, /*S*/ nullptr);
7533     } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7534       return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7535                                         Ivar->getIdentifier());
7536     }
7537   }
7538 
7539   return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7540                                           /*AcceptInvalidDecl*/ true);
7541 }
7542 
7543 namespace {
7544 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7545   llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7546 
7547 public:
7548   explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7549       : TypoExprs(TypoExprs) {}
7550   bool VisitTypoExpr(TypoExpr *TE) {
7551     TypoExprs.insert(TE);
7552     return true;
7553   }
7554 };
7555 
7556 class TransformTypos : public TreeTransform<TransformTypos> {
7557   typedef TreeTransform<TransformTypos> BaseTransform;
7558 
7559   VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7560                      // process of being initialized.
7561   llvm::function_ref<ExprResult(Expr *)> ExprFilter;
7562   llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
7563   llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
7564   llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
7565 
7566   /// Emit diagnostics for all of the TypoExprs encountered.
7567   /// If the TypoExprs were successfully corrected, then the diagnostics should
7568   /// suggest the corrections. Otherwise the diagnostics will not suggest
7569   /// anything (having been passed an empty TypoCorrection).
7570   void EmitAllDiagnostics() {
7571     for (TypoExpr *TE : TypoExprs) {
7572       auto &State = SemaRef.getTypoExprState(TE);
7573       if (State.DiagHandler) {
7574         TypoCorrection TC = State.Consumer->getCurrentCorrection();
7575         ExprResult Replacement = TransformCache[TE];
7576 
7577         // Extract the NamedDecl from the transformed TypoExpr and add it to the
7578         // TypoCorrection, replacing the existing decls. This ensures the right
7579         // NamedDecl is used in diagnostics e.g. in the case where overload
7580         // resolution was used to select one from several possible decls that
7581         // had been stored in the TypoCorrection.
7582         if (auto *ND = getDeclFromExpr(
7583                 Replacement.isInvalid() ? nullptr : Replacement.get()))
7584           TC.setCorrectionDecl(ND);
7585 
7586         State.DiagHandler(TC);
7587       }
7588       SemaRef.clearDelayedTypo(TE);
7589     }
7590   }
7591 
7592   /// If corrections for the first TypoExpr have been exhausted for a
7593   /// given combination of the other TypoExprs, retry those corrections against
7594   /// the next combination of substitutions for the other TypoExprs by advancing
7595   /// to the next potential correction of the second TypoExpr. For the second
7596   /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7597   /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7598   /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7599   /// TransformCache). Returns true if there is still any untried combinations
7600   /// of corrections.
7601   bool CheckAndAdvanceTypoExprCorrectionStreams() {
7602     for (auto TE : TypoExprs) {
7603       auto &State = SemaRef.getTypoExprState(TE);
7604       TransformCache.erase(TE);
7605       if (!State.Consumer->finished())
7606         return true;
7607       State.Consumer->resetCorrectionStream();
7608     }
7609     return false;
7610   }
7611 
7612   NamedDecl *getDeclFromExpr(Expr *E) {
7613     if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7614       E = OverloadResolution[OE];
7615 
7616     if (!E)
7617       return nullptr;
7618     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
7619       return DRE->getFoundDecl();
7620     if (auto *ME = dyn_cast<MemberExpr>(E))
7621       return ME->getFoundDecl();
7622     // FIXME: Add any other expr types that could be be seen by the delayed typo
7623     // correction TreeTransform for which the corresponding TypoCorrection could
7624     // contain multiple decls.
7625     return nullptr;
7626   }
7627 
7628   ExprResult TryTransform(Expr *E) {
7629     Sema::SFINAETrap Trap(SemaRef);
7630     ExprResult Res = TransformExpr(E);
7631     if (Trap.hasErrorOccurred() || Res.isInvalid())
7632       return ExprError();
7633 
7634     return ExprFilter(Res.get());
7635   }
7636 
7637 public:
7638   TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7639       : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
7640 
7641   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7642                                    MultiExprArg Args,
7643                                    SourceLocation RParenLoc,
7644                                    Expr *ExecConfig = nullptr) {
7645     auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7646                                                  RParenLoc, ExecConfig);
7647     if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
7648       if (Result.isUsable()) {
7649         Expr *ResultCall = Result.get();
7650         if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7651           ResultCall = BE->getSubExpr();
7652         if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7653           OverloadResolution[OE] = CE->getCallee();
7654       }
7655     }
7656     return Result;
7657   }
7658 
7659   ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7660 
7661   ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7662 
7663   ExprResult Transform(Expr *E) {
7664     ExprResult Res;
7665     while (true) {
7666       Res = TryTransform(E);
7667 
7668       // Exit if either the transform was valid or if there were no TypoExprs
7669       // to transform that still have any untried correction candidates..
7670       if (!Res.isInvalid() ||
7671           !CheckAndAdvanceTypoExprCorrectionStreams())
7672         break;
7673     }
7674 
7675     // Ensure none of the TypoExprs have multiple typo correction candidates
7676     // with the same edit length that pass all the checks and filters.
7677     // TODO: Properly handle various permutations of possible corrections when
7678     // there is more than one potentially ambiguous typo correction.
7679     // Also, disable typo correction while attempting the transform when
7680     // handling potentially ambiguous typo corrections as any new TypoExprs will
7681     // have been introduced by the application of one of the correction
7682     // candidates and add little to no value if corrected.
7683     SemaRef.DisableTypoCorrection = true;
7684     while (!AmbiguousTypoExprs.empty()) {
7685       auto TE  = AmbiguousTypoExprs.back();
7686       auto Cached = TransformCache[TE];
7687       auto &State = SemaRef.getTypoExprState(TE);
7688       State.Consumer->saveCurrentPosition();
7689       TransformCache.erase(TE);
7690       if (!TryTransform(E).isInvalid()) {
7691         State.Consumer->resetCorrectionStream();
7692         TransformCache.erase(TE);
7693         Res = ExprError();
7694         break;
7695       }
7696       AmbiguousTypoExprs.remove(TE);
7697       State.Consumer->restoreSavedPosition();
7698       TransformCache[TE] = Cached;
7699     }
7700     SemaRef.DisableTypoCorrection = false;
7701 
7702     // Ensure that all of the TypoExprs within the current Expr have been found.
7703     if (!Res.isUsable())
7704       FindTypoExprs(TypoExprs).TraverseStmt(E);
7705 
7706     EmitAllDiagnostics();
7707 
7708     return Res;
7709   }
7710 
7711   ExprResult TransformTypoExpr(TypoExpr *E) {
7712     // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7713     // cached transformation result if there is one and the TypoExpr isn't the
7714     // first one that was encountered.
7715     auto &CacheEntry = TransformCache[E];
7716     if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7717       return CacheEntry;
7718     }
7719 
7720     auto &State = SemaRef.getTypoExprState(E);
7721     assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7722 
7723     // For the first TypoExpr and an uncached TypoExpr, find the next likely
7724     // typo correction and return it.
7725     while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
7726       if (InitDecl && TC.getFoundDecl() == InitDecl)
7727         continue;
7728       // FIXME: If we would typo-correct to an invalid declaration, it's
7729       // probably best to just suppress all errors from this typo correction.
7730       ExprResult NE = State.RecoveryHandler ?
7731           State.RecoveryHandler(SemaRef, E, TC) :
7732           attemptRecovery(SemaRef, *State.Consumer, TC);
7733       if (!NE.isInvalid()) {
7734         // Check whether there may be a second viable correction with the same
7735         // edit distance; if so, remember this TypoExpr may have an ambiguous
7736         // correction so it can be more thoroughly vetted later.
7737         TypoCorrection Next;
7738         if ((Next = State.Consumer->peekNextCorrection()) &&
7739             Next.getEditDistance(false) == TC.getEditDistance(false)) {
7740           AmbiguousTypoExprs.insert(E);
7741         } else {
7742           AmbiguousTypoExprs.remove(E);
7743         }
7744         assert(!NE.isUnset() &&
7745                "Typo was transformed into a valid-but-null ExprResult");
7746         return CacheEntry = NE;
7747       }
7748     }
7749     return CacheEntry = ExprError();
7750   }
7751 };
7752 }
7753 
7754 ExprResult
7755 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7756                                 llvm::function_ref<ExprResult(Expr *)> Filter) {
7757   // If the current evaluation context indicates there are uncorrected typos
7758   // and the current expression isn't guaranteed to not have typos, try to
7759   // resolve any TypoExpr nodes that might be in the expression.
7760   if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
7761       (E->isTypeDependent() || E->isValueDependent() ||
7762        E->isInstantiationDependent())) {
7763     auto TyposResolved = DelayedTypos.size();
7764     auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
7765     TyposResolved -= DelayedTypos.size();
7766     if (Result.isInvalid() || Result.get() != E) {
7767       ExprEvalContexts.back().NumTypos -= TyposResolved;
7768       return Result;
7769     }
7770     assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
7771   }
7772   return E;
7773 }
7774 
7775 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
7776                                      bool DiscardedValue,
7777                                      bool IsConstexpr) {
7778   ExprResult FullExpr = FE;
7779 
7780   if (!FullExpr.get())
7781     return ExprError();
7782 
7783   if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
7784     return ExprError();
7785 
7786   if (DiscardedValue) {
7787     // Top-level expressions default to 'id' when we're in a debugger.
7788     if (getLangOpts().DebuggerCastResultToId &&
7789         FullExpr.get()->getType() == Context.UnknownAnyTy) {
7790       FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7791       if (FullExpr.isInvalid())
7792         return ExprError();
7793     }
7794 
7795     FullExpr = CheckPlaceholderExpr(FullExpr.get());
7796     if (FullExpr.isInvalid())
7797       return ExprError();
7798 
7799     FullExpr = IgnoredValueConversions(FullExpr.get());
7800     if (FullExpr.isInvalid())
7801       return ExprError();
7802   }
7803 
7804   FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7805   if (FullExpr.isInvalid())
7806     return ExprError();
7807 
7808   CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7809 
7810   // At the end of this full expression (which could be a deeply nested
7811   // lambda), if there is a potential capture within the nested lambda,
7812   // have the outer capture-able lambda try and capture it.
7813   // Consider the following code:
7814   // void f(int, int);
7815   // void f(const int&, double);
7816   // void foo() {
7817   //  const int x = 10, y = 20;
7818   //  auto L = [=](auto a) {
7819   //      auto M = [=](auto b) {
7820   //         f(x, b); <-- requires x to be captured by L and M
7821   //         f(y, a); <-- requires y to be captured by L, but not all Ms
7822   //      };
7823   //   };
7824   // }
7825 
7826   // FIXME: Also consider what happens for something like this that involves
7827   // the gnu-extension statement-expressions or even lambda-init-captures:
7828   //   void f() {
7829   //     const int n = 0;
7830   //     auto L =  [&](auto a) {
7831   //       +n + ({ 0; a; });
7832   //     };
7833   //   }
7834   //
7835   // Here, we see +n, and then the full-expression 0; ends, so we don't
7836   // capture n (and instead remove it from our list of potential captures),
7837   // and then the full-expression +n + ({ 0; }); ends, but it's too late
7838   // for us to see that we need to capture n after all.
7839 
7840   LambdaScopeInfo *const CurrentLSI =
7841       getCurLambda(/*IgnoreCapturedRegions=*/true);
7842   // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7843   // even if CurContext is not a lambda call operator. Refer to that Bug Report
7844   // for an example of the code that might cause this asynchrony.
7845   // By ensuring we are in the context of a lambda's call operator
7846   // we can fix the bug (we only need to check whether we need to capture
7847   // if we are within a lambda's body); but per the comments in that
7848   // PR, a proper fix would entail :
7849   //   "Alternative suggestion:
7850   //   - Add to Sema an integer holding the smallest (outermost) scope
7851   //     index that we are *lexically* within, and save/restore/set to
7852   //     FunctionScopes.size() in InstantiatingTemplate's
7853   //     constructor/destructor.
7854   //  - Teach the handful of places that iterate over FunctionScopes to
7855   //    stop at the outermost enclosing lexical scope."
7856   DeclContext *DC = CurContext;
7857   while (DC && isa<CapturedDecl>(DC))
7858     DC = DC->getParent();
7859   const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7860   if (IsInLambdaDeclContext && CurrentLSI &&
7861       CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7862     CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7863                                                               *this);
7864   return MaybeCreateExprWithCleanups(FullExpr);
7865 }
7866 
7867 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7868   if (!FullStmt) return StmtError();
7869 
7870   return MaybeCreateStmtWithCleanups(FullStmt);
7871 }
7872 
7873 Sema::IfExistsResult
7874 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7875                                    CXXScopeSpec &SS,
7876                                    const DeclarationNameInfo &TargetNameInfo) {
7877   DeclarationName TargetName = TargetNameInfo.getName();
7878   if (!TargetName)
7879     return IER_DoesNotExist;
7880 
7881   // If the name itself is dependent, then the result is dependent.
7882   if (TargetName.isDependentName())
7883     return IER_Dependent;
7884 
7885   // Do the redeclaration lookup in the current scope.
7886   LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7887                  Sema::NotForRedeclaration);
7888   LookupParsedName(R, S, &SS);
7889   R.suppressDiagnostics();
7890 
7891   switch (R.getResultKind()) {
7892   case LookupResult::Found:
7893   case LookupResult::FoundOverloaded:
7894   case LookupResult::FoundUnresolvedValue:
7895   case LookupResult::Ambiguous:
7896     return IER_Exists;
7897 
7898   case LookupResult::NotFound:
7899     return IER_DoesNotExist;
7900 
7901   case LookupResult::NotFoundInCurrentInstantiation:
7902     return IER_Dependent;
7903   }
7904 
7905   llvm_unreachable("Invalid LookupResult Kind!");
7906 }
7907 
7908 Sema::IfExistsResult
7909 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7910                                    bool IsIfExists, CXXScopeSpec &SS,
7911                                    UnqualifiedId &Name) {
7912   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7913 
7914   // Check for an unexpanded parameter pack.
7915   auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7916   if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7917       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
7918     return IER_Error;
7919 
7920   return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7921 }
7922