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