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