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