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