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