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