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