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