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