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