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