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