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