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