]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp
Upgrade to OpenSSH 7.3p1.
[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->getUnderlyingDecl()))
4225           continue;
4226         // UsingDecl itself is not a constructor
4227         if (isa<UsingDecl>(ND))
4228           continue;
4229         auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4230         if (Constructor->isCopyConstructor(FoundTQs)) {
4231           FoundConstructor = true;
4232           const FunctionProtoType *CPT
4233               = Constructor->getType()->getAs<FunctionProtoType>();
4234           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4235           if (!CPT)
4236             return false;
4237           // TODO: check whether evaluating default arguments can throw.
4238           // For now, we'll be conservative and assume that they can throw.
4239           if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
4240             return false;
4241         }
4242       }
4243
4244       return FoundConstructor;
4245     }
4246     return false;
4247   case UTT_HasNothrowConstructor:
4248     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4249     //   If __has_trivial_constructor (type) is true then the trait is
4250     //   true, else if type is a cv class or union type (or array
4251     //   thereof) with a default constructor that is known not to
4252     //   throw an exception then the trait is true, else it is false.
4253     if (T.isPODType(C) || T->isObjCLifetimeType())
4254       return true;
4255     if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4256       if (RD->hasTrivialDefaultConstructor() &&
4257           !RD->hasNonTrivialDefaultConstructor())
4258         return true;
4259
4260       bool FoundConstructor = false;
4261       for (const auto *ND : Self.LookupConstructors(RD)) {
4262         // FIXME: In C++0x, a constructor template can be a default constructor.
4263         if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4264           continue;
4265         // UsingDecl itself is not a constructor
4266         if (isa<UsingDecl>(ND))
4267           continue;
4268         auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4269         if (Constructor->isDefaultConstructor()) {
4270           FoundConstructor = true;
4271           const FunctionProtoType *CPT
4272               = Constructor->getType()->getAs<FunctionProtoType>();
4273           CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4274           if (!CPT)
4275             return false;
4276           // FIXME: check whether evaluating default arguments can throw.
4277           // For now, we'll be conservative and assume that they can throw.
4278           if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
4279             return false;
4280         }
4281       }
4282       return FoundConstructor;
4283     }
4284     return false;
4285   case UTT_HasVirtualDestructor:
4286     // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4287     //   If type is a class type with a virtual destructor ([class.dtor])
4288     //   then the trait is true, else it is false.
4289     if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4290       if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4291         return Destructor->isVirtual();
4292     return false;
4293
4294     // These type trait expressions are modeled on the specifications for the
4295     // Embarcadero C++0x type trait functions:
4296     //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4297   case UTT_IsCompleteType:
4298     // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4299     //   Returns True if and only if T is a complete type at the point of the
4300     //   function call.
4301     return !T->isIncompleteType();
4302   }
4303 }
4304
4305 /// \brief Determine whether T has a non-trivial Objective-C lifetime in
4306 /// ARC mode.
4307 static bool hasNontrivialObjCLifetime(QualType T) {
4308   switch (T.getObjCLifetime()) {
4309   case Qualifiers::OCL_ExplicitNone:
4310     return false;
4311
4312   case Qualifiers::OCL_Strong:
4313   case Qualifiers::OCL_Weak:
4314   case Qualifiers::OCL_Autoreleasing:
4315     return true;
4316
4317   case Qualifiers::OCL_None:
4318     return T->isObjCLifetimeType();
4319   }
4320
4321   llvm_unreachable("Unknown ObjC lifetime qualifier");
4322 }
4323
4324 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4325                                     QualType RhsT, SourceLocation KeyLoc);
4326
4327 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4328                               ArrayRef<TypeSourceInfo *> Args,
4329                               SourceLocation RParenLoc) {
4330   if (Kind <= UTT_Last)
4331     return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4332
4333   if (Kind <= BTT_Last)
4334     return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4335                                    Args[1]->getType(), RParenLoc);
4336
4337   switch (Kind) {
4338   case clang::TT_IsConstructible:
4339   case clang::TT_IsNothrowConstructible:
4340   case clang::TT_IsTriviallyConstructible: {
4341     // C++11 [meta.unary.prop]:
4342     //   is_trivially_constructible is defined as:
4343     //
4344     //     is_constructible<T, Args...>::value is true and the variable
4345     //     definition for is_constructible, as defined below, is known to call
4346     //     no operation that is not trivial.
4347     //
4348     //   The predicate condition for a template specialization 
4349     //   is_constructible<T, Args...> shall be satisfied if and only if the 
4350     //   following variable definition would be well-formed for some invented 
4351     //   variable t:
4352     //
4353     //     T t(create<Args>()...);
4354     assert(!Args.empty());
4355
4356     // Precondition: T and all types in the parameter pack Args shall be
4357     // complete types, (possibly cv-qualified) void, or arrays of
4358     // unknown bound.
4359     for (const auto *TSI : Args) {
4360       QualType ArgTy = TSI->getType();
4361       if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4362         continue;
4363
4364       if (S.RequireCompleteType(KWLoc, ArgTy, 
4365           diag::err_incomplete_type_used_in_type_trait_expr))
4366         return false;
4367     }
4368
4369     // Make sure the first argument is not incomplete nor a function type.
4370     QualType T = Args[0]->getType();
4371     if (T->isIncompleteType() || T->isFunctionType())
4372       return false;
4373
4374     // Make sure the first argument is not an abstract type.
4375     CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4376     if (RD && RD->isAbstract())
4377       return false;
4378
4379     SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4380     SmallVector<Expr *, 2> ArgExprs;
4381     ArgExprs.reserve(Args.size() - 1);
4382     for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4383       QualType ArgTy = Args[I]->getType();
4384       if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4385         ArgTy = S.Context.getRValueReferenceType(ArgTy);
4386       OpaqueArgExprs.push_back(
4387           OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4388                           ArgTy.getNonLValueExprType(S.Context),
4389                           Expr::getValueKindForType(ArgTy)));
4390     }
4391     for (Expr &E : OpaqueArgExprs)
4392       ArgExprs.push_back(&E);
4393
4394     // Perform the initialization in an unevaluated context within a SFINAE 
4395     // trap at translation unit scope.
4396     EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4397     Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4398     Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4399     InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4400     InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4401                                                                  RParenLoc));
4402     InitializationSequence Init(S, To, InitKind, ArgExprs);
4403     if (Init.Failed())
4404       return false;
4405
4406     ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4407     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4408       return false;
4409
4410     if (Kind == clang::TT_IsConstructible)
4411       return true;
4412
4413     if (Kind == clang::TT_IsNothrowConstructible)
4414       return S.canThrow(Result.get()) == CT_Cannot;
4415
4416     if (Kind == clang::TT_IsTriviallyConstructible) {
4417       // Under Objective-C ARC, if the destination has non-trivial Objective-C
4418       // lifetime, this is a non-trivial construction.
4419       if (S.getLangOpts().ObjCAutoRefCount &&
4420           hasNontrivialObjCLifetime(T.getNonReferenceType()))
4421         return false;
4422
4423       // The initialization succeeded; now make sure there are no non-trivial
4424       // calls.
4425       return !Result.get()->hasNonTrivialCall(S.Context);
4426     }
4427
4428     llvm_unreachable("unhandled type trait");
4429     return false;
4430   }
4431     default: llvm_unreachable("not a TT");
4432   }
4433   
4434   return false;
4435 }
4436
4437 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 
4438                                 ArrayRef<TypeSourceInfo *> Args, 
4439                                 SourceLocation RParenLoc) {
4440   QualType ResultType = Context.getLogicalOperationType();
4441
4442   if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4443                                *this, Kind, KWLoc, Args[0]->getType()))
4444     return ExprError();
4445
4446   bool Dependent = false;
4447   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4448     if (Args[I]->getType()->isDependentType()) {
4449       Dependent = true;
4450       break;
4451     }
4452   }
4453
4454   bool Result = false;
4455   if (!Dependent)
4456     Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4457
4458   return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4459                                RParenLoc, Result);
4460 }
4461
4462 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4463                                 ArrayRef<ParsedType> Args,
4464                                 SourceLocation RParenLoc) {
4465   SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
4466   ConvertedArgs.reserve(Args.size());
4467   
4468   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4469     TypeSourceInfo *TInfo;
4470     QualType T = GetTypeFromParser(Args[I], &TInfo);
4471     if (!TInfo)
4472       TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
4473     
4474     ConvertedArgs.push_back(TInfo);    
4475   }
4476
4477   return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4478 }
4479
4480 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4481                                     QualType RhsT, SourceLocation KeyLoc) {
4482   assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4483          "Cannot evaluate traits of dependent types");
4484
4485   switch(BTT) {
4486   case BTT_IsBaseOf: {
4487     // C++0x [meta.rel]p2
4488     // Base is a base class of Derived without regard to cv-qualifiers or
4489     // Base and Derived are not unions and name the same class type without
4490     // regard to cv-qualifiers.
4491
4492     const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4493     if (!lhsRecord) return false;
4494
4495     const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4496     if (!rhsRecord) return false;
4497
4498     assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4499              == (lhsRecord == rhsRecord));
4500
4501     if (lhsRecord == rhsRecord)
4502       return !lhsRecord->getDecl()->isUnion();
4503
4504     // C++0x [meta.rel]p2:
4505     //   If Base and Derived are class types and are different types
4506     //   (ignoring possible cv-qualifiers) then Derived shall be a
4507     //   complete type.
4508     if (Self.RequireCompleteType(KeyLoc, RhsT, 
4509                           diag::err_incomplete_type_used_in_type_trait_expr))
4510       return false;
4511
4512     return cast<CXXRecordDecl>(rhsRecord->getDecl())
4513       ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4514   }
4515   case BTT_IsSame:
4516     return Self.Context.hasSameType(LhsT, RhsT);
4517   case BTT_TypeCompatible:
4518     return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4519                                            RhsT.getUnqualifiedType());
4520   case BTT_IsConvertible:
4521   case BTT_IsConvertibleTo: {
4522     // C++0x [meta.rel]p4:
4523     //   Given the following function prototype:
4524     //
4525     //     template <class T> 
4526     //       typename add_rvalue_reference<T>::type create();
4527     //
4528     //   the predicate condition for a template specialization 
4529     //   is_convertible<From, To> shall be satisfied if and only if 
4530     //   the return expression in the following code would be 
4531     //   well-formed, including any implicit conversions to the return
4532     //   type of the function:
4533     //
4534     //     To test() { 
4535     //       return create<From>();
4536     //     }
4537     //
4538     //   Access checking is performed as if in a context unrelated to To and 
4539     //   From. Only the validity of the immediate context of the expression 
4540     //   of the return-statement (including conversions to the return type)
4541     //   is considered.
4542     //
4543     // We model the initialization as a copy-initialization of a temporary
4544     // of the appropriate type, which for this expression is identical to the
4545     // return statement (since NRVO doesn't apply).
4546
4547     // Functions aren't allowed to return function or array types.
4548     if (RhsT->isFunctionType() || RhsT->isArrayType())
4549       return false;
4550
4551     // A return statement in a void function must have void type.
4552     if (RhsT->isVoidType())
4553       return LhsT->isVoidType();
4554
4555     // A function definition requires a complete, non-abstract return type.
4556     if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
4557       return false;
4558
4559     // Compute the result of add_rvalue_reference.
4560     if (LhsT->isObjectType() || LhsT->isFunctionType())
4561       LhsT = Self.Context.getRValueReferenceType(LhsT);
4562
4563     // Build a fake source and destination for initialization.
4564     InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
4565     OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4566                          Expr::getValueKindForType(LhsT));
4567     Expr *FromPtr = &From;
4568     InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 
4569                                                            SourceLocation()));
4570     
4571     // Perform the initialization in an unevaluated context within a SFINAE 
4572     // trap at translation unit scope.
4573     EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4574     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4575     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4576     InitializationSequence Init(Self, To, Kind, FromPtr);
4577     if (Init.Failed())
4578       return false;
4579
4580     ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
4581     return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4582   }
4583
4584   case BTT_IsAssignable:
4585   case BTT_IsNothrowAssignable:
4586   case BTT_IsTriviallyAssignable: {
4587     // C++11 [meta.unary.prop]p3:
4588     //   is_trivially_assignable is defined as:
4589     //     is_assignable<T, U>::value is true and the assignment, as defined by
4590     //     is_assignable, is known to call no operation that is not trivial
4591     //
4592     //   is_assignable is defined as:
4593     //     The expression declval<T>() = declval<U>() is well-formed when 
4594     //     treated as an unevaluated operand (Clause 5).
4595     //
4596     //   For both, T and U shall be complete types, (possibly cv-qualified) 
4597     //   void, or arrays of unknown bound.
4598     if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
4599         Self.RequireCompleteType(KeyLoc, LhsT, 
4600           diag::err_incomplete_type_used_in_type_trait_expr))
4601       return false;
4602     if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
4603         Self.RequireCompleteType(KeyLoc, RhsT, 
4604           diag::err_incomplete_type_used_in_type_trait_expr))
4605       return false;
4606
4607     // cv void is never assignable.
4608     if (LhsT->isVoidType() || RhsT->isVoidType())
4609       return false;
4610
4611     // Build expressions that emulate the effect of declval<T>() and 
4612     // declval<U>().
4613     if (LhsT->isObjectType() || LhsT->isFunctionType())
4614       LhsT = Self.Context.getRValueReferenceType(LhsT);
4615     if (RhsT->isObjectType() || RhsT->isFunctionType())
4616       RhsT = Self.Context.getRValueReferenceType(RhsT);
4617     OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4618                         Expr::getValueKindForType(LhsT));
4619     OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4620                         Expr::getValueKindForType(RhsT));
4621     
4622     // Attempt the assignment in an unevaluated context within a SFINAE 
4623     // trap at translation unit scope.
4624     EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4625     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4626     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4627     ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4628                                         &Rhs);
4629     if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4630       return false;
4631
4632     if (BTT == BTT_IsAssignable)
4633       return true;
4634
4635     if (BTT == BTT_IsNothrowAssignable)
4636       return Self.canThrow(Result.get()) == CT_Cannot;
4637
4638     if (BTT == BTT_IsTriviallyAssignable) {
4639       // Under Objective-C ARC, if the destination has non-trivial Objective-C
4640       // lifetime, this is a non-trivial assignment.
4641       if (Self.getLangOpts().ObjCAutoRefCount &&
4642           hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4643         return false;
4644
4645       return !Result.get()->hasNonTrivialCall(Self.Context);
4646     }
4647
4648     llvm_unreachable("unhandled type trait");
4649     return false;
4650   }
4651     default: llvm_unreachable("not a BTT");
4652   }
4653   llvm_unreachable("Unknown type trait or not implemented");
4654 }
4655
4656 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4657                                      SourceLocation KWLoc,
4658                                      ParsedType Ty,
4659                                      Expr* DimExpr,
4660                                      SourceLocation RParen) {
4661   TypeSourceInfo *TSInfo;
4662   QualType T = GetTypeFromParser(Ty, &TSInfo);
4663   if (!TSInfo)
4664     TSInfo = Context.getTrivialTypeSourceInfo(T);
4665
4666   return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4667 }
4668
4669 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4670                                            QualType T, Expr *DimExpr,
4671                                            SourceLocation KeyLoc) {
4672   assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4673
4674   switch(ATT) {
4675   case ATT_ArrayRank:
4676     if (T->isArrayType()) {
4677       unsigned Dim = 0;
4678       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4679         ++Dim;
4680         T = AT->getElementType();
4681       }
4682       return Dim;
4683     }
4684     return 0;
4685
4686   case ATT_ArrayExtent: {
4687     llvm::APSInt Value;
4688     uint64_t Dim;
4689     if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
4690           diag::err_dimension_expr_not_constant_integer,
4691           false).isInvalid())
4692       return 0;
4693     if (Value.isSigned() && Value.isNegative()) {
4694       Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4695         << DimExpr->getSourceRange();
4696       return 0;
4697     }
4698     Dim = Value.getLimitedValue();
4699
4700     if (T->isArrayType()) {
4701       unsigned D = 0;
4702       bool Matched = false;
4703       while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4704         if (Dim == D) {
4705           Matched = true;
4706           break;
4707         }
4708         ++D;
4709         T = AT->getElementType();
4710       }
4711
4712       if (Matched && T->isArrayType()) {
4713         if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4714           return CAT->getSize().getLimitedValue();
4715       }
4716     }
4717     return 0;
4718   }
4719   }
4720   llvm_unreachable("Unknown type trait or not implemented");
4721 }
4722
4723 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4724                                      SourceLocation KWLoc,
4725                                      TypeSourceInfo *TSInfo,
4726                                      Expr* DimExpr,
4727                                      SourceLocation RParen) {
4728   QualType T = TSInfo->getType();
4729
4730   // FIXME: This should likely be tracked as an APInt to remove any host
4731   // assumptions about the width of size_t on the target.
4732   uint64_t Value = 0;
4733   if (!T->isDependentType())
4734     Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4735
4736   // While the specification for these traits from the Embarcadero C++
4737   // compiler's documentation says the return type is 'unsigned int', Clang
4738   // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4739   // compiler, there is no difference. On several other platforms this is an
4740   // important distinction.
4741   return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4742                                           RParen, Context.getSizeType());
4743 }
4744
4745 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
4746                                       SourceLocation KWLoc,
4747                                       Expr *Queried,
4748                                       SourceLocation RParen) {
4749   // If error parsing the expression, ignore.
4750   if (!Queried)
4751     return ExprError();
4752
4753   ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
4754
4755   return Result;
4756 }
4757
4758 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4759   switch (ET) {
4760   case ET_IsLValueExpr: return E->isLValue();
4761   case ET_IsRValueExpr: return E->isRValue();
4762   }
4763   llvm_unreachable("Expression trait not covered by switch");
4764 }
4765
4766 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
4767                                       SourceLocation KWLoc,
4768                                       Expr *Queried,
4769                                       SourceLocation RParen) {
4770   if (Queried->isTypeDependent()) {
4771     // Delay type-checking for type-dependent expressions.
4772   } else if (Queried->getType()->isPlaceholderType()) {
4773     ExprResult PE = CheckPlaceholderExpr(Queried);
4774     if (PE.isInvalid()) return ExprError();
4775     return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
4776   }
4777
4778   bool Value = EvaluateExpressionTrait(ET, Queried);
4779
4780   return new (Context)
4781       ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
4782 }
4783
4784 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
4785                                             ExprValueKind &VK,
4786                                             SourceLocation Loc,
4787                                             bool isIndirect) {
4788   assert(!LHS.get()->getType()->isPlaceholderType() &&
4789          !RHS.get()->getType()->isPlaceholderType() &&
4790          "placeholders should have been weeded out by now");
4791
4792   // The LHS undergoes lvalue conversions if this is ->*.
4793   if (isIndirect) {
4794     LHS = DefaultLvalueConversion(LHS.get());
4795     if (LHS.isInvalid()) return QualType();
4796   }
4797
4798   // The RHS always undergoes lvalue conversions.
4799   RHS = DefaultLvalueConversion(RHS.get());
4800   if (RHS.isInvalid()) return QualType();
4801
4802   const char *OpSpelling = isIndirect ? "->*" : ".*";
4803   // C++ 5.5p2
4804   //   The binary operator .* [p3: ->*] binds its second operand, which shall
4805   //   be of type "pointer to member of T" (where T is a completely-defined
4806   //   class type) [...]
4807   QualType RHSType = RHS.get()->getType();
4808   const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
4809   if (!MemPtr) {
4810     Diag(Loc, diag::err_bad_memptr_rhs)
4811       << OpSpelling << RHSType << RHS.get()->getSourceRange();
4812     return QualType();
4813   }
4814
4815   QualType Class(MemPtr->getClass(), 0);
4816
4817   // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4818   // member pointer points must be completely-defined. However, there is no
4819   // reason for this semantic distinction, and the rule is not enforced by
4820   // other compilers. Therefore, we do not check this property, as it is
4821   // likely to be considered a defect.
4822
4823   // C++ 5.5p2
4824   //   [...] to its first operand, which shall be of class T or of a class of
4825   //   which T is an unambiguous and accessible base class. [p3: a pointer to
4826   //   such a class]
4827   QualType LHSType = LHS.get()->getType();
4828   if (isIndirect) {
4829     if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4830       LHSType = Ptr->getPointeeType();
4831     else {
4832       Diag(Loc, diag::err_bad_memptr_lhs)
4833         << OpSpelling << 1 << LHSType
4834         << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
4835       return QualType();
4836     }
4837   }
4838
4839   if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
4840     // If we want to check the hierarchy, we need a complete type.
4841     if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4842                             OpSpelling, (int)isIndirect)) {
4843       return QualType();
4844     }
4845
4846     if (!IsDerivedFrom(Loc, LHSType, Class)) {
4847       Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
4848         << (int)isIndirect << LHS.get()->getType();
4849       return QualType();
4850     }
4851
4852     CXXCastPath BasePath;
4853     if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
4854                                      SourceRange(LHS.get()->getLocStart(),
4855                                                  RHS.get()->getLocEnd()),
4856                                      &BasePath))
4857       return QualType();
4858
4859     // Cast LHS to type of use.
4860     QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
4861     ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
4862     LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
4863                             &BasePath);
4864   }
4865
4866   if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
4867     // Diagnose use of pointer-to-member type which when used as
4868     // the functional cast in a pointer-to-member expression.
4869     Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4870      return QualType();
4871   }
4872
4873   // C++ 5.5p2
4874   //   The result is an object or a function of the type specified by the
4875   //   second operand.
4876   // The cv qualifiers are the union of those in the pointer and the left side,
4877   // in accordance with 5.5p5 and 5.2.5.
4878   QualType Result = MemPtr->getPointeeType();
4879   Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
4880
4881   // C++0x [expr.mptr.oper]p6:
4882   //   In a .* expression whose object expression is an rvalue, the program is
4883   //   ill-formed if the second operand is a pointer to member function with
4884   //   ref-qualifier &. In a ->* expression or in a .* expression whose object
4885   //   expression is an lvalue, the program is ill-formed if the second operand
4886   //   is a pointer to member function with ref-qualifier &&.
4887   if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4888     switch (Proto->getRefQualifier()) {
4889     case RQ_None:
4890       // Do nothing
4891       break;
4892
4893     case RQ_LValue:
4894       if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
4895         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4896           << RHSType << 1 << LHS.get()->getSourceRange();
4897       break;
4898
4899     case RQ_RValue:
4900       if (isIndirect || !LHS.get()->Classify(Context).isRValue())
4901         Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4902           << RHSType << 0 << LHS.get()->getSourceRange();
4903       break;
4904     }
4905   }
4906
4907   // C++ [expr.mptr.oper]p6:
4908   //   The result of a .* expression whose second operand is a pointer
4909   //   to a data member is of the same value category as its
4910   //   first operand. The result of a .* expression whose second
4911   //   operand is a pointer to a member function is a prvalue. The
4912   //   result of an ->* expression is an lvalue if its second operand
4913   //   is a pointer to data member and a prvalue otherwise.
4914   if (Result->isFunctionType()) {
4915     VK = VK_RValue;
4916     return Context.BoundMemberTy;
4917   } else if (isIndirect) {
4918     VK = VK_LValue;
4919   } else {
4920     VK = LHS.get()->getValueKind();
4921   }
4922
4923   return Result;
4924 }
4925
4926 /// \brief Try to convert a type to another according to C++11 5.16p3.
4927 ///
4928 /// This is part of the parameter validation for the ? operator. If either
4929 /// value operand is a class type, the two operands are attempted to be
4930 /// converted to each other. This function does the conversion in one direction.
4931 /// It returns true if the program is ill-formed and has already been diagnosed
4932 /// as such.
4933 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4934                                 SourceLocation QuestionLoc,
4935                                 bool &HaveConversion,
4936                                 QualType &ToType) {
4937   HaveConversion = false;
4938   ToType = To->getType();
4939
4940   InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
4941                                                            SourceLocation());
4942   // C++11 5.16p3
4943   //   The process for determining whether an operand expression E1 of type T1
4944   //   can be converted to match an operand expression E2 of type T2 is defined
4945   //   as follows:
4946   //   -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
4947   //      implicitly converted to type "lvalue reference to T2", subject to the
4948   //      constraint that in the conversion the reference must bind directly to
4949   //      an lvalue.
4950   //   -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
4951   //      implicitly conveted to the type "rvalue reference to R2", subject to
4952   //      the constraint that the reference must bind directly.
4953   if (To->isLValue() || To->isXValue()) {
4954     QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
4955                                 : Self.Context.getRValueReferenceType(ToType);
4956
4957     InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4958
4959     InitializationSequence InitSeq(Self, Entity, Kind, From);
4960     if (InitSeq.isDirectReferenceBinding()) {
4961       ToType = T;
4962       HaveConversion = true;
4963       return false;
4964     }
4965
4966     if (InitSeq.isAmbiguous())
4967       return InitSeq.Diagnose(Self, Entity, Kind, From);
4968   }
4969
4970   //   -- If E2 is an rvalue, or if the conversion above cannot be done:
4971   //      -- if E1 and E2 have class type, and the underlying class types are
4972   //         the same or one is a base class of the other:
4973   QualType FTy = From->getType();
4974   QualType TTy = To->getType();
4975   const RecordType *FRec = FTy->getAs<RecordType>();
4976   const RecordType *TRec = TTy->getAs<RecordType>();
4977   bool FDerivedFromT = FRec && TRec && FRec != TRec &&
4978                        Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
4979   if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
4980                        Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
4981     //         E1 can be converted to match E2 if the class of T2 is the
4982     //         same type as, or a base class of, the class of T1, and
4983     //         [cv2 > cv1].
4984     if (FRec == TRec || FDerivedFromT) {
4985       if (TTy.isAtLeastAsQualifiedAs(FTy)) {
4986         InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4987         InitializationSequence InitSeq(Self, Entity, Kind, From);
4988         if (InitSeq) {
4989           HaveConversion = true;
4990           return false;
4991         }
4992
4993         if (InitSeq.isAmbiguous())
4994           return InitSeq.Diagnose(Self, Entity, Kind, From);
4995       }
4996     }
4997
4998     return false;
4999   }
5000
5001   //     -- Otherwise: E1 can be converted to match E2 if E1 can be
5002   //        implicitly converted to the type that expression E2 would have
5003   //        if E2 were converted to an rvalue (or the type it has, if E2 is
5004   //        an rvalue).
5005   //
5006   // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5007   // to the array-to-pointer or function-to-pointer conversions.
5008   if (!TTy->getAs<TagType>())
5009     TTy = TTy.getUnqualifiedType();
5010
5011   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5012   InitializationSequence InitSeq(Self, Entity, Kind, From);
5013   HaveConversion = !InitSeq.Failed();
5014   ToType = TTy;
5015   if (InitSeq.isAmbiguous())
5016     return InitSeq.Diagnose(Self, Entity, Kind, From);
5017
5018   return false;
5019 }
5020
5021 /// \brief Try to find a common type for two according to C++0x 5.16p5.
5022 ///
5023 /// This is part of the parameter validation for the ? operator. If either
5024 /// value operand is a class type, overload resolution is used to find a
5025 /// conversion to a common type.
5026 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5027                                     SourceLocation QuestionLoc) {
5028   Expr *Args[2] = { LHS.get(), RHS.get() };
5029   OverloadCandidateSet CandidateSet(QuestionLoc,
5030                                     OverloadCandidateSet::CSK_Operator);
5031   Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5032                                     CandidateSet);
5033
5034   OverloadCandidateSet::iterator Best;
5035   switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5036     case OR_Success: {
5037       // We found a match. Perform the conversions on the arguments and move on.
5038       ExprResult LHSRes =
5039         Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5040                                        Best->Conversions[0], Sema::AA_Converting);
5041       if (LHSRes.isInvalid())
5042         break;
5043       LHS = LHSRes;
5044
5045       ExprResult RHSRes =
5046         Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5047                                        Best->Conversions[1], Sema::AA_Converting);
5048       if (RHSRes.isInvalid())
5049         break;
5050       RHS = RHSRes;
5051       if (Best->Function)
5052         Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5053       return false;
5054     }
5055     
5056     case OR_No_Viable_Function:
5057
5058       // Emit a better diagnostic if one of the expressions is a null pointer
5059       // constant and the other is a pointer type. In this case, the user most
5060       // likely forgot to take the address of the other expression.
5061       if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5062         return true;
5063
5064       Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5065         << LHS.get()->getType() << RHS.get()->getType()
5066         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5067       return true;
5068
5069     case OR_Ambiguous:
5070       Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5071         << LHS.get()->getType() << RHS.get()->getType()
5072         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5073       // FIXME: Print the possible common types by printing the return types of
5074       // the viable candidates.
5075       break;
5076
5077     case OR_Deleted:
5078       llvm_unreachable("Conditional operator has only built-in overloads");
5079   }
5080   return true;
5081 }
5082
5083 /// \brief Perform an "extended" implicit conversion as returned by
5084 /// TryClassUnification.
5085 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5086   InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5087   InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
5088                                                            SourceLocation());
5089   Expr *Arg = E.get();
5090   InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5091   ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5092   if (Result.isInvalid())
5093     return true;
5094
5095   E = Result;
5096   return false;
5097 }
5098
5099 /// \brief Check the operands of ?: under C++ semantics.
5100 ///
5101 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5102 /// extension. In this case, LHS == Cond. (But they're not aliases.)
5103 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5104                                            ExprResult &RHS, ExprValueKind &VK,
5105                                            ExprObjectKind &OK,
5106                                            SourceLocation QuestionLoc) {
5107   // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5108   // interface pointers.
5109
5110   // C++11 [expr.cond]p1
5111   //   The first expression is contextually converted to bool.
5112   if (!Cond.get()->isTypeDependent()) {
5113     ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5114     if (CondRes.isInvalid())
5115       return QualType();
5116     Cond = CondRes;
5117   }
5118
5119   // Assume r-value.
5120   VK = VK_RValue;
5121   OK = OK_Ordinary;
5122
5123   // Either of the arguments dependent?
5124   if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5125     return Context.DependentTy;
5126
5127   // C++11 [expr.cond]p2
5128   //   If either the second or the third operand has type (cv) void, ...
5129   QualType LTy = LHS.get()->getType();
5130   QualType RTy = RHS.get()->getType();
5131   bool LVoid = LTy->isVoidType();
5132   bool RVoid = RTy->isVoidType();
5133   if (LVoid || RVoid) {
5134     //   ... one of the following shall hold:
5135     //   -- The second or the third operand (but not both) is a (possibly
5136     //      parenthesized) throw-expression; the result is of the type
5137     //      and value category of the other.
5138     bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5139     bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5140     if (LThrow != RThrow) {
5141       Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5142       VK = NonThrow->getValueKind();
5143       // DR (no number yet): the result is a bit-field if the
5144       // non-throw-expression operand is a bit-field.
5145       OK = NonThrow->getObjectKind();
5146       return NonThrow->getType();
5147     }
5148
5149     //   -- Both the second and third operands have type void; the result is of
5150     //      type void and is a prvalue.
5151     if (LVoid && RVoid)
5152       return Context.VoidTy;
5153
5154     // Neither holds, error.
5155     Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5156       << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5157       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5158     return QualType();
5159   }
5160
5161   // Neither is void.
5162
5163   // C++11 [expr.cond]p3
5164   //   Otherwise, if the second and third operand have different types, and
5165   //   either has (cv) class type [...] an attempt is made to convert each of
5166   //   those operands to the type of the other.
5167   if (!Context.hasSameType(LTy, RTy) &&
5168       (LTy->isRecordType() || RTy->isRecordType())) {
5169     // These return true if a single direction is already ambiguous.
5170     QualType L2RType, R2LType;
5171     bool HaveL2R, HaveR2L;
5172     if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5173       return QualType();
5174     if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5175       return QualType();
5176
5177     //   If both can be converted, [...] the program is ill-formed.
5178     if (HaveL2R && HaveR2L) {
5179       Diag(QuestionLoc, diag::err_conditional_ambiguous)
5180         << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5181       return QualType();
5182     }
5183
5184     //   If exactly one conversion is possible, that conversion is applied to
5185     //   the chosen operand and the converted operands are used in place of the
5186     //   original operands for the remainder of this section.
5187     if (HaveL2R) {
5188       if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5189         return QualType();
5190       LTy = LHS.get()->getType();
5191     } else if (HaveR2L) {
5192       if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5193         return QualType();
5194       RTy = RHS.get()->getType();
5195     }
5196   }
5197
5198   // C++11 [expr.cond]p3
5199   //   if both are glvalues of the same value category and the same type except
5200   //   for cv-qualification, an attempt is made to convert each of those
5201   //   operands to the type of the other.
5202   ExprValueKind LVK = LHS.get()->getValueKind();
5203   ExprValueKind RVK = RHS.get()->getValueKind();
5204   if (!Context.hasSameType(LTy, RTy) &&
5205       Context.hasSameUnqualifiedType(LTy, RTy) &&
5206       LVK == RVK && LVK != VK_RValue) {
5207     // Since the unqualified types are reference-related and we require the
5208     // result to be as if a reference bound directly, the only conversion
5209     // we can perform is to add cv-qualifiers.
5210     Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
5211     Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
5212     if (RCVR.isStrictSupersetOf(LCVR)) {
5213       LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5214       LTy = LHS.get()->getType();
5215     }
5216     else if (LCVR.isStrictSupersetOf(RCVR)) {
5217       RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5218       RTy = RHS.get()->getType();
5219     }
5220   }
5221
5222   // C++11 [expr.cond]p4
5223   //   If the second and third operands are glvalues of the same value
5224   //   category and have the same type, the result is of that type and
5225   //   value category and it is a bit-field if the second or the third
5226   //   operand is a bit-field, or if both are bit-fields.
5227   // We only extend this to bitfields, not to the crazy other kinds of
5228   // l-values.
5229   bool Same = Context.hasSameType(LTy, RTy);
5230   if (Same && LVK == RVK && LVK != VK_RValue &&
5231       LHS.get()->isOrdinaryOrBitFieldObject() &&
5232       RHS.get()->isOrdinaryOrBitFieldObject()) {
5233     VK = LHS.get()->getValueKind();
5234     if (LHS.get()->getObjectKind() == OK_BitField ||
5235         RHS.get()->getObjectKind() == OK_BitField)
5236       OK = OK_BitField;
5237     return LTy;
5238   }
5239
5240   // C++11 [expr.cond]p5
5241   //   Otherwise, the result is a prvalue. If the second and third operands
5242   //   do not have the same type, and either has (cv) class type, ...
5243   if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5244     //   ... overload resolution is used to determine the conversions (if any)
5245     //   to be applied to the operands. If the overload resolution fails, the
5246     //   program is ill-formed.
5247     if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5248       return QualType();
5249   }
5250
5251   // C++11 [expr.cond]p6
5252   //   Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5253   //   conversions are performed on the second and third operands.
5254   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5255   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5256   if (LHS.isInvalid() || RHS.isInvalid())
5257     return QualType();
5258   LTy = LHS.get()->getType();
5259   RTy = RHS.get()->getType();
5260
5261   //   After those conversions, one of the following shall hold:
5262   //   -- The second and third operands have the same type; the result
5263   //      is of that type. If the operands have class type, the result
5264   //      is a prvalue temporary of the result type, which is
5265   //      copy-initialized from either the second operand or the third
5266   //      operand depending on the value of the first operand.
5267   if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5268     if (LTy->isRecordType()) {
5269       // The operands have class type. Make a temporary copy.
5270       if (RequireNonAbstractType(QuestionLoc, LTy,
5271                                  diag::err_allocation_of_abstract_type))
5272         return QualType();
5273       InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
5274
5275       ExprResult LHSCopy = PerformCopyInitialization(Entity,
5276                                                      SourceLocation(),
5277                                                      LHS);
5278       if (LHSCopy.isInvalid())
5279         return QualType();
5280
5281       ExprResult RHSCopy = PerformCopyInitialization(Entity,
5282                                                      SourceLocation(),
5283                                                      RHS);
5284       if (RHSCopy.isInvalid())
5285         return QualType();
5286
5287       LHS = LHSCopy;
5288       RHS = RHSCopy;
5289     }
5290
5291     return LTy;
5292   }
5293
5294   // Extension: conditional operator involving vector types.
5295   if (LTy->isVectorType() || RTy->isVectorType())
5296     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5297                                /*AllowBothBool*/true,
5298                                /*AllowBoolConversions*/false);
5299
5300   //   -- The second and third operands have arithmetic or enumeration type;
5301   //      the usual arithmetic conversions are performed to bring them to a
5302   //      common type, and the result is of that type.
5303   if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5304     QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5305     if (LHS.isInvalid() || RHS.isInvalid())
5306       return QualType();
5307     if (ResTy.isNull()) {
5308       Diag(QuestionLoc,
5309            diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5310         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5311       return QualType();
5312     }
5313
5314     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5315     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5316
5317     return ResTy;
5318   }
5319
5320   //   -- The second and third operands have pointer type, or one has pointer
5321   //      type and the other is a null pointer constant, or both are null
5322   //      pointer constants, at least one of which is non-integral; pointer
5323   //      conversions and qualification conversions are performed to bring them
5324   //      to their composite pointer type. The result is of the composite
5325   //      pointer type.
5326   //   -- The second and third operands have pointer to member type, or one has
5327   //      pointer to member type and the other is a null pointer constant;
5328   //      pointer to member conversions and qualification conversions are
5329   //      performed to bring them to a common type, whose cv-qualification
5330   //      shall match the cv-qualification of either the second or the third
5331   //      operand. The result is of the common type.
5332   bool NonStandardCompositeType = false;
5333   QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
5334                                  isSFINAEContext() ? nullptr
5335                                                    : &NonStandardCompositeType);
5336   if (!Composite.isNull()) {
5337     if (NonStandardCompositeType)
5338       Diag(QuestionLoc,
5339            diag::ext_typecheck_cond_incompatible_operands_nonstandard)
5340         << LTy << RTy << Composite
5341         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5342
5343     return Composite;
5344   }
5345
5346   // Similarly, attempt to find composite type of two objective-c pointers.
5347   Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5348   if (!Composite.isNull())
5349     return Composite;
5350
5351   // Check if we are using a null with a non-pointer type.
5352   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5353     return QualType();
5354
5355   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5356     << LHS.get()->getType() << RHS.get()->getType()
5357     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5358   return QualType();
5359 }
5360
5361 /// \brief Find a merged pointer type and convert the two expressions to it.
5362 ///
5363 /// This finds the composite pointer type (or member pointer type) for @p E1
5364 /// and @p E2 according to C++11 5.9p2. It converts both expressions to this
5365 /// type and returns it.
5366 /// It does not emit diagnostics.
5367 ///
5368 /// \param Loc The location of the operator requiring these two expressions to
5369 /// be converted to the composite pointer type.
5370 ///
5371 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
5372 /// a non-standard (but still sane) composite type to which both expressions
5373 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
5374 /// will be set true.
5375 QualType Sema::FindCompositePointerType(SourceLocation Loc,
5376                                         Expr *&E1, Expr *&E2,
5377                                         bool *NonStandardCompositeType) {
5378   if (NonStandardCompositeType)
5379     *NonStandardCompositeType = false;
5380
5381   assert(getLangOpts().CPlusPlus && "This function assumes C++");
5382   QualType T1 = E1->getType(), T2 = E2->getType();
5383
5384   // C++11 5.9p2
5385   //   Pointer conversions and qualification conversions are performed on
5386   //   pointer operands to bring them to their composite pointer type. If
5387   //   one operand is a null pointer constant, the composite pointer type is
5388   //   std::nullptr_t if the other operand is also a null pointer constant or,
5389   //   if the other operand is a pointer, the type of the other operand.
5390   if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
5391       !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
5392     if (T1->isNullPtrType() &&
5393         E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5394       E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
5395       return T1;
5396     }
5397     if (T2->isNullPtrType() &&
5398         E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5399       E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
5400       return T2;
5401     }
5402     return QualType();
5403   }
5404
5405   if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5406     if (T2->isMemberPointerType())
5407       E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
5408     else
5409       E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
5410     return T2;
5411   }
5412   if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5413     if (T1->isMemberPointerType())
5414       E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
5415     else
5416       E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
5417     return T1;
5418   }
5419
5420   // Now both have to be pointers or member pointers.
5421   if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
5422       (!T2->isPointerType() && !T2->isMemberPointerType()))
5423     return QualType();
5424
5425   //   Otherwise, of one of the operands has type "pointer to cv1 void," then
5426   //   the other has type "pointer to cv2 T" and the composite pointer type is
5427   //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
5428   //   Otherwise, the composite pointer type is a pointer type similar to the
5429   //   type of one of the operands, with a cv-qualification signature that is
5430   //   the union of the cv-qualification signatures of the operand types.
5431   // In practice, the first part here is redundant; it's subsumed by the second.
5432   // What we do here is, we build the two possible composite types, and try the
5433   // conversions in both directions. If only one works, or if the two composite
5434   // types are the same, we have succeeded.
5435   // FIXME: extended qualifiers?
5436   typedef SmallVector<unsigned, 4> QualifierVector;
5437   QualifierVector QualifierUnion;
5438   typedef SmallVector<std::pair<const Type *, const Type *>, 4>
5439       ContainingClassVector;
5440   ContainingClassVector MemberOfClass;
5441   QualType Composite1 = Context.getCanonicalType(T1),
5442            Composite2 = Context.getCanonicalType(T2);
5443   unsigned NeedConstBefore = 0;
5444   do {
5445     const PointerType *Ptr1, *Ptr2;
5446     if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5447         (Ptr2 = Composite2->getAs<PointerType>())) {
5448       Composite1 = Ptr1->getPointeeType();
5449       Composite2 = Ptr2->getPointeeType();
5450
5451       // If we're allowed to create a non-standard composite type, keep track
5452       // of where we need to fill in additional 'const' qualifiers.
5453       if (NonStandardCompositeType &&
5454           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5455         NeedConstBefore = QualifierUnion.size();
5456
5457       QualifierUnion.push_back(
5458                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5459       MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
5460       continue;
5461     }
5462
5463     const MemberPointerType *MemPtr1, *MemPtr2;
5464     if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5465         (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5466       Composite1 = MemPtr1->getPointeeType();
5467       Composite2 = MemPtr2->getPointeeType();
5468
5469       // If we're allowed to create a non-standard composite type, keep track
5470       // of where we need to fill in additional 'const' qualifiers.
5471       if (NonStandardCompositeType &&
5472           Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5473         NeedConstBefore = QualifierUnion.size();
5474
5475       QualifierUnion.push_back(
5476                  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5477       MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5478                                              MemPtr2->getClass()));
5479       continue;
5480     }
5481
5482     // FIXME: block pointer types?
5483
5484     // Cannot unwrap any more types.
5485     break;
5486   } while (true);
5487
5488   if (NeedConstBefore && NonStandardCompositeType) {
5489     // Extension: Add 'const' to qualifiers that come before the first qualifier
5490     // mismatch, so that our (non-standard!) composite type meets the
5491     // requirements of C++ [conv.qual]p4 bullet 3.
5492     for (unsigned I = 0; I != NeedConstBefore; ++I) {
5493       if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
5494         QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
5495         *NonStandardCompositeType = true;
5496       }
5497     }
5498   }
5499
5500   // Rewrap the composites as pointers or member pointers with the union CVRs.
5501   ContainingClassVector::reverse_iterator MOC
5502     = MemberOfClass.rbegin();
5503   for (QualifierVector::reverse_iterator
5504          I = QualifierUnion.rbegin(),
5505          E = QualifierUnion.rend();
5506        I != E; (void)++I, ++MOC) {
5507     Qualifiers Quals = Qualifiers::fromCVRMask(*I);
5508     if (MOC->first && MOC->second) {
5509       // Rebuild member pointer type
5510       Composite1 = Context.getMemberPointerType(
5511                                     Context.getQualifiedType(Composite1, Quals),
5512                                     MOC->first);
5513       Composite2 = Context.getMemberPointerType(
5514                                     Context.getQualifiedType(Composite2, Quals),
5515                                     MOC->second);
5516     } else {
5517       // Rebuild pointer type
5518       Composite1
5519         = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5520       Composite2
5521         = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
5522     }
5523   }
5524
5525   // Try to convert to the first composite pointer type.
5526   InitializedEntity Entity1
5527     = InitializedEntity::InitializeTemporary(Composite1);
5528   InitializationKind Kind
5529     = InitializationKind::CreateCopy(Loc, SourceLocation());
5530   InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
5531   InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
5532
5533   if (E1ToC1 && E2ToC1) {
5534     // Conversion to Composite1 is viable.
5535     if (!Context.hasSameType(Composite1, Composite2)) {
5536       // Composite2 is a different type from Composite1. Check whether
5537       // Composite2 is also viable.
5538       InitializedEntity Entity2
5539         = InitializedEntity::InitializeTemporary(Composite2);
5540       InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5541       InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
5542       if (E1ToC2 && E2ToC2) {
5543         // Both Composite1 and Composite2 are viable and are different;
5544         // this is an ambiguity.
5545         return QualType();
5546       }
5547     }
5548
5549     // Convert E1 to Composite1
5550     ExprResult E1Result
5551       = E1ToC1.Perform(*this, Entity1, Kind, E1);
5552     if (E1Result.isInvalid())
5553       return QualType();
5554     E1 = E1Result.getAs<Expr>();
5555
5556     // Convert E2 to Composite1
5557     ExprResult E2Result
5558       = E2ToC1.Perform(*this, Entity1, Kind, E2);
5559     if (E2Result.isInvalid())
5560       return QualType();
5561     E2 = E2Result.getAs<Expr>();
5562
5563     return Composite1;
5564   }
5565
5566   // Check whether Composite2 is viable.
5567   InitializedEntity Entity2
5568     = InitializedEntity::InitializeTemporary(Composite2);
5569   InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5570   InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
5571   if (!E1ToC2 || !E2ToC2)
5572     return QualType();
5573
5574   // Convert E1 to Composite2
5575   ExprResult E1Result
5576     = E1ToC2.Perform(*this, Entity2, Kind, E1);
5577   if (E1Result.isInvalid())
5578     return QualType();
5579   E1 = E1Result.getAs<Expr>();
5580
5581   // Convert E2 to Composite2
5582   ExprResult E2Result
5583     = E2ToC2.Perform(*this, Entity2, Kind, E2);
5584   if (E2Result.isInvalid())
5585     return QualType();
5586   E2 = E2Result.getAs<Expr>();
5587
5588   return Composite2;
5589 }
5590
5591 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
5592   if (!E)
5593     return ExprError();
5594
5595   assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5596
5597   // If the result is a glvalue, we shouldn't bind it.
5598   if (!E->isRValue())
5599     return E;
5600
5601   // In ARC, calls that return a retainable type can return retained,
5602   // in which case we have to insert a consuming cast.
5603   if (getLangOpts().ObjCAutoRefCount &&
5604       E->getType()->isObjCRetainableType()) {
5605
5606     bool ReturnsRetained;
5607
5608     // For actual calls, we compute this by examining the type of the
5609     // called value.
5610     if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5611       Expr *Callee = Call->getCallee()->IgnoreParens();
5612       QualType T = Callee->getType();
5613
5614       if (T == Context.BoundMemberTy) {
5615         // Handle pointer-to-members.
5616         if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5617           T = BinOp->getRHS()->getType();
5618         else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5619           T = Mem->getMemberDecl()->getType();
5620       }
5621       
5622       if (const PointerType *Ptr = T->getAs<PointerType>())
5623         T = Ptr->getPointeeType();
5624       else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5625         T = Ptr->getPointeeType();
5626       else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5627         T = MemPtr->getPointeeType();
5628       
5629       const FunctionType *FTy = T->getAs<FunctionType>();
5630       assert(FTy && "call to value not of function type?");
5631       ReturnsRetained = FTy->getExtInfo().getProducesResult();
5632
5633     // ActOnStmtExpr arranges things so that StmtExprs of retainable
5634     // type always produce a +1 object.
5635     } else if (isa<StmtExpr>(E)) {
5636       ReturnsRetained = true;
5637
5638     // We hit this case with the lambda conversion-to-block optimization;
5639     // we don't want any extra casts here.
5640     } else if (isa<CastExpr>(E) &&
5641                isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
5642       return E;
5643
5644     // For message sends and property references, we try to find an
5645     // actual method.  FIXME: we should infer retention by selector in
5646     // cases where we don't have an actual method.
5647     } else {
5648       ObjCMethodDecl *D = nullptr;
5649       if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5650         D = Send->getMethodDecl();
5651       } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5652         D = BoxedExpr->getBoxingMethod();
5653       } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5654         D = ArrayLit->getArrayWithObjectsMethod();
5655       } else if (ObjCDictionaryLiteral *DictLit
5656                                         = dyn_cast<ObjCDictionaryLiteral>(E)) {
5657         D = DictLit->getDictWithObjectsMethod();
5658       }
5659
5660       ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
5661
5662       // Don't do reclaims on performSelector calls; despite their
5663       // return type, the invoked method doesn't necessarily actually
5664       // return an object.
5665       if (!ReturnsRetained &&
5666           D && D->getMethodFamily() == OMF_performSelector)
5667         return E;
5668     }
5669
5670     // Don't reclaim an object of Class type.
5671     if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
5672       return E;
5673
5674     Cleanup.setExprNeedsCleanups(true);
5675
5676     CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
5677                                    : CK_ARCReclaimReturnedObject);
5678     return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
5679                                     VK_RValue);
5680   }
5681
5682   if (!getLangOpts().CPlusPlus)
5683     return E;
5684
5685   // Search for the base element type (cf. ASTContext::getBaseElementType) with
5686   // a fast path for the common case that the type is directly a RecordType.
5687   const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
5688   const RecordType *RT = nullptr;
5689   while (!RT) {
5690     switch (T->getTypeClass()) {
5691     case Type::Record:
5692       RT = cast<RecordType>(T);
5693       break;
5694     case Type::ConstantArray:
5695     case Type::IncompleteArray:
5696     case Type::VariableArray:
5697     case Type::DependentSizedArray:
5698       T = cast<ArrayType>(T)->getElementType().getTypePtr();
5699       break;
5700     default:
5701       return E;
5702     }
5703   }
5704
5705   // That should be enough to guarantee that this type is complete, if we're
5706   // not processing a decltype expression.
5707   CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5708   if (RD->isInvalidDecl() || RD->isDependentContext())
5709     return E;
5710
5711   bool IsDecltype = ExprEvalContexts.back().IsDecltype;
5712   CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
5713
5714   if (Destructor) {
5715     MarkFunctionReferenced(E->getExprLoc(), Destructor);
5716     CheckDestructorAccess(E->getExprLoc(), Destructor,
5717                           PDiag(diag::err_access_dtor_temp)
5718                             << E->getType());
5719     if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
5720       return ExprError();
5721
5722     // If destructor is trivial, we can avoid the extra copy.
5723     if (Destructor->isTrivial())
5724       return E;
5725
5726     // We need a cleanup, but we don't need to remember the temporary.
5727     Cleanup.setExprNeedsCleanups(true);
5728   }
5729
5730   CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
5731   CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
5732
5733   if (IsDecltype)
5734     ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
5735
5736   return Bind;
5737 }
5738
5739 ExprResult
5740 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
5741   if (SubExpr.isInvalid())
5742     return ExprError();
5743
5744   return MaybeCreateExprWithCleanups(SubExpr.get());
5745 }
5746
5747 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
5748   assert(SubExpr && "subexpression can't be null!");
5749
5750   CleanupVarDeclMarking();
5751
5752   unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5753   assert(ExprCleanupObjects.size() >= FirstCleanup);
5754   assert(Cleanup.exprNeedsCleanups() ||
5755          ExprCleanupObjects.size() == FirstCleanup);
5756   if (!Cleanup.exprNeedsCleanups())
5757     return SubExpr;
5758
5759   auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5760                                      ExprCleanupObjects.size() - FirstCleanup);
5761
5762   auto *E = ExprWithCleanups::Create(
5763       Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
5764   DiscardCleanupsInEvaluationContext();
5765
5766   return E;
5767 }
5768
5769 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
5770   assert(SubStmt && "sub-statement can't be null!");
5771
5772   CleanupVarDeclMarking();
5773
5774   if (!Cleanup.exprNeedsCleanups())
5775     return SubStmt;
5776
5777   // FIXME: In order to attach the temporaries, wrap the statement into
5778   // a StmtExpr; currently this is only used for asm statements.
5779   // This is hacky, either create a new CXXStmtWithTemporaries statement or
5780   // a new AsmStmtWithTemporaries.
5781   CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
5782                                                       SourceLocation(),
5783                                                       SourceLocation());
5784   Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5785                                    SourceLocation());
5786   return MaybeCreateExprWithCleanups(E);
5787 }
5788
5789 /// Process the expression contained within a decltype. For such expressions,
5790 /// certain semantic checks on temporaries are delayed until this point, and
5791 /// are omitted for the 'topmost' call in the decltype expression. If the
5792 /// topmost call bound a temporary, strip that temporary off the expression.
5793 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
5794   assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
5795
5796   // C++11 [expr.call]p11:
5797   //   If a function call is a prvalue of object type,
5798   // -- if the function call is either
5799   //   -- the operand of a decltype-specifier, or
5800   //   -- the right operand of a comma operator that is the operand of a
5801   //      decltype-specifier,
5802   //   a temporary object is not introduced for the prvalue.
5803
5804   // Recursively rebuild ParenExprs and comma expressions to strip out the
5805   // outermost CXXBindTemporaryExpr, if any.
5806   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5807     ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5808     if (SubExpr.isInvalid())
5809       return ExprError();
5810     if (SubExpr.get() == PE->getSubExpr())
5811       return E;
5812     return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
5813   }
5814   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5815     if (BO->getOpcode() == BO_Comma) {
5816       ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5817       if (RHS.isInvalid())
5818         return ExprError();
5819       if (RHS.get() == BO->getRHS())
5820         return E;
5821       return new (Context) BinaryOperator(
5822           BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
5823           BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
5824     }
5825   }
5826
5827   CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
5828   CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
5829                               : nullptr;
5830   if (TopCall)
5831     E = TopCall;
5832   else
5833     TopBind = nullptr;
5834
5835   // Disable the special decltype handling now.
5836   ExprEvalContexts.back().IsDecltype = false;
5837
5838   // In MS mode, don't perform any extra checking of call return types within a
5839   // decltype expression.
5840   if (getLangOpts().MSVCCompat)
5841     return E;
5842
5843   // Perform the semantic checks we delayed until this point.
5844   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5845        I != N; ++I) {
5846     CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
5847     if (Call == TopCall)
5848       continue;
5849
5850     if (CheckCallReturnType(Call->getCallReturnType(Context),
5851                             Call->getLocStart(),
5852                             Call, Call->getDirectCallee()))
5853       return ExprError();
5854   }
5855
5856   // Now all relevant types are complete, check the destructors are accessible
5857   // and non-deleted, and annotate them on the temporaries.
5858   for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5859        I != N; ++I) {
5860     CXXBindTemporaryExpr *Bind =
5861       ExprEvalContexts.back().DelayedDecltypeBinds[I];
5862     if (Bind == TopBind)
5863       continue;
5864
5865     CXXTemporary *Temp = Bind->getTemporary();
5866
5867     CXXRecordDecl *RD =
5868       Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5869     CXXDestructorDecl *Destructor = LookupDestructor(RD);
5870     Temp->setDestructor(Destructor);
5871
5872     MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5873     CheckDestructorAccess(Bind->getExprLoc(), Destructor,
5874                           PDiag(diag::err_access_dtor_temp)
5875                             << Bind->getType());
5876     if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5877       return ExprError();
5878
5879     // We need a cleanup, but we don't need to remember the temporary.
5880     Cleanup.setExprNeedsCleanups(true);
5881   }
5882
5883   // Possibly strip off the top CXXBindTemporaryExpr.
5884   return E;
5885 }
5886
5887 /// Note a set of 'operator->' functions that were used for a member access.
5888 static void noteOperatorArrows(Sema &S,
5889                                ArrayRef<FunctionDecl *> OperatorArrows) {
5890   unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
5891   // FIXME: Make this configurable?
5892   unsigned Limit = 9;
5893   if (OperatorArrows.size() > Limit) {
5894     // Produce Limit-1 normal notes and one 'skipping' note.
5895     SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
5896     SkipCount = OperatorArrows.size() - (Limit - 1);
5897   }
5898
5899   for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
5900     if (I == SkipStart) {
5901       S.Diag(OperatorArrows[I]->getLocation(),
5902              diag::note_operator_arrows_suppressed)
5903           << SkipCount;
5904       I += SkipCount;
5905     } else {
5906       S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
5907           << OperatorArrows[I]->getCallResultType();
5908       ++I;
5909     }
5910   }
5911 }
5912
5913 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
5914                                               SourceLocation OpLoc,
5915                                               tok::TokenKind OpKind,
5916                                               ParsedType &ObjectType,
5917                                               bool &MayBePseudoDestructor) {
5918   // Since this might be a postfix expression, get rid of ParenListExprs.
5919   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
5920   if (Result.isInvalid()) return ExprError();
5921   Base = Result.get();
5922
5923   Result = CheckPlaceholderExpr(Base);
5924   if (Result.isInvalid()) return ExprError();
5925   Base = Result.get();
5926
5927   QualType BaseType = Base->getType();
5928   MayBePseudoDestructor = false;
5929   if (BaseType->isDependentType()) {
5930     // If we have a pointer to a dependent type and are using the -> operator,
5931     // the object type is the type that the pointer points to. We might still
5932     // have enough information about that type to do something useful.
5933     if (OpKind == tok::arrow)
5934       if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5935         BaseType = Ptr->getPointeeType();
5936
5937     ObjectType = ParsedType::make(BaseType);
5938     MayBePseudoDestructor = true;
5939     return Base;
5940   }
5941
5942   // C++ [over.match.oper]p8:
5943   //   [...] When operator->returns, the operator-> is applied  to the value
5944   //   returned, with the original second operand.
5945   if (OpKind == tok::arrow) {
5946     QualType StartingType = BaseType;
5947     bool NoArrowOperatorFound = false;
5948     bool FirstIteration = true;
5949     FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
5950     // The set of types we've considered so far.
5951     llvm::SmallPtrSet<CanQualType,8> CTypes;
5952     SmallVector<FunctionDecl*, 8> OperatorArrows;
5953     CTypes.insert(Context.getCanonicalType(BaseType));
5954
5955     while (BaseType->isRecordType()) {
5956       if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
5957         Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
5958           << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
5959         noteOperatorArrows(*this, OperatorArrows);
5960         Diag(OpLoc, diag::note_operator_arrow_depth)
5961           << getLangOpts().ArrowDepth;
5962         return ExprError();
5963       }
5964
5965       Result = BuildOverloadedArrowExpr(
5966           S, Base, OpLoc,
5967           // When in a template specialization and on the first loop iteration,
5968           // potentially give the default diagnostic (with the fixit in a
5969           // separate note) instead of having the error reported back to here
5970           // and giving a diagnostic with a fixit attached to the error itself.
5971           (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
5972               ? nullptr
5973               : &NoArrowOperatorFound);
5974       if (Result.isInvalid()) {
5975         if (NoArrowOperatorFound) {
5976           if (FirstIteration) {
5977             Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5978               << BaseType << 1 << Base->getSourceRange()
5979               << FixItHint::CreateReplacement(OpLoc, ".");
5980             OpKind = tok::period;
5981             break;
5982           }
5983           Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5984             << BaseType << Base->getSourceRange();
5985           CallExpr *CE = dyn_cast<CallExpr>(Base);
5986           if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
5987             Diag(CD->getLocStart(),
5988                  diag::note_member_reference_arrow_from_operator_arrow);
5989           }
5990         }
5991         return ExprError();
5992       }
5993       Base = Result.get();
5994       if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
5995         OperatorArrows.push_back(OpCall->getDirectCallee());
5996       BaseType = Base->getType();
5997       CanQualType CBaseType = Context.getCanonicalType(BaseType);
5998       if (!CTypes.insert(CBaseType).second) {
5999         Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6000         noteOperatorArrows(*this, OperatorArrows);
6001         return ExprError();
6002       }
6003       FirstIteration = false;
6004     }
6005
6006     if (OpKind == tok::arrow &&
6007         (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
6008       BaseType = BaseType->getPointeeType();
6009   }
6010
6011   // Objective-C properties allow "." access on Objective-C pointer types,
6012   // so adjust the base type to the object type itself.
6013   if (BaseType->isObjCObjectPointerType())
6014     BaseType = BaseType->getPointeeType();
6015   
6016   // C++ [basic.lookup.classref]p2:
6017   //   [...] If the type of the object expression is of pointer to scalar
6018   //   type, the unqualified-id is looked up in the context of the complete
6019   //   postfix-expression.
6020   //
6021   // This also indicates that we could be parsing a pseudo-destructor-name.
6022   // Note that Objective-C class and object types can be pseudo-destructor
6023   // expressions or normal member (ivar or property) access expressions, and
6024   // it's legal for the type to be incomplete if this is a pseudo-destructor
6025   // call.  We'll do more incomplete-type checks later in the lookup process,
6026   // so just skip this check for ObjC types.
6027   if (BaseType->isObjCObjectOrInterfaceType()) {
6028     ObjectType = ParsedType::make(BaseType);
6029     MayBePseudoDestructor = true;
6030     return Base;
6031   } else if (!BaseType->isRecordType()) {
6032     ObjectType = nullptr;
6033     MayBePseudoDestructor = true;
6034     return Base;
6035   }
6036
6037   // The object type must be complete (or dependent), or
6038   // C++11 [expr.prim.general]p3:
6039   //   Unlike the object expression in other contexts, *this is not required to
6040   //   be of complete type for purposes of class member access (5.2.5) outside 
6041   //   the member function body.
6042   if (!BaseType->isDependentType() &&
6043       !isThisOutsideMemberFunctionBody(BaseType) &&
6044       RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
6045     return ExprError();
6046
6047   // C++ [basic.lookup.classref]p2:
6048   //   If the id-expression in a class member access (5.2.5) is an
6049   //   unqualified-id, and the type of the object expression is of a class
6050   //   type C (or of pointer to a class type C), the unqualified-id is looked
6051   //   up in the scope of class C. [...]
6052   ObjectType = ParsedType::make(BaseType);
6053   return Base;
6054 }
6055
6056 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base, 
6057                    tok::TokenKind& OpKind, SourceLocation OpLoc) {
6058   if (Base->hasPlaceholderType()) {
6059     ExprResult result = S.CheckPlaceholderExpr(Base);
6060     if (result.isInvalid()) return true;
6061     Base = result.get();
6062   }
6063   ObjectType = Base->getType();
6064
6065   // C++ [expr.pseudo]p2:
6066   //   The left-hand side of the dot operator shall be of scalar type. The
6067   //   left-hand side of the arrow operator shall be of pointer to scalar type.
6068   //   This scalar type is the object type.
6069   // Note that this is rather different from the normal handling for the
6070   // arrow operator.
6071   if (OpKind == tok::arrow) {
6072     if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6073       ObjectType = Ptr->getPointeeType();
6074     } else if (!Base->isTypeDependent()) {
6075       // The user wrote "p->" when they probably meant "p."; fix it.
6076       S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6077         << ObjectType << true
6078         << FixItHint::CreateReplacement(OpLoc, ".");
6079       if (S.isSFINAEContext())
6080         return true;
6081
6082       OpKind = tok::period;
6083     }
6084   }
6085
6086   return false;
6087 }
6088
6089 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
6090                                            SourceLocation OpLoc,
6091                                            tok::TokenKind OpKind,
6092                                            const CXXScopeSpec &SS,
6093                                            TypeSourceInfo *ScopeTypeInfo,
6094                                            SourceLocation CCLoc,
6095                                            SourceLocation TildeLoc,
6096                                          PseudoDestructorTypeStorage Destructed) {
6097   TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
6098
6099   QualType ObjectType;
6100   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6101     return ExprError();
6102
6103   if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6104       !ObjectType->isVectorType()) {
6105     if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
6106       Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
6107     else {
6108       Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6109         << ObjectType << Base->getSourceRange();
6110       return ExprError();
6111     }
6112   }
6113
6114   // C++ [expr.pseudo]p2:
6115   //   [...] The cv-unqualified versions of the object type and of the type
6116   //   designated by the pseudo-destructor-name shall be the same type.
6117   if (DestructedTypeInfo) {
6118     QualType DestructedType = DestructedTypeInfo->getType();
6119     SourceLocation DestructedTypeStart
6120       = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
6121     if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6122       if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6123         Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6124           << ObjectType << DestructedType << Base->getSourceRange()
6125           << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6126
6127         // Recover by setting the destructed type to the object type.
6128         DestructedType = ObjectType;
6129         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6130                                                            DestructedTypeStart);
6131         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6132       } else if (DestructedType.getObjCLifetime() != 
6133                                                 ObjectType.getObjCLifetime()) {
6134         
6135         if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6136           // Okay: just pretend that the user provided the correctly-qualified
6137           // type.
6138         } else {
6139           Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6140             << ObjectType << DestructedType << Base->getSourceRange()
6141             << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6142         }
6143         
6144         // Recover by setting the destructed type to the object type.
6145         DestructedType = ObjectType;
6146         DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6147                                                            DestructedTypeStart);
6148         Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6149       }
6150     }
6151   }
6152
6153   // C++ [expr.pseudo]p2:
6154   //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6155   //   form
6156   //
6157   //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
6158   //
6159   //   shall designate the same scalar type.
6160   if (ScopeTypeInfo) {
6161     QualType ScopeType = ScopeTypeInfo->getType();
6162     if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
6163         !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
6164
6165       Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
6166            diag::err_pseudo_dtor_type_mismatch)
6167         << ObjectType << ScopeType << Base->getSourceRange()
6168         << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
6169
6170       ScopeType = QualType();
6171       ScopeTypeInfo = nullptr;
6172     }
6173   }
6174
6175   Expr *Result
6176     = new (Context) CXXPseudoDestructorExpr(Context, Base,
6177                                             OpKind == tok::arrow, OpLoc,
6178                                             SS.getWithLocInContext(Context),
6179                                             ScopeTypeInfo,
6180                                             CCLoc,
6181                                             TildeLoc,
6182                                             Destructed);
6183
6184   return Result;
6185 }
6186
6187 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6188                                            SourceLocation OpLoc,
6189                                            tok::TokenKind OpKind,
6190                                            CXXScopeSpec &SS,
6191                                            UnqualifiedId &FirstTypeName,
6192                                            SourceLocation CCLoc,
6193                                            SourceLocation TildeLoc,
6194                                            UnqualifiedId &SecondTypeName) {
6195   assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6196           FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6197          "Invalid first type name in pseudo-destructor");
6198   assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6199           SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6200          "Invalid second type name in pseudo-destructor");
6201
6202   QualType ObjectType;
6203   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6204     return ExprError();
6205
6206   // Compute the object type that we should use for name lookup purposes. Only
6207   // record types and dependent types matter.
6208   ParsedType ObjectTypePtrForLookup;
6209   if (!SS.isSet()) {
6210     if (ObjectType->isRecordType())
6211       ObjectTypePtrForLookup = ParsedType::make(ObjectType);
6212     else if (ObjectType->isDependentType())
6213       ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
6214   }
6215
6216   // Convert the name of the type being destructed (following the ~) into a
6217   // type (with source-location information).
6218   QualType DestructedType;
6219   TypeSourceInfo *DestructedTypeInfo = nullptr;
6220   PseudoDestructorTypeStorage Destructed;
6221   if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6222     ParsedType T = getTypeName(*SecondTypeName.Identifier,
6223                                SecondTypeName.StartLocation,
6224                                S, &SS, true, false, ObjectTypePtrForLookup);
6225     if (!T &&
6226         ((SS.isSet() && !computeDeclContext(SS, false)) ||
6227          (!SS.isSet() && ObjectType->isDependentType()))) {
6228       // The name of the type being destroyed is a dependent name, and we
6229       // couldn't find anything useful in scope. Just store the identifier and
6230       // it's location, and we'll perform (qualified) name lookup again at
6231       // template instantiation time.
6232       Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6233                                                SecondTypeName.StartLocation);
6234     } else if (!T) {
6235       Diag(SecondTypeName.StartLocation,
6236            diag::err_pseudo_dtor_destructor_non_type)
6237         << SecondTypeName.Identifier << ObjectType;
6238       if (isSFINAEContext())
6239         return ExprError();
6240
6241       // Recover by assuming we had the right type all along.
6242       DestructedType = ObjectType;
6243     } else
6244       DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
6245   } else {
6246     // Resolve the template-id to a type.
6247     TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
6248     ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6249                                        TemplateId->NumArgs);
6250     TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6251                                        TemplateId->TemplateKWLoc,
6252                                        TemplateId->Template,
6253                                        TemplateId->TemplateNameLoc,
6254                                        TemplateId->LAngleLoc,
6255                                        TemplateArgsPtr,
6256                                        TemplateId->RAngleLoc);
6257     if (T.isInvalid() || !T.get()) {
6258       // Recover by assuming we had the right type all along.
6259       DestructedType = ObjectType;
6260     } else
6261       DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
6262   }
6263
6264   // If we've performed some kind of recovery, (re-)build the type source
6265   // information.
6266   if (!DestructedType.isNull()) {
6267     if (!DestructedTypeInfo)
6268       DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
6269                                                   SecondTypeName.StartLocation);
6270     Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6271   }
6272
6273   // Convert the name of the scope type (the type prior to '::') into a type.
6274   TypeSourceInfo *ScopeTypeInfo = nullptr;
6275   QualType ScopeType;
6276   if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6277       FirstTypeName.Identifier) {
6278     if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6279       ParsedType T = getTypeName(*FirstTypeName.Identifier,
6280                                  FirstTypeName.StartLocation,
6281                                  S, &SS, true, false, ObjectTypePtrForLookup);
6282       if (!T) {
6283         Diag(FirstTypeName.StartLocation,
6284              diag::err_pseudo_dtor_destructor_non_type)
6285           << FirstTypeName.Identifier << ObjectType;
6286
6287         if (isSFINAEContext())
6288           return ExprError();
6289
6290         // Just drop this type. It's unnecessary anyway.
6291         ScopeType = QualType();
6292       } else
6293         ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
6294     } else {
6295       // Resolve the template-id to a type.
6296       TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
6297       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6298                                          TemplateId->NumArgs);
6299       TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6300                                          TemplateId->TemplateKWLoc,
6301                                          TemplateId->Template,
6302                                          TemplateId->TemplateNameLoc,
6303                                          TemplateId->LAngleLoc,
6304                                          TemplateArgsPtr,
6305                                          TemplateId->RAngleLoc);
6306       if (T.isInvalid() || !T.get()) {
6307         // Recover by dropping this type.
6308         ScopeType = QualType();
6309       } else
6310         ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
6311     }
6312   }
6313
6314   if (!ScopeType.isNull() && !ScopeTypeInfo)
6315     ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6316                                                   FirstTypeName.StartLocation);
6317
6318
6319   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
6320                                    ScopeTypeInfo, CCLoc, TildeLoc,
6321                                    Destructed);
6322 }
6323
6324 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6325                                            SourceLocation OpLoc,
6326                                            tok::TokenKind OpKind,
6327                                            SourceLocation TildeLoc, 
6328                                            const DeclSpec& DS) {
6329   QualType ObjectType;
6330   if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6331     return ExprError();
6332
6333   QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6334                                  false);
6335
6336   TypeLocBuilder TLB;
6337   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6338   DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6339   TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6340   PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6341
6342   return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
6343                                    nullptr, SourceLocation(), TildeLoc,
6344                                    Destructed);
6345 }
6346
6347 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
6348                                         CXXConversionDecl *Method,
6349                                         bool HadMultipleCandidates) {
6350   if (Method->getParent()->isLambda() &&
6351       Method->getConversionType()->isBlockPointerType()) {
6352     // This is a lambda coversion to block pointer; check if the argument
6353     // is a LambdaExpr.
6354     Expr *SubE = E;
6355     CastExpr *CE = dyn_cast<CastExpr>(SubE);
6356     if (CE && CE->getCastKind() == CK_NoOp)
6357       SubE = CE->getSubExpr();
6358     SubE = SubE->IgnoreParens();
6359     if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6360       SubE = BE->getSubExpr();
6361     if (isa<LambdaExpr>(SubE)) {
6362       // For the conversion to block pointer on a lambda expression, we
6363       // construct a special BlockLiteral instead; this doesn't really make
6364       // a difference in ARC, but outside of ARC the resulting block literal
6365       // follows the normal lifetime rules for block literals instead of being
6366       // autoreleased.
6367       DiagnosticErrorTrap Trap(Diags);
6368       PushExpressionEvaluationContext(PotentiallyEvaluated);
6369       ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6370                                                      E->getExprLoc(),
6371                                                      Method, E);
6372       PopExpressionEvaluationContext();
6373
6374       if (Exp.isInvalid())
6375         Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6376       return Exp;
6377     }
6378   }
6379
6380   ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
6381                                           FoundDecl, Method);
6382   if (Exp.isInvalid())
6383     return true;
6384
6385   MemberExpr *ME = new (Context) MemberExpr(
6386       Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6387       Context.BoundMemberTy, VK_RValue, OK_Ordinary);
6388   if (HadMultipleCandidates)
6389     ME->setHadMultipleCandidates(true);
6390   MarkMemberReferenced(ME);
6391
6392   QualType ResultType = Method->getReturnType();
6393   ExprValueKind VK = Expr::getValueKindForType(ResultType);
6394   ResultType = ResultType.getNonLValueExprType(Context);
6395
6396   CXXMemberCallExpr *CE =
6397     new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
6398                                     Exp.get()->getLocEnd());
6399   return CE;
6400 }
6401
6402 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6403                                       SourceLocation RParen) {
6404   // If the operand is an unresolved lookup expression, the expression is ill-
6405   // formed per [over.over]p1, because overloaded function names cannot be used
6406   // without arguments except in explicit contexts.
6407   ExprResult R = CheckPlaceholderExpr(Operand);
6408   if (R.isInvalid())
6409     return R;
6410
6411   // The operand may have been modified when checking the placeholder type.
6412   Operand = R.get();
6413
6414   if (ActiveTemplateInstantiations.empty() &&
6415       Operand->HasSideEffects(Context, false)) {
6416     // The expression operand for noexcept is in an unevaluated expression
6417     // context, so side effects could result in unintended consequences.
6418     Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6419   }
6420
6421   CanThrowResult CanThrow = canThrow(Operand);
6422   return new (Context)
6423       CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
6424 }
6425
6426 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6427                                    Expr *Operand, SourceLocation RParen) {
6428   return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
6429 }
6430
6431 static bool IsSpecialDiscardedValue(Expr *E) {
6432   // In C++11, discarded-value expressions of a certain form are special,
6433   // according to [expr]p10:
6434   //   The lvalue-to-rvalue conversion (4.1) is applied only if the
6435   //   expression is an lvalue of volatile-qualified type and it has
6436   //   one of the following forms:
6437   E = E->IgnoreParens();
6438
6439   //   - id-expression (5.1.1),
6440   if (isa<DeclRefExpr>(E))
6441     return true;
6442
6443   //   - subscripting (5.2.1),
6444   if (isa<ArraySubscriptExpr>(E))
6445     return true;
6446
6447   //   - class member access (5.2.5),
6448   if (isa<MemberExpr>(E))
6449     return true;
6450
6451   //   - indirection (5.3.1),
6452   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6453     if (UO->getOpcode() == UO_Deref)
6454       return true;
6455
6456   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6457     //   - pointer-to-member operation (5.5),
6458     if (BO->isPtrMemOp())
6459       return true;
6460
6461     //   - comma expression (5.18) where the right operand is one of the above.
6462     if (BO->getOpcode() == BO_Comma)
6463       return IsSpecialDiscardedValue(BO->getRHS());
6464   }
6465
6466   //   - conditional expression (5.16) where both the second and the third
6467   //     operands are one of the above, or
6468   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6469     return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6470            IsSpecialDiscardedValue(CO->getFalseExpr());
6471   // The related edge case of "*x ?: *x".
6472   if (BinaryConditionalOperator *BCO =
6473           dyn_cast<BinaryConditionalOperator>(E)) {
6474     if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6475       return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6476              IsSpecialDiscardedValue(BCO->getFalseExpr());
6477   }
6478
6479   // Objective-C++ extensions to the rule.
6480   if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6481     return true;
6482
6483   return false;
6484 }
6485
6486 /// Perform the conversions required for an expression used in a
6487 /// context that ignores the result.
6488 ExprResult Sema::IgnoredValueConversions(Expr *E) {
6489   if (E->hasPlaceholderType()) {
6490     ExprResult result = CheckPlaceholderExpr(E);
6491     if (result.isInvalid()) return E;
6492     E = result.get();
6493   }
6494
6495   // C99 6.3.2.1:
6496   //   [Except in specific positions,] an lvalue that does not have
6497   //   array type is converted to the value stored in the
6498   //   designated object (and is no longer an lvalue).
6499   if (E->isRValue()) {
6500     // In C, function designators (i.e. expressions of function type)
6501     // are r-values, but we still want to do function-to-pointer decay
6502     // on them.  This is both technically correct and convenient for
6503     // some clients.
6504     if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
6505       return DefaultFunctionArrayConversion(E);
6506
6507     return E;
6508   }
6509
6510   if (getLangOpts().CPlusPlus)  {
6511     // The C++11 standard defines the notion of a discarded-value expression;
6512     // normally, we don't need to do anything to handle it, but if it is a
6513     // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6514     // conversion.
6515     if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
6516         E->getType().isVolatileQualified() &&
6517         IsSpecialDiscardedValue(E)) {
6518       ExprResult Res = DefaultLvalueConversion(E);
6519       if (Res.isInvalid())
6520         return E;
6521       E = Res.get();
6522     } 
6523     return E;
6524   }
6525
6526   // GCC seems to also exclude expressions of incomplete enum type.
6527   if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6528     if (!T->getDecl()->isComplete()) {
6529       // FIXME: stupid workaround for a codegen bug!
6530       E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
6531       return E;
6532     }
6533   }
6534
6535   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6536   if (Res.isInvalid())
6537     return E;
6538   E = Res.get();
6539
6540   if (!E->getType()->isVoidType())
6541     RequireCompleteType(E->getExprLoc(), E->getType(),
6542                         diag::err_incomplete_type);
6543   return E;
6544 }
6545
6546 // If we can unambiguously determine whether Var can never be used
6547 // in a constant expression, return true.
6548 //  - if the variable and its initializer are non-dependent, then
6549 //    we can unambiguously check if the variable is a constant expression.
6550 //  - if the initializer is not value dependent - we can determine whether
6551 //    it can be used to initialize a constant expression.  If Init can not
6552 //    be used to initialize a constant expression we conclude that Var can 
6553 //    never be a constant expression.
6554 //  - FXIME: if the initializer is dependent, we can still do some analysis and
6555 //    identify certain cases unambiguously as non-const by using a Visitor:
6556 //      - such as those that involve odr-use of a ParmVarDecl, involve a new
6557 //        delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
6558 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, 
6559     ASTContext &Context) {
6560   if (isa<ParmVarDecl>(Var)) return true;
6561   const VarDecl *DefVD = nullptr;
6562
6563   // If there is no initializer - this can not be a constant expression.
6564   if (!Var->getAnyInitializer(DefVD)) return true;
6565   assert(DefVD);
6566   if (DefVD->isWeak()) return false;
6567   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
6568
6569   Expr *Init = cast<Expr>(Eval->Value);
6570
6571   if (Var->getType()->isDependentType() || Init->isValueDependent()) {
6572     // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6573     // of value-dependent expressions, and use it here to determine whether the
6574     // initializer is a potential constant expression.
6575     return false;
6576   }
6577
6578   return !IsVariableAConstantExpression(Var, Context); 
6579 }
6580
6581 /// \brief Check if the current lambda has any potential captures 
6582 /// that must be captured by any of its enclosing lambdas that are ready to 
6583 /// capture. If there is a lambda that can capture a nested 
6584 /// potential-capture, go ahead and do so.  Also, check to see if any 
6585 /// variables are uncaptureable or do not involve an odr-use so do not 
6586 /// need to be captured.
6587
6588 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6589     Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6590
6591   assert(!S.isUnevaluatedContext());
6592   assert(S.CurContext->isDependentContext());
6593 #ifndef NDEBUG
6594   DeclContext *DC = S.CurContext;
6595   while (DC && isa<CapturedDecl>(DC))
6596     DC = DC->getParent();
6597   assert(
6598       CurrentLSI->CallOperator == DC &&
6599       "The current call operator must be synchronized with Sema's CurContext");
6600 #endif // NDEBUG
6601
6602   const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
6603
6604   ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
6605       S.FunctionScopes.data(), S.FunctionScopes.size());
6606   
6607   // All the potentially captureable variables in the current nested
6608   // lambda (within a generic outer lambda), must be captured by an
6609   // outer lambda that is enclosed within a non-dependent context.
6610   const unsigned NumPotentialCaptures =
6611       CurrentLSI->getNumPotentialVariableCaptures();
6612   for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
6613     Expr *VarExpr = nullptr;
6614     VarDecl *Var = nullptr;
6615     CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
6616     // If the variable is clearly identified as non-odr-used and the full
6617     // expression is not instantiation dependent, only then do we not 
6618     // need to check enclosing lambda's for speculative captures.
6619     // For e.g.:
6620     // Even though 'x' is not odr-used, it should be captured.
6621     // int test() {
6622     //   const int x = 10;
6623     //   auto L = [=](auto a) {
6624     //     (void) +x + a;
6625     //   };
6626     // }
6627     if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
6628         !IsFullExprInstantiationDependent)
6629       continue;
6630
6631     // If we have a capture-capable lambda for the variable, go ahead and
6632     // capture the variable in that lambda (and all its enclosing lambdas).
6633     if (const Optional<unsigned> Index =
6634             getStackIndexOfNearestEnclosingCaptureCapableLambda(
6635                 FunctionScopesArrayRef, Var, S)) {
6636       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6637       MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
6638                          &FunctionScopeIndexOfCapturableLambda);
6639     } 
6640     const bool IsVarNeverAConstantExpression = 
6641         VariableCanNeverBeAConstantExpression(Var, S.Context);
6642     if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
6643       // This full expression is not instantiation dependent or the variable
6644       // can not be used in a constant expression - which means 
6645       // this variable must be odr-used here, so diagnose a 
6646       // capture violation early, if the variable is un-captureable.
6647       // This is purely for diagnosing errors early.  Otherwise, this
6648       // error would get diagnosed when the lambda becomes capture ready.
6649       QualType CaptureType, DeclRefType;
6650       SourceLocation ExprLoc = VarExpr->getExprLoc();
6651       if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
6652                           /*EllipsisLoc*/ SourceLocation(), 
6653                           /*BuildAndDiagnose*/false, CaptureType, 
6654                           DeclRefType, nullptr)) {
6655         // We will never be able to capture this variable, and we need
6656         // to be able to in any and all instantiations, so diagnose it.
6657         S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
6658                           /*EllipsisLoc*/ SourceLocation(), 
6659                           /*BuildAndDiagnose*/true, CaptureType, 
6660                           DeclRefType, nullptr);
6661       }
6662     }
6663   }
6664
6665   // Check if 'this' needs to be captured.
6666   if (CurrentLSI->hasPotentialThisCapture()) {
6667     // If we have a capture-capable lambda for 'this', go ahead and capture
6668     // 'this' in that lambda (and all its enclosing lambdas).
6669     if (const Optional<unsigned> Index =
6670             getStackIndexOfNearestEnclosingCaptureCapableLambda(
6671                 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
6672       const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6673       S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
6674                             /*Explicit*/ false, /*BuildAndDiagnose*/ true,
6675                             &FunctionScopeIndexOfCapturableLambda);
6676     }
6677   }
6678
6679   // Reset all the potential captures at the end of each full-expression.
6680   CurrentLSI->clearPotentialCaptures();
6681 }
6682
6683 static ExprResult attemptRecovery(Sema &SemaRef,
6684                                   const TypoCorrectionConsumer &Consumer,
6685                                   const TypoCorrection &TC) {
6686   LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
6687                  Consumer.getLookupResult().getLookupKind());
6688   const CXXScopeSpec *SS = Consumer.getSS();
6689   CXXScopeSpec NewSS;
6690
6691   // Use an approprate CXXScopeSpec for building the expr.
6692   if (auto *NNS = TC.getCorrectionSpecifier())
6693     NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
6694   else if (SS && !TC.WillReplaceSpecifier())
6695     NewSS = *SS;
6696
6697   if (auto *ND = TC.getFoundDecl()) {
6698     R.setLookupName(ND->getDeclName());
6699     R.addDecl(ND);
6700     if (ND->isCXXClassMember()) {
6701       // Figure out the correct naming class to add to the LookupResult.
6702       CXXRecordDecl *Record = nullptr;
6703       if (auto *NNS = TC.getCorrectionSpecifier())
6704         Record = NNS->getAsType()->getAsCXXRecordDecl();
6705       if (!Record)
6706         Record =
6707             dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
6708       if (Record)
6709         R.setNamingClass(Record);
6710
6711       // Detect and handle the case where the decl might be an implicit
6712       // member.
6713       bool MightBeImplicitMember;
6714       if (!Consumer.isAddressOfOperand())
6715         MightBeImplicitMember = true;
6716       else if (!NewSS.isEmpty())
6717         MightBeImplicitMember = false;
6718       else if (R.isOverloadedResult())
6719         MightBeImplicitMember = false;
6720       else if (R.isUnresolvableResult())
6721         MightBeImplicitMember = true;
6722       else
6723         MightBeImplicitMember = isa<FieldDecl>(ND) ||
6724                                 isa<IndirectFieldDecl>(ND) ||
6725                                 isa<MSPropertyDecl>(ND);
6726
6727       if (MightBeImplicitMember)
6728         return SemaRef.BuildPossibleImplicitMemberExpr(
6729             NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
6730             /*TemplateArgs*/ nullptr, /*S*/ nullptr);
6731     } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
6732       return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
6733                                         Ivar->getIdentifier());
6734     }
6735   }
6736
6737   return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
6738                                           /*AcceptInvalidDecl*/ true);
6739 }
6740
6741 namespace {
6742 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
6743   llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
6744
6745 public:
6746   explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
6747       : TypoExprs(TypoExprs) {}
6748   bool VisitTypoExpr(TypoExpr *TE) {
6749     TypoExprs.insert(TE);
6750     return true;
6751   }
6752 };
6753
6754 class TransformTypos : public TreeTransform<TransformTypos> {
6755   typedef TreeTransform<TransformTypos> BaseTransform;
6756
6757   VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
6758                      // process of being initialized.
6759   llvm::function_ref<ExprResult(Expr *)> ExprFilter;
6760   llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
6761   llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
6762   llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
6763
6764   /// \brief Emit diagnostics for all of the TypoExprs encountered.
6765   /// If the TypoExprs were successfully corrected, then the diagnostics should
6766   /// suggest the corrections. Otherwise the diagnostics will not suggest
6767   /// anything (having been passed an empty TypoCorrection).
6768   void EmitAllDiagnostics() {
6769     for (auto E : TypoExprs) {
6770       TypoExpr *TE = cast<TypoExpr>(E);
6771       auto &State = SemaRef.getTypoExprState(TE);
6772       if (State.DiagHandler) {
6773         TypoCorrection TC = State.Consumer->getCurrentCorrection();
6774         ExprResult Replacement = TransformCache[TE];
6775
6776         // Extract the NamedDecl from the transformed TypoExpr and add it to the
6777         // TypoCorrection, replacing the existing decls. This ensures the right
6778         // NamedDecl is used in diagnostics e.g. in the case where overload
6779         // resolution was used to select one from several possible decls that
6780         // had been stored in the TypoCorrection.
6781         if (auto *ND = getDeclFromExpr(
6782                 Replacement.isInvalid() ? nullptr : Replacement.get()))
6783           TC.setCorrectionDecl(ND);
6784
6785         State.DiagHandler(TC);
6786       }
6787       SemaRef.clearDelayedTypo(TE);
6788     }
6789   }
6790
6791   /// \brief If corrections for the first TypoExpr have been exhausted for a
6792   /// given combination of the other TypoExprs, retry those corrections against
6793   /// the next combination of substitutions for the other TypoExprs by advancing
6794   /// to the next potential correction of the second TypoExpr. For the second
6795   /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
6796   /// the stream is reset and the next TypoExpr's stream is advanced by one (a
6797   /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
6798   /// TransformCache). Returns true if there is still any untried combinations
6799   /// of corrections.
6800   bool CheckAndAdvanceTypoExprCorrectionStreams() {
6801     for (auto TE : TypoExprs) {
6802       auto &State = SemaRef.getTypoExprState(TE);
6803       TransformCache.erase(TE);
6804       if (!State.Consumer->finished())
6805         return true;
6806       State.Consumer->resetCorrectionStream();
6807     }
6808     return false;
6809   }
6810
6811   NamedDecl *getDeclFromExpr(Expr *E) {
6812     if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
6813       E = OverloadResolution[OE];
6814
6815     if (!E)
6816       return nullptr;
6817     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
6818       return DRE->getFoundDecl();
6819     if (auto *ME = dyn_cast<MemberExpr>(E))
6820       return ME->getFoundDecl();
6821     // FIXME: Add any other expr types that could be be seen by the delayed typo
6822     // correction TreeTransform for which the corresponding TypoCorrection could
6823     // contain multiple decls.
6824     return nullptr;
6825   }
6826
6827   ExprResult TryTransform(Expr *E) {
6828     Sema::SFINAETrap Trap(SemaRef);
6829     ExprResult Res = TransformExpr(E);
6830     if (Trap.hasErrorOccurred() || Res.isInvalid())
6831       return ExprError();
6832
6833     return ExprFilter(Res.get());
6834   }
6835
6836 public:
6837   TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
6838       : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
6839
6840   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
6841                                    MultiExprArg Args,
6842                                    SourceLocation RParenLoc,
6843                                    Expr *ExecConfig = nullptr) {
6844     auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
6845                                                  RParenLoc, ExecConfig);
6846     if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
6847       if (Result.isUsable()) {
6848         Expr *ResultCall = Result.get();
6849         if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
6850           ResultCall = BE->getSubExpr();
6851         if (auto *CE = dyn_cast<CallExpr>(ResultCall))
6852           OverloadResolution[OE] = CE->getCallee();
6853       }
6854     }
6855     return Result;
6856   }
6857
6858   ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
6859
6860   ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
6861
6862   ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
6863     return Owned(E);
6864   }
6865
6866   ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
6867     return Owned(E);
6868   }
6869
6870   ExprResult Transform(Expr *E) {
6871     ExprResult Res;
6872     while (true) {
6873       Res = TryTransform(E);
6874
6875       // Exit if either the transform was valid or if there were no TypoExprs
6876       // to transform that still have any untried correction candidates..
6877       if (!Res.isInvalid() ||
6878           !CheckAndAdvanceTypoExprCorrectionStreams())
6879         break;
6880     }
6881
6882     // Ensure none of the TypoExprs have multiple typo correction candidates
6883     // with the same edit length that pass all the checks and filters.
6884     // TODO: Properly handle various permutations of possible corrections when
6885     // there is more than one potentially ambiguous typo correction.
6886     // Also, disable typo correction while attempting the transform when
6887     // handling potentially ambiguous typo corrections as any new TypoExprs will
6888     // have been introduced by the application of one of the correction
6889     // candidates and add little to no value if corrected.
6890     SemaRef.DisableTypoCorrection = true;
6891     while (!AmbiguousTypoExprs.empty()) {
6892       auto TE  = AmbiguousTypoExprs.back();
6893       auto Cached = TransformCache[TE];
6894       auto &State = SemaRef.getTypoExprState(TE);
6895       State.Consumer->saveCurrentPosition();
6896       TransformCache.erase(TE);
6897       if (!TryTransform(E).isInvalid()) {
6898         State.Consumer->resetCorrectionStream();
6899         TransformCache.erase(TE);
6900         Res = ExprError();
6901         break;
6902       }
6903       AmbiguousTypoExprs.remove(TE);
6904       State.Consumer->restoreSavedPosition();
6905       TransformCache[TE] = Cached;
6906     }
6907     SemaRef.DisableTypoCorrection = false;
6908
6909     // Ensure that all of the TypoExprs within the current Expr have been found.
6910     if (!Res.isUsable())
6911       FindTypoExprs(TypoExprs).TraverseStmt(E);
6912
6913     EmitAllDiagnostics();
6914
6915     return Res;
6916   }
6917
6918   ExprResult TransformTypoExpr(TypoExpr *E) {
6919     // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
6920     // cached transformation result if there is one and the TypoExpr isn't the
6921     // first one that was encountered.
6922     auto &CacheEntry = TransformCache[E];
6923     if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
6924       return CacheEntry;
6925     }
6926
6927     auto &State = SemaRef.getTypoExprState(E);
6928     assert(State.Consumer && "Cannot transform a cleared TypoExpr");
6929
6930     // For the first TypoExpr and an uncached TypoExpr, find the next likely
6931     // typo correction and return it.
6932     while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
6933       if (InitDecl && TC.getFoundDecl() == InitDecl)
6934         continue;
6935       ExprResult NE = State.RecoveryHandler ?
6936           State.RecoveryHandler(SemaRef, E, TC) :
6937           attemptRecovery(SemaRef, *State.Consumer, TC);
6938       if (!NE.isInvalid()) {
6939         // Check whether there may be a second viable correction with the same
6940         // edit distance; if so, remember this TypoExpr may have an ambiguous
6941         // correction so it can be more thoroughly vetted later.
6942         TypoCorrection Next;
6943         if ((Next = State.Consumer->peekNextCorrection()) &&
6944             Next.getEditDistance(false) == TC.getEditDistance(false)) {
6945           AmbiguousTypoExprs.insert(E);
6946         } else {
6947           AmbiguousTypoExprs.remove(E);
6948         }
6949         assert(!NE.isUnset() &&
6950                "Typo was transformed into a valid-but-null ExprResult");
6951         return CacheEntry = NE;
6952       }
6953     }
6954     return CacheEntry = ExprError();
6955   }
6956 };
6957 }
6958
6959 ExprResult
6960 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
6961                                 llvm::function_ref<ExprResult(Expr *)> Filter) {
6962   // If the current evaluation context indicates there are uncorrected typos
6963   // and the current expression isn't guaranteed to not have typos, try to
6964   // resolve any TypoExpr nodes that might be in the expression.
6965   if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
6966       (E->isTypeDependent() || E->isValueDependent() ||
6967        E->isInstantiationDependent())) {
6968     auto TyposInContext = ExprEvalContexts.back().NumTypos;
6969     assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
6970     ExprEvalContexts.back().NumTypos = ~0U;
6971     auto TyposResolved = DelayedTypos.size();
6972     auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
6973     ExprEvalContexts.back().NumTypos = TyposInContext;
6974     TyposResolved -= DelayedTypos.size();
6975     if (Result.isInvalid() || Result.get() != E) {
6976       ExprEvalContexts.back().NumTypos -= TyposResolved;
6977       return Result;
6978     }
6979     assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
6980   }
6981   return E;
6982 }
6983
6984 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
6985                                      bool DiscardedValue,
6986                                      bool IsConstexpr, 
6987                                      bool IsLambdaInitCaptureInitializer) {
6988   ExprResult FullExpr = FE;
6989
6990   if (!FullExpr.get())
6991     return ExprError();
6992  
6993   // If we are an init-expression in a lambdas init-capture, we should not 
6994   // diagnose an unexpanded pack now (will be diagnosed once lambda-expr 
6995   // containing full-expression is done).
6996   // template<class ... Ts> void test(Ts ... t) {
6997   //   test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
6998   //     return a;
6999   //   }() ...);
7000   // }
7001   // FIXME: This is a hack. It would be better if we pushed the lambda scope
7002   // when we parse the lambda introducer, and teach capturing (but not
7003   // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7004   // corresponding class yet (that is, have LambdaScopeInfo either represent a
7005   // lambda where we've entered the introducer but not the body, or represent a
7006   // lambda where we've entered the body, depending on where the
7007   // parser/instantiation has got to).
7008   if (!IsLambdaInitCaptureInitializer && 
7009       DiagnoseUnexpandedParameterPack(FullExpr.get()))
7010     return ExprError();
7011
7012   // Top-level expressions default to 'id' when we're in a debugger.
7013   if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
7014       FullExpr.get()->getType() == Context.UnknownAnyTy) {
7015     FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7016     if (FullExpr.isInvalid())
7017       return ExprError();
7018   }
7019
7020   if (DiscardedValue) {
7021     FullExpr = CheckPlaceholderExpr(FullExpr.get());
7022     if (FullExpr.isInvalid())
7023       return ExprError();
7024
7025     FullExpr = IgnoredValueConversions(FullExpr.get());
7026     if (FullExpr.isInvalid())
7027       return ExprError();
7028   }
7029
7030   FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7031   if (FullExpr.isInvalid())
7032     return ExprError();
7033
7034   CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7035
7036   // At the end of this full expression (which could be a deeply nested 
7037   // lambda), if there is a potential capture within the nested lambda, 
7038   // have the outer capture-able lambda try and capture it.
7039   // Consider the following code:
7040   // void f(int, int);
7041   // void f(const int&, double);
7042   // void foo() {   
7043   //  const int x = 10, y = 20;
7044   //  auto L = [=](auto a) {
7045   //      auto M = [=](auto b) {
7046   //         f(x, b); <-- requires x to be captured by L and M
7047   //         f(y, a); <-- requires y to be captured by L, but not all Ms
7048   //      };
7049   //   };
7050   // }
7051
7052   // FIXME: Also consider what happens for something like this that involves 
7053   // the gnu-extension statement-expressions or even lambda-init-captures:   
7054   //   void f() {
7055   //     const int n = 0;
7056   //     auto L =  [&](auto a) {
7057   //       +n + ({ 0; a; });
7058   //     };
7059   //   }
7060   // 
7061   // Here, we see +n, and then the full-expression 0; ends, so we don't 
7062   // capture n (and instead remove it from our list of potential captures), 
7063   // and then the full-expression +n + ({ 0; }); ends, but it's too late 
7064   // for us to see that we need to capture n after all.
7065
7066   LambdaScopeInfo *const CurrentLSI =
7067       getCurLambda(/*IgnoreCapturedRegions=*/true);
7068   // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer 
7069   // even if CurContext is not a lambda call operator. Refer to that Bug Report
7070   // for an example of the code that might cause this asynchrony.  
7071   // By ensuring we are in the context of a lambda's call operator
7072   // we can fix the bug (we only need to check whether we need to capture
7073   // if we are within a lambda's body); but per the comments in that 
7074   // PR, a proper fix would entail :
7075   //   "Alternative suggestion:
7076   //   - Add to Sema an integer holding the smallest (outermost) scope 
7077   //     index that we are *lexically* within, and save/restore/set to 
7078   //     FunctionScopes.size() in InstantiatingTemplate's 
7079   //     constructor/destructor.
7080   //  - Teach the handful of places that iterate over FunctionScopes to 
7081   //    stop at the outermost enclosing lexical scope."
7082   DeclContext *DC = CurContext;
7083   while (DC && isa<CapturedDecl>(DC))
7084     DC = DC->getParent();
7085   const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7086   if (IsInLambdaDeclContext && CurrentLSI &&
7087       CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7088     CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7089                                                               *this);
7090   return MaybeCreateExprWithCleanups(FullExpr);
7091 }
7092
7093 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7094   if (!FullStmt) return StmtError();
7095
7096   return MaybeCreateStmtWithCleanups(FullStmt);
7097 }
7098
7099 Sema::IfExistsResult 
7100 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7101                                    CXXScopeSpec &SS,
7102                                    const DeclarationNameInfo &TargetNameInfo) {
7103   DeclarationName TargetName = TargetNameInfo.getName();
7104   if (!TargetName)
7105     return IER_DoesNotExist;
7106   
7107   // If the name itself is dependent, then the result is dependent.
7108   if (TargetName.isDependentName())
7109     return IER_Dependent;
7110   
7111   // Do the redeclaration lookup in the current scope.
7112   LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7113                  Sema::NotForRedeclaration);
7114   LookupParsedName(R, S, &SS);
7115   R.suppressDiagnostics();
7116   
7117   switch (R.getResultKind()) {
7118   case LookupResult::Found:
7119   case LookupResult::FoundOverloaded:
7120   case LookupResult::FoundUnresolvedValue:
7121   case LookupResult::Ambiguous:
7122     return IER_Exists;
7123     
7124   case LookupResult::NotFound:
7125     return IER_DoesNotExist;
7126     
7127   case LookupResult::NotFoundInCurrentInstantiation:
7128     return IER_Dependent;
7129   }
7130
7131   llvm_unreachable("Invalid LookupResult Kind!");
7132 }
7133
7134 Sema::IfExistsResult 
7135 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7136                                    bool IsIfExists, CXXScopeSpec &SS,
7137                                    UnqualifiedId &Name) {
7138   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7139   
7140   // Check for unexpanded parameter packs.
7141   SmallVector<UnexpandedParameterPack, 4> Unexpanded;
7142   collectUnexpandedParameterPacks(SS, Unexpanded);
7143   collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
7144   if (!Unexpanded.empty()) {
7145     DiagnoseUnexpandedParameterPacks(KeywordLoc,
7146                                      IsIfExists? UPPC_IfExists 
7147                                                : UPPC_IfNotExists, 
7148                                      Unexpanded);
7149     return IER_Error;
7150   }
7151   
7152   return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7153 }