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