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