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