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