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