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