SemaExprCXX.cpp revision 429bb276991ff2dbc7c5b438828b9b7737cb15eb
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/TemplateDeduction.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/CXXInheritance.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/Preprocessor.h"
30#include "llvm/ADT/STLExtras.h"
31using namespace clang;
32using namespace sema;
33
34ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
35                                   IdentifierInfo &II,
36                                   SourceLocation NameLoc,
37                                   Scope *S, CXXScopeSpec &SS,
38                                   ParsedType ObjectTypePtr,
39                                   bool EnteringContext) {
40  // Determine where to perform name lookup.
41
42  // FIXME: This area of the standard is very messy, and the current
43  // wording is rather unclear about which scopes we search for the
44  // destructor name; see core issues 399 and 555. Issue 399 in
45  // particular shows where the current description of destructor name
46  // lookup is completely out of line with existing practice, e.g.,
47  // this appears to be ill-formed:
48  //
49  //   namespace N {
50  //     template <typename T> struct S {
51  //       ~S();
52  //     };
53  //   }
54  //
55  //   void f(N::S<int>* s) {
56  //     s->N::S<int>::~S();
57  //   }
58  //
59  // See also PR6358 and PR6359.
60  // For this reason, we're currently only doing the C++03 version of this
61  // code; the C++0x version has to wait until we get a proper spec.
62  QualType SearchType;
63  DeclContext *LookupCtx = 0;
64  bool isDependent = false;
65  bool LookInScope = false;
66
67  // If we have an object type, it's because we are in a
68  // pseudo-destructor-expression or a member access expression, and
69  // we know what type we're looking for.
70  if (ObjectTypePtr)
71    SearchType = GetTypeFromParser(ObjectTypePtr);
72
73  if (SS.isSet()) {
74    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
75
76    bool AlreadySearched = false;
77    bool LookAtPrefix = true;
78    // C++ [basic.lookup.qual]p6:
79    //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
80    //   the type-names are looked up as types in the scope designated by the
81    //   nested-name-specifier. In a qualified-id of the form:
82    //
83    //     ::[opt] nested-name-specifier  ~ class-name
84    //
85    //   where the nested-name-specifier designates a namespace scope, and in
86    //   a qualified-id of the form:
87    //
88    //     ::opt nested-name-specifier class-name ::  ~ class-name
89    //
90    //   the class-names are looked up as types in the scope designated by
91    //   the nested-name-specifier.
92    //
93    // Here, we check the first case (completely) and determine whether the
94    // code below is permitted to look at the prefix of the
95    // nested-name-specifier.
96    DeclContext *DC = computeDeclContext(SS, EnteringContext);
97    if (DC && DC->isFileContext()) {
98      AlreadySearched = true;
99      LookupCtx = DC;
100      isDependent = false;
101    } else if (DC && isa<CXXRecordDecl>(DC))
102      LookAtPrefix = false;
103
104    // The second case from the C++03 rules quoted further above.
105    NestedNameSpecifier *Prefix = 0;
106    if (AlreadySearched) {
107      // Nothing left to do.
108    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
109      CXXScopeSpec PrefixSS;
110      PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
111      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
112      isDependent = isDependentScopeSpecifier(PrefixSS);
113    } else if (ObjectTypePtr) {
114      LookupCtx = computeDeclContext(SearchType);
115      isDependent = SearchType->isDependentType();
116    } else {
117      LookupCtx = computeDeclContext(SS, EnteringContext);
118      isDependent = LookupCtx && LookupCtx->isDependentContext();
119    }
120
121    LookInScope = false;
122  } else if (ObjectTypePtr) {
123    // C++ [basic.lookup.classref]p3:
124    //   If the unqualified-id is ~type-name, the type-name is looked up
125    //   in the context of the entire postfix-expression. If the type T
126    //   of the object expression is of a class type C, the type-name is
127    //   also looked up in the scope of class C. At least one of the
128    //   lookups shall find a name that refers to (possibly
129    //   cv-qualified) T.
130    LookupCtx = computeDeclContext(SearchType);
131    isDependent = SearchType->isDependentType();
132    assert((isDependent || !SearchType->isIncompleteType()) &&
133           "Caller should have completed object type");
134
135    LookInScope = true;
136  } else {
137    // Perform lookup into the current scope (only).
138    LookInScope = true;
139  }
140
141  TypeDecl *NonMatchingTypeDecl = 0;
142  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
143  for (unsigned Step = 0; Step != 2; ++Step) {
144    // Look for the name first in the computed lookup context (if we
145    // have one) and, if that fails to find a match, in the scope (if
146    // we're allowed to look there).
147    Found.clear();
148    if (Step == 0 && LookupCtx)
149      LookupQualifiedName(Found, LookupCtx);
150    else if (Step == 1 && LookInScope && S)
151      LookupName(Found, S);
152    else
153      continue;
154
155    // FIXME: Should we be suppressing ambiguities here?
156    if (Found.isAmbiguous())
157      return ParsedType();
158
159    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
160      QualType T = Context.getTypeDeclType(Type);
161
162      if (SearchType.isNull() || SearchType->isDependentType() ||
163          Context.hasSameUnqualifiedType(T, SearchType)) {
164        // We found our type!
165
166        return ParsedType::make(T);
167      }
168
169      if (!SearchType.isNull())
170        NonMatchingTypeDecl = Type;
171    }
172
173    // If the name that we found is a class template name, and it is
174    // the same name as the template name in the last part of the
175    // nested-name-specifier (if present) or the object type, then
176    // this is the destructor for that class.
177    // FIXME: This is a workaround until we get real drafting for core
178    // issue 399, for which there isn't even an obvious direction.
179    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
180      QualType MemberOfType;
181      if (SS.isSet()) {
182        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
183          // Figure out the type of the context, if it has one.
184          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
185            MemberOfType = Context.getTypeDeclType(Record);
186        }
187      }
188      if (MemberOfType.isNull())
189        MemberOfType = SearchType;
190
191      if (MemberOfType.isNull())
192        continue;
193
194      // We're referring into a class template specialization. If the
195      // class template we found is the same as the template being
196      // specialized, we found what we are looking for.
197      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
198        if (ClassTemplateSpecializationDecl *Spec
199              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
200          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
201                Template->getCanonicalDecl())
202            return ParsedType::make(MemberOfType);
203        }
204
205        continue;
206      }
207
208      // We're referring to an unresolved class template
209      // specialization. Determine whether we class template we found
210      // is the same as the template being specialized or, if we don't
211      // know which template is being specialized, that it at least
212      // has the same name.
213      if (const TemplateSpecializationType *SpecType
214            = MemberOfType->getAs<TemplateSpecializationType>()) {
215        TemplateName SpecName = SpecType->getTemplateName();
216
217        // The class template we found is the same template being
218        // specialized.
219        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
220          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
221            return ParsedType::make(MemberOfType);
222
223          continue;
224        }
225
226        // The class template we found has the same name as the
227        // (dependent) template name being specialized.
228        if (DependentTemplateName *DepTemplate
229                                    = SpecName.getAsDependentTemplateName()) {
230          if (DepTemplate->isIdentifier() &&
231              DepTemplate->getIdentifier() == Template->getIdentifier())
232            return ParsedType::make(MemberOfType);
233
234          continue;
235        }
236      }
237    }
238  }
239
240  if (isDependent) {
241    // We didn't find our type, but that's okay: it's dependent
242    // anyway.
243
244    // FIXME: What if we have no nested-name-specifier?
245    QualType T = CheckTypenameType(ETK_None, SourceLocation(),
246                                   SS.getWithLocInContext(Context),
247                                   II, NameLoc);
248    return ParsedType::make(T);
249  }
250
251  if (NonMatchingTypeDecl) {
252    QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
253    Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
254      << T << SearchType;
255    Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
256      << T;
257  } else if (ObjectTypePtr)
258    Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
259      << &II;
260  else
261    Diag(NameLoc, diag::err_destructor_class_name);
262
263  return ParsedType();
264}
265
266/// \brief Build a C++ typeid expression with a type operand.
267ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
268                                SourceLocation TypeidLoc,
269                                TypeSourceInfo *Operand,
270                                SourceLocation RParenLoc) {
271  // C++ [expr.typeid]p4:
272  //   The top-level cv-qualifiers of the lvalue expression or the type-id
273  //   that is the operand of typeid are always ignored.
274  //   If the type of the type-id is a class type or a reference to a class
275  //   type, the class shall be completely-defined.
276  Qualifiers Quals;
277  QualType T
278    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
279                                      Quals);
280  if (T->getAs<RecordType>() &&
281      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
282    return ExprError();
283
284  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
285                                           Operand,
286                                           SourceRange(TypeidLoc, RParenLoc)));
287}
288
289/// \brief Build a C++ typeid expression with an expression operand.
290ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
291                                SourceLocation TypeidLoc,
292                                Expr *E,
293                                SourceLocation RParenLoc) {
294  bool isUnevaluatedOperand = true;
295  if (E && !E->isTypeDependent()) {
296    QualType T = E->getType();
297    if (const RecordType *RecordT = T->getAs<RecordType>()) {
298      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
299      // C++ [expr.typeid]p3:
300      //   [...] If the type of the expression is a class type, the class
301      //   shall be completely-defined.
302      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
303        return ExprError();
304
305      // C++ [expr.typeid]p3:
306      //   When typeid is applied to an expression other than an glvalue of a
307      //   polymorphic class type [...] [the] expression is an unevaluated
308      //   operand. [...]
309      if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
310        isUnevaluatedOperand = false;
311
312        // We require a vtable to query the type at run time.
313        MarkVTableUsed(TypeidLoc, RecordD);
314      }
315    }
316
317    // C++ [expr.typeid]p4:
318    //   [...] If the type of the type-id is a reference to a possibly
319    //   cv-qualified type, the result of the typeid expression refers to a
320    //   std::type_info object representing the cv-unqualified referenced
321    //   type.
322    Qualifiers Quals;
323    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
324    if (!Context.hasSameType(T, UnqualT)) {
325      T = UnqualT;
326      E = ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)).take();
327    }
328  }
329
330  // If this is an unevaluated operand, clear out the set of
331  // declaration references we have been computing and eliminate any
332  // temporaries introduced in its computation.
333  if (isUnevaluatedOperand)
334    ExprEvalContexts.back().Context = Unevaluated;
335
336  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
337                                           E,
338                                           SourceRange(TypeidLoc, RParenLoc)));
339}
340
341/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
342ExprResult
343Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
344                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
345  // Find the std::type_info type.
346  if (!getStdNamespace())
347    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
348
349  if (!CXXTypeInfoDecl) {
350    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
351    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
352    LookupQualifiedName(R, getStdNamespace());
353    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
354    if (!CXXTypeInfoDecl)
355      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
356  }
357
358  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
359
360  if (isType) {
361    // The operand is a type; handle it as such.
362    TypeSourceInfo *TInfo = 0;
363    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
364                                   &TInfo);
365    if (T.isNull())
366      return ExprError();
367
368    if (!TInfo)
369      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
370
371    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
372  }
373
374  // The operand is an expression.
375  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
376}
377
378/// Retrieve the UuidAttr associated with QT.
379static UuidAttr *GetUuidAttrOfType(QualType QT) {
380  // Optionally remove one level of pointer, reference or array indirection.
381  const Type *Ty = QT.getTypePtr();;
382  if (QT->isPointerType() || QT->isReferenceType())
383    Ty = QT->getPointeeType().getTypePtr();
384  else if (QT->isArrayType())
385    Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
386
387  // Loop all class definition and declaration looking for an uuid attribute.
388  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
389  while (RD) {
390    if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
391      return Uuid;
392    RD = RD->getPreviousDeclaration();
393  }
394  return 0;
395}
396
397/// \brief Build a Microsoft __uuidof expression with a type operand.
398ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
399                                SourceLocation TypeidLoc,
400                                TypeSourceInfo *Operand,
401                                SourceLocation RParenLoc) {
402  if (!Operand->getType()->isDependentType()) {
403    if (!GetUuidAttrOfType(Operand->getType()))
404      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
405  }
406
407  // FIXME: add __uuidof semantic analysis for type operand.
408  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
409                                           Operand,
410                                           SourceRange(TypeidLoc, RParenLoc)));
411}
412
413/// \brief Build a Microsoft __uuidof expression with an expression operand.
414ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
415                                SourceLocation TypeidLoc,
416                                Expr *E,
417                                SourceLocation RParenLoc) {
418  if (!E->getType()->isDependentType()) {
419    if (!GetUuidAttrOfType(E->getType()) &&
420        !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
421      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
422  }
423  // FIXME: add __uuidof semantic analysis for type operand.
424  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
425                                           E,
426                                           SourceRange(TypeidLoc, RParenLoc)));
427}
428
429/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
430ExprResult
431Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
432                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
433  // If MSVCGuidDecl has not been cached, do the lookup.
434  if (!MSVCGuidDecl) {
435    IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
436    LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
437    LookupQualifiedName(R, Context.getTranslationUnitDecl());
438    MSVCGuidDecl = R.getAsSingle<RecordDecl>();
439    if (!MSVCGuidDecl)
440      return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
441  }
442
443  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
444
445  if (isType) {
446    // The operand is a type; handle it as such.
447    TypeSourceInfo *TInfo = 0;
448    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
449                                   &TInfo);
450    if (T.isNull())
451      return ExprError();
452
453    if (!TInfo)
454      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
455
456    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
457  }
458
459  // The operand is an expression.
460  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
461}
462
463/// ActOnCXXBoolLiteral - Parse {true,false} literals.
464ExprResult
465Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
466  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
467         "Unknown C++ Boolean value!");
468  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
469                                                Context.BoolTy, OpLoc));
470}
471
472/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
473ExprResult
474Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
475  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
476}
477
478/// ActOnCXXThrow - Parse throw expressions.
479ExprResult
480Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
481  // Don't report an error if 'throw' is used in system headers.
482  if (!getLangOptions().CXXExceptions &&
483      !getSourceManager().isInSystemHeader(OpLoc))
484    Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
485
486  if (Ex && !Ex->isTypeDependent()) {
487    ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex);
488    if (ExRes.isInvalid())
489      return ExprError();
490    Ex = ExRes.take();
491  }
492  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
493}
494
495/// CheckCXXThrowOperand - Validate the operand of a throw.
496ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E) {
497  // C++ [except.throw]p3:
498  //   A throw-expression initializes a temporary object, called the exception
499  //   object, the type of which is determined by removing any top-level
500  //   cv-qualifiers from the static type of the operand of throw and adjusting
501  //   the type from "array of T" or "function returning T" to "pointer to T"
502  //   or "pointer to function returning T", [...]
503  if (E->getType().hasQualifiers())
504    E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
505                      CastCategory(E)).take();
506
507  ExprResult Res = DefaultFunctionArrayConversion(E);
508  if (Res.isInvalid())
509    return ExprError();
510  E = Res.take();
511
512  //   If the type of the exception would be an incomplete type or a pointer
513  //   to an incomplete type other than (cv) void the program is ill-formed.
514  QualType Ty = E->getType();
515  bool isPointer = false;
516  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
517    Ty = Ptr->getPointeeType();
518    isPointer = true;
519  }
520  if (!isPointer || !Ty->isVoidType()) {
521    if (RequireCompleteType(ThrowLoc, Ty,
522                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
523                                            : diag::err_throw_incomplete)
524                              << E->getSourceRange()))
525      return ExprError();
526
527    if (RequireNonAbstractType(ThrowLoc, E->getType(),
528                               PDiag(diag::err_throw_abstract_type)
529                                 << E->getSourceRange()))
530      return ExprError();
531  }
532
533  // Initialize the exception result.  This implicitly weeds out
534  // abstract types or types with inaccessible copy constructors.
535  const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
536
537  // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
538  InitializedEntity Entity =
539      InitializedEntity::InitializeException(ThrowLoc, E->getType(),
540                                             /*NRVO=*/false);
541  Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
542                                        QualType(), E);
543  if (Res.isInvalid())
544    return ExprError();
545  E = Res.take();
546
547  // If the exception has class type, we need additional handling.
548  const RecordType *RecordTy = Ty->getAs<RecordType>();
549  if (!RecordTy)
550    return Owned(E);
551  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
552
553  // If we are throwing a polymorphic class type or pointer thereof,
554  // exception handling will make use of the vtable.
555  MarkVTableUsed(ThrowLoc, RD);
556
557  // If a pointer is thrown, the referenced object will not be destroyed.
558  if (isPointer)
559    return Owned(E);
560
561  // If the class has a non-trivial destructor, we must be able to call it.
562  if (RD->hasTrivialDestructor())
563    return Owned(E);
564
565  CXXDestructorDecl *Destructor
566    = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
567  if (!Destructor)
568    return Owned(E);
569
570  MarkDeclarationReferenced(E->getExprLoc(), Destructor);
571  CheckDestructorAccess(E->getExprLoc(), Destructor,
572                        PDiag(diag::err_access_dtor_exception) << Ty);
573  return Owned(E);
574}
575
576CXXMethodDecl *Sema::tryCaptureCXXThis() {
577  // Ignore block scopes: we can capture through them.
578  // Ignore nested enum scopes: we'll diagnose non-constant expressions
579  // where they're invalid, and other uses are legitimate.
580  // Don't ignore nested class scopes: you can't use 'this' in a local class.
581  DeclContext *DC = CurContext;
582  while (true) {
583    if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
584    else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
585    else break;
586  }
587
588  // If we're not in an instance method, error out.
589  CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
590  if (!method || !method->isInstance())
591    return 0;
592
593  // Mark that we're closing on 'this' in all the block scopes, if applicable.
594  for (unsigned idx = FunctionScopes.size() - 1;
595       isa<BlockScopeInfo>(FunctionScopes[idx]);
596       --idx)
597    cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
598
599  return method;
600}
601
602ExprResult Sema::ActOnCXXThis(SourceLocation loc) {
603  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
604  /// is a non-lvalue expression whose value is the address of the object for
605  /// which the function is called.
606
607  CXXMethodDecl *method = tryCaptureCXXThis();
608  if (!method) return Diag(loc, diag::err_invalid_this_use);
609
610  return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
611                                         /*isImplicit=*/false));
612}
613
614ExprResult
615Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
616                                SourceLocation LParenLoc,
617                                MultiExprArg exprs,
618                                SourceLocation RParenLoc) {
619  if (!TypeRep)
620    return ExprError();
621
622  TypeSourceInfo *TInfo;
623  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
624  if (!TInfo)
625    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
626
627  return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
628}
629
630/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
631/// Can be interpreted either as function-style casting ("int(x)")
632/// or class type construction ("ClassType(x,y,z)")
633/// or creation of a value-initialized type ("int()").
634ExprResult
635Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
636                                SourceLocation LParenLoc,
637                                MultiExprArg exprs,
638                                SourceLocation RParenLoc) {
639  QualType Ty = TInfo->getType();
640  unsigned NumExprs = exprs.size();
641  Expr **Exprs = (Expr**)exprs.get();
642  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
643  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
644
645  if (Ty->isDependentType() ||
646      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
647    exprs.release();
648
649    return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
650                                                    LParenLoc,
651                                                    Exprs, NumExprs,
652                                                    RParenLoc));
653  }
654
655  if (Ty->isArrayType())
656    return ExprError(Diag(TyBeginLoc,
657                          diag::err_value_init_for_array_type) << FullRange);
658  if (!Ty->isVoidType() &&
659      RequireCompleteType(TyBeginLoc, Ty,
660                          PDiag(diag::err_invalid_incomplete_type_use)
661                            << FullRange))
662    return ExprError();
663
664  if (RequireNonAbstractType(TyBeginLoc, Ty,
665                             diag::err_allocation_of_abstract_type))
666    return ExprError();
667
668
669  // C++ [expr.type.conv]p1:
670  // If the expression list is a single expression, the type conversion
671  // expression is equivalent (in definedness, and if defined in meaning) to the
672  // corresponding cast expression.
673  //
674  if (NumExprs == 1) {
675    CastKind Kind = CK_Invalid;
676    ExprValueKind VK = VK_RValue;
677    CXXCastPath BasePath;
678    ExprResult CastExpr =
679      CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
680                     Kind, VK, BasePath,
681                     /*FunctionalStyle=*/true);
682    if (CastExpr.isInvalid())
683      return ExprError();
684    Exprs[0] = CastExpr.take();
685
686    exprs.release();
687
688    return Owned(CXXFunctionalCastExpr::Create(Context,
689                                               Ty.getNonLValueExprType(Context),
690                                               VK, TInfo, TyBeginLoc, Kind,
691                                               Exprs[0], &BasePath,
692                                               RParenLoc));
693  }
694
695  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
696  InitializationKind Kind
697    = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
698                                                  LParenLoc, RParenLoc)
699               : InitializationKind::CreateValue(TyBeginLoc,
700                                                 LParenLoc, RParenLoc);
701  InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
702  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
703
704  // FIXME: Improve AST representation?
705  return move(Result);
706}
707
708/// doesUsualArrayDeleteWantSize - Answers whether the usual
709/// operator delete[] for the given type has a size_t parameter.
710static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
711                                         QualType allocType) {
712  const RecordType *record =
713    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
714  if (!record) return false;
715
716  // Try to find an operator delete[] in class scope.
717
718  DeclarationName deleteName =
719    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
720  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
721  S.LookupQualifiedName(ops, record->getDecl());
722
723  // We're just doing this for information.
724  ops.suppressDiagnostics();
725
726  // Very likely: there's no operator delete[].
727  if (ops.empty()) return false;
728
729  // If it's ambiguous, it should be illegal to call operator delete[]
730  // on this thing, so it doesn't matter if we allocate extra space or not.
731  if (ops.isAmbiguous()) return false;
732
733  LookupResult::Filter filter = ops.makeFilter();
734  while (filter.hasNext()) {
735    NamedDecl *del = filter.next()->getUnderlyingDecl();
736
737    // C++0x [basic.stc.dynamic.deallocation]p2:
738    //   A template instance is never a usual deallocation function,
739    //   regardless of its signature.
740    if (isa<FunctionTemplateDecl>(del)) {
741      filter.erase();
742      continue;
743    }
744
745    // C++0x [basic.stc.dynamic.deallocation]p2:
746    //   If class T does not declare [an operator delete[] with one
747    //   parameter] but does declare a member deallocation function
748    //   named operator delete[] with exactly two parameters, the
749    //   second of which has type std::size_t, then this function
750    //   is a usual deallocation function.
751    if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
752      filter.erase();
753      continue;
754    }
755  }
756  filter.done();
757
758  if (!ops.isSingleResult()) return false;
759
760  const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
761  return (del->getNumParams() == 2);
762}
763
764/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
765/// @code new (memory) int[size][4] @endcode
766/// or
767/// @code ::new Foo(23, "hello") @endcode
768/// For the interpretation of this heap of arguments, consult the base version.
769ExprResult
770Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
771                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
772                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
773                  Declarator &D, SourceLocation ConstructorLParen,
774                  MultiExprArg ConstructorArgs,
775                  SourceLocation ConstructorRParen) {
776  bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
777
778  Expr *ArraySize = 0;
779  // If the specified type is an array, unwrap it and save the expression.
780  if (D.getNumTypeObjects() > 0 &&
781      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
782    DeclaratorChunk &Chunk = D.getTypeObject(0);
783    if (TypeContainsAuto)
784      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
785        << D.getSourceRange());
786    if (Chunk.Arr.hasStatic)
787      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
788        << D.getSourceRange());
789    if (!Chunk.Arr.NumElts)
790      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
791        << D.getSourceRange());
792
793    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
794    D.DropFirstTypeObject();
795  }
796
797  // Every dimension shall be of constant size.
798  if (ArraySize) {
799    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
800      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
801        break;
802
803      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
804      if (Expr *NumElts = (Expr *)Array.NumElts) {
805        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
806            !NumElts->isIntegerConstantExpr(Context)) {
807          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
808            << NumElts->getSourceRange();
809          return ExprError();
810        }
811      }
812    }
813  }
814
815  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
816                                               /*AllowAuto=*/true);
817  QualType AllocType = TInfo->getType();
818  if (D.isInvalidType())
819    return ExprError();
820
821  return BuildCXXNew(StartLoc, UseGlobal,
822                     PlacementLParen,
823                     move(PlacementArgs),
824                     PlacementRParen,
825                     TypeIdParens,
826                     AllocType,
827                     TInfo,
828                     ArraySize,
829                     ConstructorLParen,
830                     move(ConstructorArgs),
831                     ConstructorRParen,
832                     TypeContainsAuto);
833}
834
835ExprResult
836Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
837                  SourceLocation PlacementLParen,
838                  MultiExprArg PlacementArgs,
839                  SourceLocation PlacementRParen,
840                  SourceRange TypeIdParens,
841                  QualType AllocType,
842                  TypeSourceInfo *AllocTypeInfo,
843                  Expr *ArraySize,
844                  SourceLocation ConstructorLParen,
845                  MultiExprArg ConstructorArgs,
846                  SourceLocation ConstructorRParen,
847                  bool TypeMayContainAuto) {
848  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
849
850  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
851  if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
852    if (ConstructorArgs.size() == 0)
853      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
854                       << AllocType << TypeRange);
855    if (ConstructorArgs.size() != 1) {
856      Expr *FirstBad = ConstructorArgs.get()[1];
857      return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
858                            diag::err_auto_new_ctor_multiple_expressions)
859                       << AllocType << TypeRange);
860    }
861    TypeSourceInfo *DeducedType = 0;
862    if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
863      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
864                       << AllocType
865                       << ConstructorArgs.get()[0]->getType()
866                       << TypeRange
867                       << ConstructorArgs.get()[0]->getSourceRange());
868    if (!DeducedType)
869      return ExprError();
870
871    AllocTypeInfo = DeducedType;
872    AllocType = AllocTypeInfo->getType();
873  }
874
875  // Per C++0x [expr.new]p5, the type being constructed may be a
876  // typedef of an array type.
877  if (!ArraySize) {
878    if (const ConstantArrayType *Array
879                              = Context.getAsConstantArrayType(AllocType)) {
880      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
881                                         Context.getSizeType(),
882                                         TypeRange.getEnd());
883      AllocType = Array->getElementType();
884    }
885  }
886
887  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
888    return ExprError();
889
890  QualType ResultType = Context.getPointerType(AllocType);
891
892  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
893  //   or enumeration type with a non-negative value."
894  if (ArraySize && !ArraySize->isTypeDependent()) {
895
896    QualType SizeType = ArraySize->getType();
897
898    ExprResult ConvertedSize
899      = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
900                                       PDiag(diag::err_array_size_not_integral),
901                                     PDiag(diag::err_array_size_incomplete_type)
902                                       << ArraySize->getSourceRange(),
903                               PDiag(diag::err_array_size_explicit_conversion),
904                                       PDiag(diag::note_array_size_conversion),
905                               PDiag(diag::err_array_size_ambiguous_conversion),
906                                       PDiag(diag::note_array_size_conversion),
907                          PDiag(getLangOptions().CPlusPlus0x? 0
908                                            : diag::ext_array_size_conversion));
909    if (ConvertedSize.isInvalid())
910      return ExprError();
911
912    ArraySize = ConvertedSize.take();
913    SizeType = ArraySize->getType();
914    if (!SizeType->isIntegralOrUnscopedEnumerationType())
915      return ExprError();
916
917    // Let's see if this is a constant < 0. If so, we reject it out of hand.
918    // We don't care about special rules, so we tell the machinery it's not
919    // evaluated - it gives us a result in more cases.
920    if (!ArraySize->isValueDependent()) {
921      llvm::APSInt Value;
922      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
923        if (Value < llvm::APSInt(
924                        llvm::APInt::getNullValue(Value.getBitWidth()),
925                                 Value.isUnsigned()))
926          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
927                                diag::err_typecheck_negative_array_size)
928            << ArraySize->getSourceRange());
929
930        if (!AllocType->isDependentType()) {
931          unsigned ActiveSizeBits
932            = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
933          if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
934            Diag(ArraySize->getSourceRange().getBegin(),
935                 diag::err_array_too_large)
936              << Value.toString(10)
937              << ArraySize->getSourceRange();
938            return ExprError();
939          }
940        }
941      } else if (TypeIdParens.isValid()) {
942        // Can't have dynamic array size when the type-id is in parentheses.
943        Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
944          << ArraySize->getSourceRange()
945          << FixItHint::CreateRemoval(TypeIdParens.getBegin())
946          << FixItHint::CreateRemoval(TypeIdParens.getEnd());
947
948        TypeIdParens = SourceRange();
949      }
950    }
951
952    ArraySize = ImpCastExprToType(ArraySize, Context.getSizeType(),
953                      CK_IntegralCast).take();
954  }
955
956  FunctionDecl *OperatorNew = 0;
957  FunctionDecl *OperatorDelete = 0;
958  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
959  unsigned NumPlaceArgs = PlacementArgs.size();
960
961  if (!AllocType->isDependentType() &&
962      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
963      FindAllocationFunctions(StartLoc,
964                              SourceRange(PlacementLParen, PlacementRParen),
965                              UseGlobal, AllocType, ArraySize, PlaceArgs,
966                              NumPlaceArgs, OperatorNew, OperatorDelete))
967    return ExprError();
968
969  // If this is an array allocation, compute whether the usual array
970  // deallocation function for the type has a size_t parameter.
971  bool UsualArrayDeleteWantsSize = false;
972  if (ArraySize && !AllocType->isDependentType())
973    UsualArrayDeleteWantsSize
974      = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
975
976  llvm::SmallVector<Expr *, 8> AllPlaceArgs;
977  if (OperatorNew) {
978    // Add default arguments, if any.
979    const FunctionProtoType *Proto =
980      OperatorNew->getType()->getAs<FunctionProtoType>();
981    VariadicCallType CallType =
982      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
983
984    if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
985                               Proto, 1, PlaceArgs, NumPlaceArgs,
986                               AllPlaceArgs, CallType))
987      return ExprError();
988
989    NumPlaceArgs = AllPlaceArgs.size();
990    if (NumPlaceArgs > 0)
991      PlaceArgs = &AllPlaceArgs[0];
992  }
993
994  bool Init = ConstructorLParen.isValid();
995  // --- Choosing a constructor ---
996  CXXConstructorDecl *Constructor = 0;
997  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
998  unsigned NumConsArgs = ConstructorArgs.size();
999  ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
1000
1001  // Array 'new' can't have any initializers.
1002  if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
1003    SourceRange InitRange(ConsArgs[0]->getLocStart(),
1004                          ConsArgs[NumConsArgs - 1]->getLocEnd());
1005
1006    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1007    return ExprError();
1008  }
1009
1010  if (!AllocType->isDependentType() &&
1011      !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1012    // C++0x [expr.new]p15:
1013    //   A new-expression that creates an object of type T initializes that
1014    //   object as follows:
1015    InitializationKind Kind
1016    //     - If the new-initializer is omitted, the object is default-
1017    //       initialized (8.5); if no initialization is performed,
1018    //       the object has indeterminate value
1019      = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
1020    //     - Otherwise, the new-initializer is interpreted according to the
1021    //       initialization rules of 8.5 for direct-initialization.
1022             : InitializationKind::CreateDirect(TypeRange.getBegin(),
1023                                                ConstructorLParen,
1024                                                ConstructorRParen);
1025
1026    InitializedEntity Entity
1027      = InitializedEntity::InitializeNew(StartLoc, AllocType);
1028    InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
1029    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1030                                                move(ConstructorArgs));
1031    if (FullInit.isInvalid())
1032      return ExprError();
1033
1034    // FullInit is our initializer; walk through it to determine if it's a
1035    // constructor call, which CXXNewExpr handles directly.
1036    if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1037      if (CXXBindTemporaryExpr *Binder
1038            = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1039        FullInitExpr = Binder->getSubExpr();
1040      if (CXXConstructExpr *Construct
1041                    = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1042        Constructor = Construct->getConstructor();
1043        for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1044                                         AEnd = Construct->arg_end();
1045             A != AEnd; ++A)
1046          ConvertedConstructorArgs.push_back(*A);
1047      } else {
1048        // Take the converted initializer.
1049        ConvertedConstructorArgs.push_back(FullInit.release());
1050      }
1051    } else {
1052      // No initialization required.
1053    }
1054
1055    // Take the converted arguments and use them for the new expression.
1056    NumConsArgs = ConvertedConstructorArgs.size();
1057    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
1058  }
1059
1060  // Mark the new and delete operators as referenced.
1061  if (OperatorNew)
1062    MarkDeclarationReferenced(StartLoc, OperatorNew);
1063  if (OperatorDelete)
1064    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1065
1066  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
1067
1068  PlacementArgs.release();
1069  ConstructorArgs.release();
1070
1071  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1072                                        PlaceArgs, NumPlaceArgs, TypeIdParens,
1073                                        ArraySize, Constructor, Init,
1074                                        ConsArgs, NumConsArgs, OperatorDelete,
1075                                        UsualArrayDeleteWantsSize,
1076                                        ResultType, AllocTypeInfo,
1077                                        StartLoc,
1078                                        Init ? ConstructorRParen :
1079                                               TypeRange.getEnd(),
1080                                        ConstructorLParen, ConstructorRParen));
1081}
1082
1083/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1084/// in a new-expression.
1085/// dimension off and stores the size expression in ArraySize.
1086bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1087                              SourceRange R) {
1088  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1089  //   abstract class type or array thereof.
1090  if (AllocType->isFunctionType())
1091    return Diag(Loc, diag::err_bad_new_type)
1092      << AllocType << 0 << R;
1093  else if (AllocType->isReferenceType())
1094    return Diag(Loc, diag::err_bad_new_type)
1095      << AllocType << 1 << R;
1096  else if (!AllocType->isDependentType() &&
1097           RequireCompleteType(Loc, AllocType,
1098                               PDiag(diag::err_new_incomplete_type)
1099                                 << R))
1100    return true;
1101  else if (RequireNonAbstractType(Loc, AllocType,
1102                                  diag::err_allocation_of_abstract_type))
1103    return true;
1104  else if (AllocType->isVariablyModifiedType())
1105    return Diag(Loc, diag::err_variably_modified_new_type)
1106             << AllocType;
1107
1108  return false;
1109}
1110
1111/// \brief Determine whether the given function is a non-placement
1112/// deallocation function.
1113static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1114  if (FD->isInvalidDecl())
1115    return false;
1116
1117  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1118    return Method->isUsualDeallocationFunction();
1119
1120  return ((FD->getOverloadedOperator() == OO_Delete ||
1121           FD->getOverloadedOperator() == OO_Array_Delete) &&
1122          FD->getNumParams() == 1);
1123}
1124
1125/// FindAllocationFunctions - Finds the overloads of operator new and delete
1126/// that are appropriate for the allocation.
1127bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1128                                   bool UseGlobal, QualType AllocType,
1129                                   bool IsArray, Expr **PlaceArgs,
1130                                   unsigned NumPlaceArgs,
1131                                   FunctionDecl *&OperatorNew,
1132                                   FunctionDecl *&OperatorDelete) {
1133  // --- Choosing an allocation function ---
1134  // C++ 5.3.4p8 - 14 & 18
1135  // 1) If UseGlobal is true, only look in the global scope. Else, also look
1136  //   in the scope of the allocated class.
1137  // 2) If an array size is given, look for operator new[], else look for
1138  //   operator new.
1139  // 3) The first argument is always size_t. Append the arguments from the
1140  //   placement form.
1141
1142  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1143  // We don't care about the actual value of this argument.
1144  // FIXME: Should the Sema create the expression and embed it in the syntax
1145  // tree? Or should the consumer just recalculate the value?
1146  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1147                      Context.Target.getPointerWidth(0)),
1148                      Context.getSizeType(),
1149                      SourceLocation());
1150  AllocArgs[0] = &Size;
1151  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1152
1153  // C++ [expr.new]p8:
1154  //   If the allocated type is a non-array type, the allocation
1155  //   function's name is operator new and the deallocation function's
1156  //   name is operator delete. If the allocated type is an array
1157  //   type, the allocation function's name is operator new[] and the
1158  //   deallocation function's name is operator delete[].
1159  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1160                                        IsArray ? OO_Array_New : OO_New);
1161  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1162                                        IsArray ? OO_Array_Delete : OO_Delete);
1163
1164  QualType AllocElemType = Context.getBaseElementType(AllocType);
1165
1166  if (AllocElemType->isRecordType() && !UseGlobal) {
1167    CXXRecordDecl *Record
1168      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1169    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1170                          AllocArgs.size(), Record, /*AllowMissing=*/true,
1171                          OperatorNew))
1172      return true;
1173  }
1174  if (!OperatorNew) {
1175    // Didn't find a member overload. Look for a global one.
1176    DeclareGlobalNewDelete();
1177    DeclContext *TUDecl = Context.getTranslationUnitDecl();
1178    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1179                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1180                          OperatorNew))
1181      return true;
1182  }
1183
1184  // We don't need an operator delete if we're running under
1185  // -fno-exceptions.
1186  if (!getLangOptions().Exceptions) {
1187    OperatorDelete = 0;
1188    return false;
1189  }
1190
1191  // FindAllocationOverload can change the passed in arguments, so we need to
1192  // copy them back.
1193  if (NumPlaceArgs > 0)
1194    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
1195
1196  // C++ [expr.new]p19:
1197  //
1198  //   If the new-expression begins with a unary :: operator, the
1199  //   deallocation function's name is looked up in the global
1200  //   scope. Otherwise, if the allocated type is a class type T or an
1201  //   array thereof, the deallocation function's name is looked up in
1202  //   the scope of T. If this lookup fails to find the name, or if
1203  //   the allocated type is not a class type or array thereof, the
1204  //   deallocation function's name is looked up in the global scope.
1205  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1206  if (AllocElemType->isRecordType() && !UseGlobal) {
1207    CXXRecordDecl *RD
1208      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1209    LookupQualifiedName(FoundDelete, RD);
1210  }
1211  if (FoundDelete.isAmbiguous())
1212    return true; // FIXME: clean up expressions?
1213
1214  if (FoundDelete.empty()) {
1215    DeclareGlobalNewDelete();
1216    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1217  }
1218
1219  FoundDelete.suppressDiagnostics();
1220
1221  llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1222
1223  // Whether we're looking for a placement operator delete is dictated
1224  // by whether we selected a placement operator new, not by whether
1225  // we had explicit placement arguments.  This matters for things like
1226  //   struct A { void *operator new(size_t, int = 0); ... };
1227  //   A *a = new A()
1228  bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1229
1230  if (isPlacementNew) {
1231    // C++ [expr.new]p20:
1232    //   A declaration of a placement deallocation function matches the
1233    //   declaration of a placement allocation function if it has the
1234    //   same number of parameters and, after parameter transformations
1235    //   (8.3.5), all parameter types except the first are
1236    //   identical. [...]
1237    //
1238    // To perform this comparison, we compute the function type that
1239    // the deallocation function should have, and use that type both
1240    // for template argument deduction and for comparison purposes.
1241    //
1242    // FIXME: this comparison should ignore CC and the like.
1243    QualType ExpectedFunctionType;
1244    {
1245      const FunctionProtoType *Proto
1246        = OperatorNew->getType()->getAs<FunctionProtoType>();
1247
1248      llvm::SmallVector<QualType, 4> ArgTypes;
1249      ArgTypes.push_back(Context.VoidPtrTy);
1250      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1251        ArgTypes.push_back(Proto->getArgType(I));
1252
1253      FunctionProtoType::ExtProtoInfo EPI;
1254      EPI.Variadic = Proto->isVariadic();
1255
1256      ExpectedFunctionType
1257        = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1258                                  ArgTypes.size(), EPI);
1259    }
1260
1261    for (LookupResult::iterator D = FoundDelete.begin(),
1262                             DEnd = FoundDelete.end();
1263         D != DEnd; ++D) {
1264      FunctionDecl *Fn = 0;
1265      if (FunctionTemplateDecl *FnTmpl
1266            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1267        // Perform template argument deduction to try to match the
1268        // expected function type.
1269        TemplateDeductionInfo Info(Context, StartLoc);
1270        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1271          continue;
1272      } else
1273        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1274
1275      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1276        Matches.push_back(std::make_pair(D.getPair(), Fn));
1277    }
1278  } else {
1279    // C++ [expr.new]p20:
1280    //   [...] Any non-placement deallocation function matches a
1281    //   non-placement allocation function. [...]
1282    for (LookupResult::iterator D = FoundDelete.begin(),
1283                             DEnd = FoundDelete.end();
1284         D != DEnd; ++D) {
1285      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1286        if (isNonPlacementDeallocationFunction(Fn))
1287          Matches.push_back(std::make_pair(D.getPair(), Fn));
1288    }
1289  }
1290
1291  // C++ [expr.new]p20:
1292  //   [...] If the lookup finds a single matching deallocation
1293  //   function, that function will be called; otherwise, no
1294  //   deallocation function will be called.
1295  if (Matches.size() == 1) {
1296    OperatorDelete = Matches[0].second;
1297
1298    // C++0x [expr.new]p20:
1299    //   If the lookup finds the two-parameter form of a usual
1300    //   deallocation function (3.7.4.2) and that function, considered
1301    //   as a placement deallocation function, would have been
1302    //   selected as a match for the allocation function, the program
1303    //   is ill-formed.
1304    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1305        isNonPlacementDeallocationFunction(OperatorDelete)) {
1306      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1307        << SourceRange(PlaceArgs[0]->getLocStart(),
1308                       PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1309      Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1310        << DeleteName;
1311    } else {
1312      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1313                            Matches[0].first);
1314    }
1315  }
1316
1317  return false;
1318}
1319
1320/// FindAllocationOverload - Find an fitting overload for the allocation
1321/// function in the specified scope.
1322bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1323                                  DeclarationName Name, Expr** Args,
1324                                  unsigned NumArgs, DeclContext *Ctx,
1325                                  bool AllowMissing, FunctionDecl *&Operator) {
1326  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1327  LookupQualifiedName(R, Ctx);
1328  if (R.empty()) {
1329    if (AllowMissing)
1330      return false;
1331    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1332      << Name << Range;
1333  }
1334
1335  if (R.isAmbiguous())
1336    return true;
1337
1338  R.suppressDiagnostics();
1339
1340  OverloadCandidateSet Candidates(StartLoc);
1341  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1342       Alloc != AllocEnd; ++Alloc) {
1343    // Even member operator new/delete are implicitly treated as
1344    // static, so don't use AddMemberCandidate.
1345    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1346
1347    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1348      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1349                                   /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1350                                   Candidates,
1351                                   /*SuppressUserConversions=*/false);
1352      continue;
1353    }
1354
1355    FunctionDecl *Fn = cast<FunctionDecl>(D);
1356    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1357                         /*SuppressUserConversions=*/false);
1358  }
1359
1360  // Do the resolution.
1361  OverloadCandidateSet::iterator Best;
1362  switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1363  case OR_Success: {
1364    // Got one!
1365    FunctionDecl *FnDecl = Best->Function;
1366    MarkDeclarationReferenced(StartLoc, FnDecl);
1367    // The first argument is size_t, and the first parameter must be size_t,
1368    // too. This is checked on declaration and can be assumed. (It can't be
1369    // asserted on, though, since invalid decls are left in there.)
1370    // Watch out for variadic allocator function.
1371    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1372    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1373      ExprResult Result
1374        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1375                                                       Context,
1376                                                       FnDecl->getParamDecl(i)),
1377                                    SourceLocation(),
1378                                    Owned(Args[i]));
1379      if (Result.isInvalid())
1380        return true;
1381
1382      Args[i] = Result.takeAs<Expr>();
1383    }
1384    Operator = FnDecl;
1385    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1386    return false;
1387  }
1388
1389  case OR_No_Viable_Function:
1390    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1391      << Name << Range;
1392    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1393    return true;
1394
1395  case OR_Ambiguous:
1396    Diag(StartLoc, diag::err_ovl_ambiguous_call)
1397      << Name << Range;
1398    Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1399    return true;
1400
1401  case OR_Deleted: {
1402    Diag(StartLoc, diag::err_ovl_deleted_call)
1403      << Best->Function->isDeleted()
1404      << Name
1405      << getDeletedOrUnavailableSuffix(Best->Function)
1406      << Range;
1407    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1408    return true;
1409  }
1410  }
1411  assert(false && "Unreachable, bad result from BestViableFunction");
1412  return true;
1413}
1414
1415
1416/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1417/// delete. These are:
1418/// @code
1419///   // C++03:
1420///   void* operator new(std::size_t) throw(std::bad_alloc);
1421///   void* operator new[](std::size_t) throw(std::bad_alloc);
1422///   void operator delete(void *) throw();
1423///   void operator delete[](void *) throw();
1424///   // C++0x:
1425///   void* operator new(std::size_t);
1426///   void* operator new[](std::size_t);
1427///   void operator delete(void *);
1428///   void operator delete[](void *);
1429/// @endcode
1430/// C++0x operator delete is implicitly noexcept.
1431/// Note that the placement and nothrow forms of new are *not* implicitly
1432/// declared. Their use requires including \<new\>.
1433void Sema::DeclareGlobalNewDelete() {
1434  if (GlobalNewDeleteDeclared)
1435    return;
1436
1437  // C++ [basic.std.dynamic]p2:
1438  //   [...] The following allocation and deallocation functions (18.4) are
1439  //   implicitly declared in global scope in each translation unit of a
1440  //   program
1441  //
1442  //     C++03:
1443  //     void* operator new(std::size_t) throw(std::bad_alloc);
1444  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1445  //     void  operator delete(void*) throw();
1446  //     void  operator delete[](void*) throw();
1447  //     C++0x:
1448  //     void* operator new(std::size_t);
1449  //     void* operator new[](std::size_t);
1450  //     void  operator delete(void*);
1451  //     void  operator delete[](void*);
1452  //
1453  //   These implicit declarations introduce only the function names operator
1454  //   new, operator new[], operator delete, operator delete[].
1455  //
1456  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1457  // "std" or "bad_alloc" as necessary to form the exception specification.
1458  // However, we do not make these implicit declarations visible to name
1459  // lookup.
1460  // Note that the C++0x versions of operator delete are deallocation functions,
1461  // and thus are implicitly noexcept.
1462  if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
1463    // The "std::bad_alloc" class has not yet been declared, so build it
1464    // implicitly.
1465    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1466                                        getOrCreateStdNamespace(),
1467                                        SourceLocation(), SourceLocation(),
1468                                      &PP.getIdentifierTable().get("bad_alloc"),
1469                                        0);
1470    getStdBadAlloc()->setImplicit(true);
1471  }
1472
1473  GlobalNewDeleteDeclared = true;
1474
1475  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1476  QualType SizeT = Context.getSizeType();
1477  bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1478
1479  DeclareGlobalAllocationFunction(
1480      Context.DeclarationNames.getCXXOperatorName(OO_New),
1481      VoidPtr, SizeT, AssumeSaneOperatorNew);
1482  DeclareGlobalAllocationFunction(
1483      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1484      VoidPtr, SizeT, AssumeSaneOperatorNew);
1485  DeclareGlobalAllocationFunction(
1486      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1487      Context.VoidTy, VoidPtr);
1488  DeclareGlobalAllocationFunction(
1489      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1490      Context.VoidTy, VoidPtr);
1491}
1492
1493/// DeclareGlobalAllocationFunction - Declares a single implicit global
1494/// allocation function if it doesn't already exist.
1495void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1496                                           QualType Return, QualType Argument,
1497                                           bool AddMallocAttr) {
1498  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1499
1500  // Check if this function is already declared.
1501  {
1502    DeclContext::lookup_iterator Alloc, AllocEnd;
1503    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1504         Alloc != AllocEnd; ++Alloc) {
1505      // Only look at non-template functions, as it is the predefined,
1506      // non-templated allocation function we are trying to declare here.
1507      if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1508        QualType InitialParamType =
1509          Context.getCanonicalType(
1510            Func->getParamDecl(0)->getType().getUnqualifiedType());
1511        // FIXME: Do we need to check for default arguments here?
1512        if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1513          if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1514            Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1515          return;
1516        }
1517      }
1518    }
1519  }
1520
1521  QualType BadAllocType;
1522  bool HasBadAllocExceptionSpec
1523    = (Name.getCXXOverloadedOperator() == OO_New ||
1524       Name.getCXXOverloadedOperator() == OO_Array_New);
1525  if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
1526    assert(StdBadAlloc && "Must have std::bad_alloc declared");
1527    BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1528  }
1529
1530  FunctionProtoType::ExtProtoInfo EPI;
1531  if (HasBadAllocExceptionSpec) {
1532    if (!getLangOptions().CPlusPlus0x) {
1533      EPI.ExceptionSpecType = EST_Dynamic;
1534      EPI.NumExceptions = 1;
1535      EPI.Exceptions = &BadAllocType;
1536    }
1537  } else {
1538    EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1539                                EST_BasicNoexcept : EST_DynamicNone;
1540  }
1541
1542  QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
1543  FunctionDecl *Alloc =
1544    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1545                         SourceLocation(), Name,
1546                         FnType, /*TInfo=*/0, SC_None,
1547                         SC_None, false, true);
1548  Alloc->setImplicit();
1549
1550  if (AddMallocAttr)
1551    Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1552
1553  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1554                                           SourceLocation(), 0,
1555                                           Argument, /*TInfo=*/0,
1556                                           SC_None, SC_None, 0);
1557  Alloc->setParams(&Param, 1);
1558
1559  // FIXME: Also add this declaration to the IdentifierResolver, but
1560  // make sure it is at the end of the chain to coincide with the
1561  // global scope.
1562  Context.getTranslationUnitDecl()->addDecl(Alloc);
1563}
1564
1565bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1566                                    DeclarationName Name,
1567                                    FunctionDecl* &Operator) {
1568  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1569  // Try to find operator delete/operator delete[] in class scope.
1570  LookupQualifiedName(Found, RD);
1571
1572  if (Found.isAmbiguous())
1573    return true;
1574
1575  Found.suppressDiagnostics();
1576
1577  llvm::SmallVector<DeclAccessPair,4> Matches;
1578  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1579       F != FEnd; ++F) {
1580    NamedDecl *ND = (*F)->getUnderlyingDecl();
1581
1582    // Ignore template operator delete members from the check for a usual
1583    // deallocation function.
1584    if (isa<FunctionTemplateDecl>(ND))
1585      continue;
1586
1587    if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1588      Matches.push_back(F.getPair());
1589  }
1590
1591  // There's exactly one suitable operator;  pick it.
1592  if (Matches.size() == 1) {
1593    Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1594    CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1595                          Matches[0]);
1596    return false;
1597
1598  // We found multiple suitable operators;  complain about the ambiguity.
1599  } else if (!Matches.empty()) {
1600    Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1601      << Name << RD;
1602
1603    for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1604           F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1605      Diag((*F)->getUnderlyingDecl()->getLocation(),
1606           diag::note_member_declared_here) << Name;
1607    return true;
1608  }
1609
1610  // We did find operator delete/operator delete[] declarations, but
1611  // none of them were suitable.
1612  if (!Found.empty()) {
1613    Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1614      << Name << RD;
1615
1616    for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1617         F != FEnd; ++F)
1618      Diag((*F)->getUnderlyingDecl()->getLocation(),
1619           diag::note_member_declared_here) << Name;
1620
1621    return true;
1622  }
1623
1624  // Look for a global declaration.
1625  DeclareGlobalNewDelete();
1626  DeclContext *TUDecl = Context.getTranslationUnitDecl();
1627
1628  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1629  Expr* DeallocArgs[1];
1630  DeallocArgs[0] = &Null;
1631  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1632                             DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1633                             Operator))
1634    return true;
1635
1636  assert(Operator && "Did not find a deallocation function!");
1637  return false;
1638}
1639
1640/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1641/// @code ::delete ptr; @endcode
1642/// or
1643/// @code delete [] ptr; @endcode
1644ExprResult
1645Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1646                     bool ArrayForm, Expr *ExE) {
1647  // C++ [expr.delete]p1:
1648  //   The operand shall have a pointer type, or a class type having a single
1649  //   conversion function to a pointer type. The result has type void.
1650  //
1651  // DR599 amends "pointer type" to "pointer to object type" in both cases.
1652
1653  ExprResult Ex = Owned(ExE);
1654  FunctionDecl *OperatorDelete = 0;
1655  bool ArrayFormAsWritten = ArrayForm;
1656  bool UsualArrayDeleteWantsSize = false;
1657
1658  if (!Ex.get()->isTypeDependent()) {
1659    QualType Type = Ex.get()->getType();
1660
1661    if (const RecordType *Record = Type->getAs<RecordType>()) {
1662      if (RequireCompleteType(StartLoc, Type,
1663                              PDiag(diag::err_delete_incomplete_class_type)))
1664        return ExprError();
1665
1666      llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1667
1668      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1669      const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1670      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1671             E = Conversions->end(); I != E; ++I) {
1672        NamedDecl *D = I.getDecl();
1673        if (isa<UsingShadowDecl>(D))
1674          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1675
1676        // Skip over templated conversion functions; they aren't considered.
1677        if (isa<FunctionTemplateDecl>(D))
1678          continue;
1679
1680        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1681
1682        QualType ConvType = Conv->getConversionType().getNonReferenceType();
1683        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1684          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
1685            ObjectPtrConversions.push_back(Conv);
1686      }
1687      if (ObjectPtrConversions.size() == 1) {
1688        // We have a single conversion to a pointer-to-object type. Perform
1689        // that conversion.
1690        // TODO: don't redo the conversion calculation.
1691        ExprResult Res =
1692          PerformImplicitConversion(Ex.get(),
1693                            ObjectPtrConversions.front()->getConversionType(),
1694                                    AA_Converting);
1695        if (Res.isUsable()) {
1696          Ex = move(Res);
1697          Type = Ex.get()->getType();
1698        }
1699      }
1700      else if (ObjectPtrConversions.size() > 1) {
1701        Diag(StartLoc, diag::err_ambiguous_delete_operand)
1702              << Type << Ex.get()->getSourceRange();
1703        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1704          NoteOverloadCandidate(ObjectPtrConversions[i]);
1705        return ExprError();
1706      }
1707    }
1708
1709    if (!Type->isPointerType())
1710      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1711        << Type << Ex.get()->getSourceRange());
1712
1713    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1714    if (Pointee->isVoidType() && !isSFINAEContext()) {
1715      // The C++ standard bans deleting a pointer to a non-object type, which
1716      // effectively bans deletion of "void*". However, most compilers support
1717      // this, so we treat it as a warning unless we're in a SFINAE context.
1718      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1719        << Type << Ex.get()->getSourceRange();
1720    } else if (Pointee->isFunctionType() || Pointee->isVoidType())
1721      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1722        << Type << Ex.get()->getSourceRange());
1723    else if (!Pointee->isDependentType() &&
1724             RequireCompleteType(StartLoc, Pointee,
1725                                 PDiag(diag::warn_delete_incomplete)
1726                                   << Ex.get()->getSourceRange()))
1727      return ExprError();
1728
1729    // C++ [expr.delete]p2:
1730    //   [Note: a pointer to a const type can be the operand of a
1731    //   delete-expression; it is not necessary to cast away the constness
1732    //   (5.2.11) of the pointer expression before it is used as the operand
1733    //   of the delete-expression. ]
1734    Ex = ImpCastExprToType(Ex.take(), Context.getPointerType(Context.VoidTy),
1735                      CK_NoOp);
1736
1737    if (Pointee->isArrayType() && !ArrayForm) {
1738      Diag(StartLoc, diag::warn_delete_array_type)
1739          << Type << Ex.get()->getSourceRange()
1740          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1741      ArrayForm = true;
1742    }
1743
1744    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1745                                      ArrayForm ? OO_Array_Delete : OO_Delete);
1746
1747    QualType PointeeElem = Context.getBaseElementType(Pointee);
1748    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1749      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1750
1751      if (!UseGlobal &&
1752          FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1753        return ExprError();
1754
1755      // If we're allocating an array of records, check whether the
1756      // usual operator delete[] has a size_t parameter.
1757      if (ArrayForm) {
1758        // If the user specifically asked to use the global allocator,
1759        // we'll need to do the lookup into the class.
1760        if (UseGlobal)
1761          UsualArrayDeleteWantsSize =
1762            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1763
1764        // Otherwise, the usual operator delete[] should be the
1765        // function we just found.
1766        else if (isa<CXXMethodDecl>(OperatorDelete))
1767          UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1768      }
1769
1770      if (!RD->hasTrivialDestructor())
1771        if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1772          MarkDeclarationReferenced(StartLoc,
1773                                    const_cast<CXXDestructorDecl*>(Dtor));
1774          DiagnoseUseOfDecl(Dtor, StartLoc);
1775        }
1776    }
1777
1778    if (!OperatorDelete) {
1779      // Look for a global declaration.
1780      DeclareGlobalNewDelete();
1781      DeclContext *TUDecl = Context.getTranslationUnitDecl();
1782      Expr *Arg = Ex.get();
1783      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1784                                 &Arg, 1, TUDecl, /*AllowMissing=*/false,
1785                                 OperatorDelete))
1786        return ExprError();
1787    }
1788
1789    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1790
1791    // Check access and ambiguity of operator delete and destructor.
1792    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1793      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1794      if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1795          CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
1796                      PDiag(diag::err_access_dtor) << PointeeElem);
1797      }
1798    }
1799
1800  }
1801
1802  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1803                                           ArrayFormAsWritten,
1804                                           UsualArrayDeleteWantsSize,
1805                                           OperatorDelete, Ex.take(), StartLoc));
1806}
1807
1808/// \brief Check the use of the given variable as a C++ condition in an if,
1809/// while, do-while, or switch statement.
1810ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1811                                        SourceLocation StmtLoc,
1812                                        bool ConvertToBoolean) {
1813  QualType T = ConditionVar->getType();
1814
1815  // C++ [stmt.select]p2:
1816  //   The declarator shall not specify a function or an array.
1817  if (T->isFunctionType())
1818    return ExprError(Diag(ConditionVar->getLocation(),
1819                          diag::err_invalid_use_of_function_type)
1820                       << ConditionVar->getSourceRange());
1821  else if (T->isArrayType())
1822    return ExprError(Diag(ConditionVar->getLocation(),
1823                          diag::err_invalid_use_of_array_type)
1824                     << ConditionVar->getSourceRange());
1825
1826  ExprResult Condition =
1827    Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1828                                        ConditionVar,
1829                                        ConditionVar->getLocation(),
1830                            ConditionVar->getType().getNonReferenceType(),
1831                              VK_LValue));
1832  if (ConvertToBoolean) {
1833    Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
1834    if (Condition.isInvalid())
1835      return ExprError();
1836  }
1837
1838  return move(Condition);
1839}
1840
1841/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1842ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
1843  // C++ 6.4p4:
1844  // The value of a condition that is an initialized declaration in a statement
1845  // other than a switch statement is the value of the declared variable
1846  // implicitly converted to type bool. If that conversion is ill-formed, the
1847  // program is ill-formed.
1848  // The value of a condition that is an expression is the value of the
1849  // expression, implicitly converted to bool.
1850  //
1851  return PerformContextuallyConvertToBool(CondExpr);
1852}
1853
1854/// Helper function to determine whether this is the (deprecated) C++
1855/// conversion from a string literal to a pointer to non-const char or
1856/// non-const wchar_t (for narrow and wide string literals,
1857/// respectively).
1858bool
1859Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1860  // Look inside the implicit cast, if it exists.
1861  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1862    From = Cast->getSubExpr();
1863
1864  // A string literal (2.13.4) that is not a wide string literal can
1865  // be converted to an rvalue of type "pointer to char"; a wide
1866  // string literal can be converted to an rvalue of type "pointer
1867  // to wchar_t" (C++ 4.2p2).
1868  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
1869    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1870      if (const BuiltinType *ToPointeeType
1871          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1872        // This conversion is considered only when there is an
1873        // explicit appropriate pointer target type (C++ 4.2p2).
1874        if (!ToPtrType->getPointeeType().hasQualifiers() &&
1875            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1876             (!StrLit->isWide() &&
1877              (ToPointeeType->getKind() == BuiltinType::Char_U ||
1878               ToPointeeType->getKind() == BuiltinType::Char_S))))
1879          return true;
1880      }
1881
1882  return false;
1883}
1884
1885static ExprResult BuildCXXCastArgument(Sema &S,
1886                                       SourceLocation CastLoc,
1887                                       QualType Ty,
1888                                       CastKind Kind,
1889                                       CXXMethodDecl *Method,
1890                                       NamedDecl *FoundDecl,
1891                                       Expr *From) {
1892  switch (Kind) {
1893  default: assert(0 && "Unhandled cast kind!");
1894  case CK_ConstructorConversion: {
1895    ASTOwningVector<Expr*> ConstructorArgs(S);
1896
1897    if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1898                                  MultiExprArg(&From, 1),
1899                                  CastLoc, ConstructorArgs))
1900      return ExprError();
1901
1902    ExprResult Result =
1903    S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1904                            move_arg(ConstructorArgs),
1905                            /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1906                            SourceRange());
1907    if (Result.isInvalid())
1908      return ExprError();
1909
1910    return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1911  }
1912
1913  case CK_UserDefinedConversion: {
1914    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1915
1916    // Create an implicit call expr that calls it.
1917    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
1918    if (Result.isInvalid())
1919      return ExprError();
1920
1921    return S.MaybeBindToTemporary(Result.get());
1922  }
1923  }
1924}
1925
1926/// PerformImplicitConversion - Perform an implicit conversion of the
1927/// expression From to the type ToType using the pre-computed implicit
1928/// conversion sequence ICS. Returns the converted
1929/// expression. Action is the kind of conversion we're performing,
1930/// used in the error message.
1931ExprResult
1932Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1933                                const ImplicitConversionSequence &ICS,
1934                                AssignmentAction Action, bool CStyle) {
1935  switch (ICS.getKind()) {
1936  case ImplicitConversionSequence::StandardConversion: {
1937    ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
1938                                               Action, CStyle);
1939    if (Res.isInvalid())
1940      return ExprError();
1941    From = Res.take();
1942    break;
1943  }
1944
1945  case ImplicitConversionSequence::UserDefinedConversion: {
1946
1947      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1948      CastKind CastKind;
1949      QualType BeforeToType;
1950      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1951        CastKind = CK_UserDefinedConversion;
1952
1953        // If the user-defined conversion is specified by a conversion function,
1954        // the initial standard conversion sequence converts the source type to
1955        // the implicit object parameter of the conversion function.
1956        BeforeToType = Context.getTagDeclType(Conv->getParent());
1957      } else {
1958        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
1959        CastKind = CK_ConstructorConversion;
1960        // Do no conversion if dealing with ... for the first conversion.
1961        if (!ICS.UserDefined.EllipsisConversion) {
1962          // If the user-defined conversion is specified by a constructor, the
1963          // initial standard conversion sequence converts the source type to the
1964          // type required by the argument of the constructor
1965          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1966        }
1967      }
1968      // Watch out for elipsis conversion.
1969      if (!ICS.UserDefined.EllipsisConversion) {
1970        ExprResult Res =
1971          PerformImplicitConversion(From, BeforeToType,
1972                                    ICS.UserDefined.Before, AA_Converting,
1973                                    CStyle);
1974        if (Res.isInvalid())
1975          return ExprError();
1976        From = Res.take();
1977      }
1978
1979      ExprResult CastArg
1980        = BuildCXXCastArgument(*this,
1981                               From->getLocStart(),
1982                               ToType.getNonReferenceType(),
1983                               CastKind, cast<CXXMethodDecl>(FD),
1984                               ICS.UserDefined.FoundConversionFunction,
1985                               From);
1986
1987      if (CastArg.isInvalid())
1988        return ExprError();
1989
1990      From = CastArg.take();
1991
1992      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1993                                       AA_Converting, CStyle);
1994  }
1995
1996  case ImplicitConversionSequence::AmbiguousConversion:
1997    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
1998                          PDiag(diag::err_typecheck_ambiguous_condition)
1999                            << From->getSourceRange());
2000     return ExprError();
2001
2002  case ImplicitConversionSequence::EllipsisConversion:
2003    assert(false && "Cannot perform an ellipsis conversion");
2004    return Owned(From);
2005
2006  case ImplicitConversionSequence::BadConversion:
2007    return ExprError();
2008  }
2009
2010  // Everything went well.
2011  return Owned(From);
2012}
2013
2014/// PerformImplicitConversion - Perform an implicit conversion of the
2015/// expression From to the type ToType by following the standard
2016/// conversion sequence SCS. Returns the converted
2017/// expression. Flavor is the context in which we're performing this
2018/// conversion, for use in error messages.
2019ExprResult
2020Sema::PerformImplicitConversion(Expr *From, QualType ToType,
2021                                const StandardConversionSequence& SCS,
2022                                AssignmentAction Action, bool CStyle) {
2023  // Overall FIXME: we are recomputing too many types here and doing far too
2024  // much extra work. What this means is that we need to keep track of more
2025  // information that is computed when we try the implicit conversion initially,
2026  // so that we don't need to recompute anything here.
2027  QualType FromType = From->getType();
2028
2029  if (SCS.CopyConstructor) {
2030    // FIXME: When can ToType be a reference type?
2031    assert(!ToType->isReferenceType());
2032    if (SCS.Second == ICK_Derived_To_Base) {
2033      ASTOwningVector<Expr*> ConstructorArgs(*this);
2034      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2035                                  MultiExprArg(*this, &From, 1),
2036                                  /*FIXME:ConstructLoc*/SourceLocation(),
2037                                  ConstructorArgs))
2038        return ExprError();
2039      return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2040                                   ToType, SCS.CopyConstructor,
2041                                   move_arg(ConstructorArgs),
2042                                   /*ZeroInit*/ false,
2043                                   CXXConstructExpr::CK_Complete,
2044                                   SourceRange());
2045    }
2046    return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2047                                 ToType, SCS.CopyConstructor,
2048                                 MultiExprArg(*this, &From, 1),
2049                                 /*ZeroInit*/ false,
2050                                 CXXConstructExpr::CK_Complete,
2051                                 SourceRange());
2052  }
2053
2054  // Resolve overloaded function references.
2055  if (Context.hasSameType(FromType, Context.OverloadTy)) {
2056    DeclAccessPair Found;
2057    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2058                                                          true, Found);
2059    if (!Fn)
2060      return ExprError();
2061
2062    if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2063      return ExprError();
2064
2065    From = FixOverloadedFunctionReference(From, Found, Fn);
2066    FromType = From->getType();
2067  }
2068
2069  // Perform the first implicit conversion.
2070  switch (SCS.First) {
2071  case ICK_Identity:
2072    // Nothing to do.
2073    break;
2074
2075  case ICK_Lvalue_To_Rvalue:
2076    // Should this get its own ICK?
2077    if (From->getObjectKind() == OK_ObjCProperty) {
2078      ExprResult FromRes = ConvertPropertyForRValue(From);
2079      if (FromRes.isInvalid())
2080        return ExprError();
2081      From = FromRes.take();
2082      if (!From->isGLValue()) break;
2083    }
2084
2085    // Check for trivial buffer overflows.
2086    CheckArrayAccess(From);
2087
2088    FromType = FromType.getUnqualifiedType();
2089    From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2090                                    From, 0, VK_RValue);
2091    break;
2092
2093  case ICK_Array_To_Pointer:
2094    FromType = Context.getArrayDecayedType(FromType);
2095    From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay).take();
2096    break;
2097
2098  case ICK_Function_To_Pointer:
2099    FromType = Context.getPointerType(FromType);
2100    From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay).take();
2101    break;
2102
2103  default:
2104    assert(false && "Improper first standard conversion");
2105    break;
2106  }
2107
2108  // Perform the second implicit conversion
2109  switch (SCS.Second) {
2110  case ICK_Identity:
2111    // If both sides are functions (or pointers/references to them), there could
2112    // be incompatible exception declarations.
2113    if (CheckExceptionSpecCompatibility(From, ToType))
2114      return ExprError();
2115    // Nothing else to do.
2116    break;
2117
2118  case ICK_NoReturn_Adjustment:
2119    // If both sides are functions (or pointers/references to them), there could
2120    // be incompatible exception declarations.
2121    if (CheckExceptionSpecCompatibility(From, ToType))
2122      return ExprError();
2123
2124    From = ImpCastExprToType(From, ToType, CK_NoOp).take();
2125    break;
2126
2127  case ICK_Integral_Promotion:
2128  case ICK_Integral_Conversion:
2129    From = ImpCastExprToType(From, ToType, CK_IntegralCast).take();
2130    break;
2131
2132  case ICK_Floating_Promotion:
2133  case ICK_Floating_Conversion:
2134    From = ImpCastExprToType(From, ToType, CK_FloatingCast).take();
2135    break;
2136
2137  case ICK_Complex_Promotion:
2138  case ICK_Complex_Conversion: {
2139    QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2140    QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2141    CastKind CK;
2142    if (FromEl->isRealFloatingType()) {
2143      if (ToEl->isRealFloatingType())
2144        CK = CK_FloatingComplexCast;
2145      else
2146        CK = CK_FloatingComplexToIntegralComplex;
2147    } else if (ToEl->isRealFloatingType()) {
2148      CK = CK_IntegralComplexToFloatingComplex;
2149    } else {
2150      CK = CK_IntegralComplexCast;
2151    }
2152    From = ImpCastExprToType(From, ToType, CK).take();
2153    break;
2154  }
2155
2156  case ICK_Floating_Integral:
2157    if (ToType->isRealFloatingType())
2158      From = ImpCastExprToType(From, ToType, CK_IntegralToFloating).take();
2159    else
2160      From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral).take();
2161    break;
2162
2163  case ICK_Compatible_Conversion:
2164    From = ImpCastExprToType(From, ToType, CK_NoOp).take();
2165    break;
2166
2167  case ICK_Pointer_Conversion: {
2168    if (SCS.IncompatibleObjC && Action != AA_Casting) {
2169      // Diagnose incompatible Objective-C conversions
2170      if (Action == AA_Initializing)
2171        Diag(From->getSourceRange().getBegin(),
2172             diag::ext_typecheck_convert_incompatible_pointer)
2173          << ToType << From->getType() << Action
2174          << From->getSourceRange();
2175      else
2176        Diag(From->getSourceRange().getBegin(),
2177             diag::ext_typecheck_convert_incompatible_pointer)
2178          << From->getType() << ToType << Action
2179          << From->getSourceRange();
2180    }
2181
2182    CastKind Kind = CK_Invalid;
2183    CXXCastPath BasePath;
2184    if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2185      return ExprError();
2186    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
2187    break;
2188  }
2189
2190  case ICK_Pointer_Member: {
2191    CastKind Kind = CK_Invalid;
2192    CXXCastPath BasePath;
2193    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2194      return ExprError();
2195    if (CheckExceptionSpecCompatibility(From, ToType))
2196      return ExprError();
2197    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
2198    break;
2199  }
2200
2201  case ICK_Boolean_Conversion:
2202    From = ImpCastExprToType(From, Context.BoolTy,
2203                             ScalarTypeToBooleanCastKind(FromType)).take();
2204    break;
2205
2206  case ICK_Derived_To_Base: {
2207    CXXCastPath BasePath;
2208    if (CheckDerivedToBaseConversion(From->getType(),
2209                                     ToType.getNonReferenceType(),
2210                                     From->getLocStart(),
2211                                     From->getSourceRange(),
2212                                     &BasePath,
2213                                     CStyle))
2214      return ExprError();
2215
2216    From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2217                      CK_DerivedToBase, CastCategory(From),
2218                      &BasePath).take();
2219    break;
2220  }
2221
2222  case ICK_Vector_Conversion:
2223    From = ImpCastExprToType(From, ToType, CK_BitCast).take();
2224    break;
2225
2226  case ICK_Vector_Splat:
2227    From = ImpCastExprToType(From, ToType, CK_VectorSplat).take();
2228    break;
2229
2230  case ICK_Complex_Real:
2231    // Case 1.  x -> _Complex y
2232    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2233      QualType ElType = ToComplex->getElementType();
2234      bool isFloatingComplex = ElType->isRealFloatingType();
2235
2236      // x -> y
2237      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2238        // do nothing
2239      } else if (From->getType()->isRealFloatingType()) {
2240        From = ImpCastExprToType(From, ElType,
2241                isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2242      } else {
2243        assert(From->getType()->isIntegerType());
2244        From = ImpCastExprToType(From, ElType,
2245                isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2246      }
2247      // y -> _Complex y
2248      From = ImpCastExprToType(From, ToType,
2249                   isFloatingComplex ? CK_FloatingRealToComplex
2250                                     : CK_IntegralRealToComplex).take();
2251
2252    // Case 2.  _Complex x -> y
2253    } else {
2254      const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2255      assert(FromComplex);
2256
2257      QualType ElType = FromComplex->getElementType();
2258      bool isFloatingComplex = ElType->isRealFloatingType();
2259
2260      // _Complex x -> x
2261      From = ImpCastExprToType(From, ElType,
2262                   isFloatingComplex ? CK_FloatingComplexToReal
2263                                     : CK_IntegralComplexToReal).take();
2264
2265      // x -> y
2266      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2267        // do nothing
2268      } else if (ToType->isRealFloatingType()) {
2269        From = ImpCastExprToType(From, ToType,
2270                isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating).take();
2271      } else {
2272        assert(ToType->isIntegerType());
2273        From = ImpCastExprToType(From, ToType,
2274                isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast).take();
2275      }
2276    }
2277    break;
2278
2279  case ICK_Block_Pointer_Conversion: {
2280      From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2281                               VK_RValue).take();
2282      break;
2283    }
2284
2285  case ICK_TransparentUnionConversion: {
2286    ExprResult FromRes = Owned(From);
2287    Sema::AssignConvertType ConvTy =
2288      CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2289    if (FromRes.isInvalid())
2290      return ExprError();
2291    From = FromRes.take();
2292    assert ((ConvTy == Sema::Compatible) &&
2293            "Improper transparent union conversion");
2294    (void)ConvTy;
2295    break;
2296  }
2297
2298  case ICK_Lvalue_To_Rvalue:
2299  case ICK_Array_To_Pointer:
2300  case ICK_Function_To_Pointer:
2301  case ICK_Qualification:
2302  case ICK_Num_Conversion_Kinds:
2303    assert(false && "Improper second standard conversion");
2304    break;
2305  }
2306
2307  switch (SCS.Third) {
2308  case ICK_Identity:
2309    // Nothing to do.
2310    break;
2311
2312  case ICK_Qualification: {
2313    // The qualification keeps the category of the inner expression, unless the
2314    // target type isn't a reference.
2315    ExprValueKind VK = ToType->isReferenceType() ?
2316                                  CastCategory(From) : VK_RValue;
2317    From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2318                             CK_NoOp, VK).take();
2319
2320    if (SCS.DeprecatedStringLiteralToCharPtr &&
2321        !getLangOptions().WritableStrings)
2322      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2323        << ToType.getNonReferenceType();
2324
2325    break;
2326    }
2327
2328  default:
2329    assert(false && "Improper third standard conversion");
2330    break;
2331  }
2332
2333  return Owned(From);
2334}
2335
2336ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
2337                                     SourceLocation KWLoc,
2338                                     ParsedType Ty,
2339                                     SourceLocation RParen) {
2340  TypeSourceInfo *TSInfo;
2341  QualType T = GetTypeFromParser(Ty, &TSInfo);
2342
2343  if (!TSInfo)
2344    TSInfo = Context.getTrivialTypeSourceInfo(T);
2345  return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
2346}
2347
2348static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2349                                   SourceLocation KeyLoc) {
2350  // FIXME: For many of these traits, we need a complete type before we can
2351  // check these properties.
2352  assert(!T->isDependentType() &&
2353         "Cannot evaluate traits for dependent types.");
2354  ASTContext &C = Self.Context;
2355  switch(UTT) {
2356  default: assert(false && "Unknown type trait or not implemented");
2357  case UTT_IsPOD: return T->isPODType();
2358  case UTT_IsLiteral: return T->isLiteralType();
2359  case UTT_IsClass: // Fallthrough
2360  case UTT_IsUnion:
2361    if (const RecordType *Record = T->getAs<RecordType>()) {
2362      bool Union = Record->getDecl()->isUnion();
2363      return UTT == UTT_IsUnion ? Union : !Union;
2364    }
2365    return false;
2366  case UTT_IsEnum: return T->isEnumeralType();
2367  case UTT_IsPolymorphic:
2368    if (const RecordType *Record = T->getAs<RecordType>()) {
2369      // Type traits are only parsed in C++, so we've got CXXRecords.
2370      return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2371    }
2372    return false;
2373  case UTT_IsAbstract:
2374    if (const RecordType *RT = T->getAs<RecordType>())
2375      return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2376    return false;
2377  case UTT_IsEmpty:
2378    if (const RecordType *Record = T->getAs<RecordType>()) {
2379      return !Record->getDecl()->isUnion()
2380          && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2381    }
2382    return false;
2383  case UTT_HasTrivialConstructor:
2384    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2385    //   If __is_pod (type) is true then the trait is true, else if type is
2386    //   a cv class or union type (or array thereof) with a trivial default
2387    //   constructor ([class.ctor]) then the trait is true, else it is false.
2388    if (T->isPODType())
2389      return true;
2390    if (const RecordType *RT =
2391          C.getBaseElementType(T)->getAs<RecordType>())
2392      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2393    return false;
2394  case UTT_HasTrivialCopy:
2395    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2396    //   If __is_pod (type) is true or type is a reference type then
2397    //   the trait is true, else if type is a cv class or union type
2398    //   with a trivial copy constructor ([class.copy]) then the trait
2399    //   is true, else it is false.
2400    if (T->isPODType() || T->isReferenceType())
2401      return true;
2402    if (const RecordType *RT = T->getAs<RecordType>())
2403      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2404    return false;
2405  case UTT_HasTrivialAssign:
2406    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2407    //   If type is const qualified or is a reference type then the
2408    //   trait is false. Otherwise if __is_pod (type) is true then the
2409    //   trait is true, else if type is a cv class or union type with
2410    //   a trivial copy assignment ([class.copy]) then the trait is
2411    //   true, else it is false.
2412    // Note: the const and reference restrictions are interesting,
2413    // given that const and reference members don't prevent a class
2414    // from having a trivial copy assignment operator (but do cause
2415    // errors if the copy assignment operator is actually used, q.v.
2416    // [class.copy]p12).
2417
2418    if (C.getBaseElementType(T).isConstQualified())
2419      return false;
2420    if (T->isPODType())
2421      return true;
2422    if (const RecordType *RT = T->getAs<RecordType>())
2423      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2424    return false;
2425  case UTT_HasTrivialDestructor:
2426    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2427    //   If __is_pod (type) is true or type is a reference type
2428    //   then the trait is true, else if type is a cv class or union
2429    //   type (or array thereof) with a trivial destructor
2430    //   ([class.dtor]) then the trait is true, else it is
2431    //   false.
2432    if (T->isPODType() || T->isReferenceType())
2433      return true;
2434    if (const RecordType *RT =
2435          C.getBaseElementType(T)->getAs<RecordType>())
2436      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2437    return false;
2438  // TODO: Propagate nothrowness for implicitly declared special members.
2439  case UTT_HasNothrowAssign:
2440    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2441    //   If type is const qualified or is a reference type then the
2442    //   trait is false. Otherwise if __has_trivial_assign (type)
2443    //   is true then the trait is true, else if type is a cv class
2444    //   or union type with copy assignment operators that are known
2445    //   not to throw an exception then the trait is true, else it is
2446    //   false.
2447    if (C.getBaseElementType(T).isConstQualified())
2448      return false;
2449    if (T->isReferenceType())
2450      return false;
2451    if (T->isPODType())
2452      return true;
2453    if (const RecordType *RT = T->getAs<RecordType>()) {
2454      CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2455      if (RD->hasTrivialCopyAssignment())
2456        return true;
2457
2458      bool FoundAssign = false;
2459      bool AllNoThrow = true;
2460      DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
2461      LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2462                       Sema::LookupOrdinaryName);
2463      if (Self.LookupQualifiedName(Res, RD)) {
2464        for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2465             Op != OpEnd; ++Op) {
2466          CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2467          if (Operator->isCopyAssignmentOperator()) {
2468            FoundAssign = true;
2469            const FunctionProtoType *CPT
2470                = Operator->getType()->getAs<FunctionProtoType>();
2471            if (!CPT->isNothrow(Self.Context)) {
2472              AllNoThrow = false;
2473              break;
2474            }
2475          }
2476        }
2477      }
2478
2479      return FoundAssign && AllNoThrow;
2480    }
2481    return false;
2482  case UTT_HasNothrowCopy:
2483    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2484    //   If __has_trivial_copy (type) is true then the trait is true, else
2485    //   if type is a cv class or union type with copy constructors that are
2486    //   known not to throw an exception then the trait is true, else it is
2487    //   false.
2488    if (T->isPODType() || T->isReferenceType())
2489      return true;
2490    if (const RecordType *RT = T->getAs<RecordType>()) {
2491      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2492      if (RD->hasTrivialCopyConstructor())
2493        return true;
2494
2495      bool FoundConstructor = false;
2496      bool AllNoThrow = true;
2497      unsigned FoundTQs;
2498      DeclContext::lookup_const_iterator Con, ConEnd;
2499      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2500           Con != ConEnd; ++Con) {
2501        // A template constructor is never a copy constructor.
2502        // FIXME: However, it may actually be selected at the actual overload
2503        // resolution point.
2504        if (isa<FunctionTemplateDecl>(*Con))
2505          continue;
2506        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2507        if (Constructor->isCopyConstructor(FoundTQs)) {
2508          FoundConstructor = true;
2509          const FunctionProtoType *CPT
2510              = Constructor->getType()->getAs<FunctionProtoType>();
2511          // FIXME: check whether evaluating default arguments can throw.
2512          // For now, we'll be conservative and assume that they can throw.
2513          if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) {
2514            AllNoThrow = false;
2515            break;
2516          }
2517        }
2518      }
2519
2520      return FoundConstructor && AllNoThrow;
2521    }
2522    return false;
2523  case UTT_HasNothrowConstructor:
2524    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2525    //   If __has_trivial_constructor (type) is true then the trait is
2526    //   true, else if type is a cv class or union type (or array
2527    //   thereof) with a default constructor that is known not to
2528    //   throw an exception then the trait is true, else it is false.
2529    if (T->isPODType())
2530      return true;
2531    if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2532      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2533      if (RD->hasTrivialConstructor())
2534        return true;
2535
2536      DeclContext::lookup_const_iterator Con, ConEnd;
2537      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2538           Con != ConEnd; ++Con) {
2539        // FIXME: In C++0x, a constructor template can be a default constructor.
2540        if (isa<FunctionTemplateDecl>(*Con))
2541          continue;
2542        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2543        if (Constructor->isDefaultConstructor()) {
2544          const FunctionProtoType *CPT
2545              = Constructor->getType()->getAs<FunctionProtoType>();
2546          // TODO: check whether evaluating default arguments can throw.
2547          // For now, we'll be conservative and assume that they can throw.
2548          return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
2549        }
2550      }
2551    }
2552    return false;
2553  case UTT_HasVirtualDestructor:
2554    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2555    //   If type is a class type with a virtual destructor ([class.dtor])
2556    //   then the trait is true, else it is false.
2557    if (const RecordType *Record = T->getAs<RecordType>()) {
2558      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2559      if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
2560        return Destructor->isVirtual();
2561    }
2562    return false;
2563  }
2564}
2565
2566ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
2567                                     SourceLocation KWLoc,
2568                                     TypeSourceInfo *TSInfo,
2569                                     SourceLocation RParen) {
2570  QualType T = TSInfo->getType();
2571
2572  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2573  // all traits except __is_class, __is_enum and __is_union require a the type
2574  // to be complete, an array of unknown bound, or void.
2575  if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
2576    QualType E = T;
2577    if (T->isIncompleteArrayType())
2578      E = Context.getAsArrayType(T)->getElementType();
2579    if (!T->isVoidType() &&
2580        RequireCompleteType(KWLoc, E,
2581                            diag::err_incomplete_type_used_in_type_trait_expr))
2582      return ExprError();
2583  }
2584
2585  bool Value = false;
2586  if (!T->isDependentType())
2587    Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
2588
2589  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
2590                                                RParen, Context.BoolTy));
2591}
2592
2593ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2594                                      SourceLocation KWLoc,
2595                                      ParsedType LhsTy,
2596                                      ParsedType RhsTy,
2597                                      SourceLocation RParen) {
2598  TypeSourceInfo *LhsTSInfo;
2599  QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2600  if (!LhsTSInfo)
2601    LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2602
2603  TypeSourceInfo *RhsTSInfo;
2604  QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2605  if (!RhsTSInfo)
2606    RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2607
2608  return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2609}
2610
2611static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2612                                    QualType LhsT, QualType RhsT,
2613                                    SourceLocation KeyLoc) {
2614  assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2615         "Cannot evaluate traits for dependent types.");
2616
2617  switch(BTT) {
2618  case BTT_IsBaseOf: {
2619    // C++0x [meta.rel]p2
2620    // Base is a base class of Derived without regard to cv-qualifiers or
2621    // Base and Derived are not unions and name the same class type without
2622    // regard to cv-qualifiers.
2623
2624    const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2625    if (!lhsRecord) return false;
2626
2627    const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2628    if (!rhsRecord) return false;
2629
2630    assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2631             == (lhsRecord == rhsRecord));
2632
2633    if (lhsRecord == rhsRecord)
2634      return !lhsRecord->getDecl()->isUnion();
2635
2636    // C++0x [meta.rel]p2:
2637    //   If Base and Derived are class types and are different types
2638    //   (ignoring possible cv-qualifiers) then Derived shall be a
2639    //   complete type.
2640    if (Self.RequireCompleteType(KeyLoc, RhsT,
2641                          diag::err_incomplete_type_used_in_type_trait_expr))
2642      return false;
2643
2644    return cast<CXXRecordDecl>(rhsRecord->getDecl())
2645      ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2646  }
2647
2648  case BTT_TypeCompatible:
2649    return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2650                                           RhsT.getUnqualifiedType());
2651
2652  case BTT_IsConvertibleTo: {
2653    // C++0x [meta.rel]p4:
2654    //   Given the following function prototype:
2655    //
2656    //     template <class T>
2657    //       typename add_rvalue_reference<T>::type create();
2658    //
2659    //   the predicate condition for a template specialization
2660    //   is_convertible<From, To> shall be satisfied if and only if
2661    //   the return expression in the following code would be
2662    //   well-formed, including any implicit conversions to the return
2663    //   type of the function:
2664    //
2665    //     To test() {
2666    //       return create<From>();
2667    //     }
2668    //
2669    //   Access checking is performed as if in a context unrelated to To and
2670    //   From. Only the validity of the immediate context of the expression
2671    //   of the return-statement (including conversions to the return type)
2672    //   is considered.
2673    //
2674    // We model the initialization as a copy-initialization of a temporary
2675    // of the appropriate type, which for this expression is identical to the
2676    // return statement (since NRVO doesn't apply).
2677    if (LhsT->isObjectType() || LhsT->isFunctionType())
2678      LhsT = Self.Context.getRValueReferenceType(LhsT);
2679
2680    InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
2681    OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
2682                         Expr::getValueKindForType(LhsT));
2683    Expr *FromPtr = &From;
2684    InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2685                                                           SourceLocation()));
2686
2687    // Perform the initialization within a SFINAE trap at translation unit
2688    // scope.
2689    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2690    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
2691    InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2692    if (Init.getKind() == InitializationSequence::FailedSequence)
2693      return false;
2694
2695    ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2696    return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2697  }
2698  }
2699  llvm_unreachable("Unknown type trait or not implemented");
2700}
2701
2702ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2703                                      SourceLocation KWLoc,
2704                                      TypeSourceInfo *LhsTSInfo,
2705                                      TypeSourceInfo *RhsTSInfo,
2706                                      SourceLocation RParen) {
2707  QualType LhsT = LhsTSInfo->getType();
2708  QualType RhsT = RhsTSInfo->getType();
2709
2710  if (BTT == BTT_TypeCompatible) {
2711    if (getLangOptions().CPlusPlus) {
2712      Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2713        << SourceRange(KWLoc, RParen);
2714      return ExprError();
2715    }
2716  }
2717
2718  bool Value = false;
2719  if (!LhsT->isDependentType() && !RhsT->isDependentType())
2720    Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2721
2722  // Select trait result type.
2723  QualType ResultType;
2724  switch (BTT) {
2725  case BTT_IsBaseOf:       ResultType = Context.BoolTy; break;
2726  case BTT_TypeCompatible: ResultType = Context.IntTy; break;
2727  case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
2728  }
2729
2730  return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2731                                                 RhsTSInfo, Value, RParen,
2732                                                 ResultType));
2733}
2734
2735QualType Sema::CheckPointerToMemberOperands(ExprResult &lex, ExprResult &rex,
2736                                            ExprValueKind &VK,
2737                                            SourceLocation Loc,
2738                                            bool isIndirect) {
2739  const char *OpSpelling = isIndirect ? "->*" : ".*";
2740  // C++ 5.5p2
2741  //   The binary operator .* [p3: ->*] binds its second operand, which shall
2742  //   be of type "pointer to member of T" (where T is a completely-defined
2743  //   class type) [...]
2744  QualType RType = rex.get()->getType();
2745  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
2746  if (!MemPtr) {
2747    Diag(Loc, diag::err_bad_memptr_rhs)
2748      << OpSpelling << RType << rex.get()->getSourceRange();
2749    return QualType();
2750  }
2751
2752  QualType Class(MemPtr->getClass(), 0);
2753
2754  // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2755  // member pointer points must be completely-defined. However, there is no
2756  // reason for this semantic distinction, and the rule is not enforced by
2757  // other compilers. Therefore, we do not check this property, as it is
2758  // likely to be considered a defect.
2759
2760  // C++ 5.5p2
2761  //   [...] to its first operand, which shall be of class T or of a class of
2762  //   which T is an unambiguous and accessible base class. [p3: a pointer to
2763  //   such a class]
2764  QualType LType = lex.get()->getType();
2765  if (isIndirect) {
2766    if (const PointerType *Ptr = LType->getAs<PointerType>())
2767      LType = Ptr->getPointeeType();
2768    else {
2769      Diag(Loc, diag::err_bad_memptr_lhs)
2770        << OpSpelling << 1 << LType
2771        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
2772      return QualType();
2773    }
2774  }
2775
2776  if (!Context.hasSameUnqualifiedType(Class, LType)) {
2777    // If we want to check the hierarchy, we need a complete type.
2778    if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2779        << OpSpelling << (int)isIndirect)) {
2780      return QualType();
2781    }
2782    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2783                       /*DetectVirtual=*/false);
2784    // FIXME: Would it be useful to print full ambiguity paths, or is that
2785    // overkill?
2786    if (!IsDerivedFrom(LType, Class, Paths) ||
2787        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2788      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
2789        << (int)isIndirect << lex.get()->getType();
2790      return QualType();
2791    }
2792    // Cast LHS to type of use.
2793    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
2794    ExprValueKind VK =
2795        isIndirect ? VK_RValue : CastCategory(lex.get());
2796
2797    CXXCastPath BasePath;
2798    BuildBasePathArray(Paths, BasePath);
2799    lex = ImpCastExprToType(lex.take(), UseType, CK_DerivedToBase, VK, &BasePath);
2800  }
2801
2802  if (isa<CXXScalarValueInitExpr>(rex.get()->IgnoreParens())) {
2803    // Diagnose use of pointer-to-member type which when used as
2804    // the functional cast in a pointer-to-member expression.
2805    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2806     return QualType();
2807  }
2808
2809  // C++ 5.5p2
2810  //   The result is an object or a function of the type specified by the
2811  //   second operand.
2812  // The cv qualifiers are the union of those in the pointer and the left side,
2813  // in accordance with 5.5p5 and 5.2.5.
2814  // FIXME: This returns a dereferenced member function pointer as a normal
2815  // function type. However, the only operation valid on such functions is
2816  // calling them. There's also a GCC extension to get a function pointer to the
2817  // thing, which is another complication, because this type - unlike the type
2818  // that is the result of this expression - takes the class as the first
2819  // argument.
2820  // We probably need a "MemberFunctionClosureType" or something like that.
2821  QualType Result = MemPtr->getPointeeType();
2822  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
2823
2824  // C++0x [expr.mptr.oper]p6:
2825  //   In a .* expression whose object expression is an rvalue, the program is
2826  //   ill-formed if the second operand is a pointer to member function with
2827  //   ref-qualifier &. In a ->* expression or in a .* expression whose object
2828  //   expression is an lvalue, the program is ill-formed if the second operand
2829  //   is a pointer to member function with ref-qualifier &&.
2830  if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2831    switch (Proto->getRefQualifier()) {
2832    case RQ_None:
2833      // Do nothing
2834      break;
2835
2836    case RQ_LValue:
2837      if (!isIndirect && !lex.get()->Classify(Context).isLValue())
2838        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2839          << RType << 1 << lex.get()->getSourceRange();
2840      break;
2841
2842    case RQ_RValue:
2843      if (isIndirect || !lex.get()->Classify(Context).isRValue())
2844        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2845          << RType << 0 << lex.get()->getSourceRange();
2846      break;
2847    }
2848  }
2849
2850  // C++ [expr.mptr.oper]p6:
2851  //   The result of a .* expression whose second operand is a pointer
2852  //   to a data member is of the same value category as its
2853  //   first operand. The result of a .* expression whose second
2854  //   operand is a pointer to a member function is a prvalue. The
2855  //   result of an ->* expression is an lvalue if its second operand
2856  //   is a pointer to data member and a prvalue otherwise.
2857  if (Result->isFunctionType())
2858    VK = VK_RValue;
2859  else if (isIndirect)
2860    VK = VK_LValue;
2861  else
2862    VK = lex.get()->getValueKind();
2863
2864  return Result;
2865}
2866
2867/// \brief Try to convert a type to another according to C++0x 5.16p3.
2868///
2869/// This is part of the parameter validation for the ? operator. If either
2870/// value operand is a class type, the two operands are attempted to be
2871/// converted to each other. This function does the conversion in one direction.
2872/// It returns true if the program is ill-formed and has already been diagnosed
2873/// as such.
2874static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2875                                SourceLocation QuestionLoc,
2876                                bool &HaveConversion,
2877                                QualType &ToType) {
2878  HaveConversion = false;
2879  ToType = To->getType();
2880
2881  InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2882                                                           SourceLocation());
2883  // C++0x 5.16p3
2884  //   The process for determining whether an operand expression E1 of type T1
2885  //   can be converted to match an operand expression E2 of type T2 is defined
2886  //   as follows:
2887  //   -- If E2 is an lvalue:
2888  bool ToIsLvalue = To->isLValue();
2889  if (ToIsLvalue) {
2890    //   E1 can be converted to match E2 if E1 can be implicitly converted to
2891    //   type "lvalue reference to T2", subject to the constraint that in the
2892    //   conversion the reference must bind directly to E1.
2893    QualType T = Self.Context.getLValueReferenceType(ToType);
2894    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2895
2896    InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2897    if (InitSeq.isDirectReferenceBinding()) {
2898      ToType = T;
2899      HaveConversion = true;
2900      return false;
2901    }
2902
2903    if (InitSeq.isAmbiguous())
2904      return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2905  }
2906
2907  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
2908  //      -- if E1 and E2 have class type, and the underlying class types are
2909  //         the same or one is a base class of the other:
2910  QualType FTy = From->getType();
2911  QualType TTy = To->getType();
2912  const RecordType *FRec = FTy->getAs<RecordType>();
2913  const RecordType *TRec = TTy->getAs<RecordType>();
2914  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2915                       Self.IsDerivedFrom(FTy, TTy);
2916  if (FRec && TRec &&
2917      (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
2918    //         E1 can be converted to match E2 if the class of T2 is the
2919    //         same type as, or a base class of, the class of T1, and
2920    //         [cv2 > cv1].
2921    if (FRec == TRec || FDerivedFromT) {
2922      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
2923        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2924        InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2925        if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2926          HaveConversion = true;
2927          return false;
2928        }
2929
2930        if (InitSeq.isAmbiguous())
2931          return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2932      }
2933    }
2934
2935    return false;
2936  }
2937
2938  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
2939  //        implicitly converted to the type that expression E2 would have
2940  //        if E2 were converted to an rvalue (or the type it has, if E2 is
2941  //        an rvalue).
2942  //
2943  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2944  // to the array-to-pointer or function-to-pointer conversions.
2945  if (!TTy->getAs<TagType>())
2946    TTy = TTy.getUnqualifiedType();
2947
2948  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2949  InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2950  HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2951  ToType = TTy;
2952  if (InitSeq.isAmbiguous())
2953    return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2954
2955  return false;
2956}
2957
2958/// \brief Try to find a common type for two according to C++0x 5.16p5.
2959///
2960/// This is part of the parameter validation for the ? operator. If either
2961/// value operand is a class type, overload resolution is used to find a
2962/// conversion to a common type.
2963static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
2964                                    SourceLocation QuestionLoc) {
2965  Expr *Args[2] = { LHS.get(), RHS.get() };
2966  OverloadCandidateSet CandidateSet(QuestionLoc);
2967  Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
2968                                    CandidateSet);
2969
2970  OverloadCandidateSet::iterator Best;
2971  switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
2972    case OR_Success: {
2973      // We found a match. Perform the conversions on the arguments and move on.
2974      ExprResult LHSRes =
2975        Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
2976                                       Best->Conversions[0], Sema::AA_Converting);
2977      if (LHSRes.isInvalid())
2978        break;
2979      LHS = move(LHSRes);
2980
2981      ExprResult RHSRes =
2982        Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
2983                                       Best->Conversions[1], Sema::AA_Converting);
2984      if (RHSRes.isInvalid())
2985        break;
2986      RHS = move(RHSRes);
2987      if (Best->Function)
2988        Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
2989      return false;
2990    }
2991
2992    case OR_No_Viable_Function:
2993
2994      // Emit a better diagnostic if one of the expressions is a null pointer
2995      // constant and the other is a pointer type. In this case, the user most
2996      // likely forgot to take the address of the other expression.
2997      if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
2998        return true;
2999
3000      Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3001        << LHS.get()->getType() << RHS.get()->getType()
3002        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3003      return true;
3004
3005    case OR_Ambiguous:
3006      Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
3007        << LHS.get()->getType() << RHS.get()->getType()
3008        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3009      // FIXME: Print the possible common types by printing the return types of
3010      // the viable candidates.
3011      break;
3012
3013    case OR_Deleted:
3014      assert(false && "Conditional operator has only built-in overloads");
3015      break;
3016  }
3017  return true;
3018}
3019
3020/// \brief Perform an "extended" implicit conversion as returned by
3021/// TryClassUnification.
3022static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
3023  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3024  InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
3025                                                           SourceLocation());
3026  Expr *Arg = E.take();
3027  InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3028  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
3029  if (Result.isInvalid())
3030    return true;
3031
3032  E = Result;
3033  return false;
3034}
3035
3036/// \brief Check the operands of ?: under C++ semantics.
3037///
3038/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3039/// extension. In this case, LHS == Cond. (But they're not aliases.)
3040QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
3041                                           ExprValueKind &VK, ExprObjectKind &OK,
3042                                           SourceLocation QuestionLoc) {
3043  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3044  // interface pointers.
3045
3046  // C++0x 5.16p1
3047  //   The first expression is contextually converted to bool.
3048  if (!Cond.get()->isTypeDependent()) {
3049    ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3050    if (CondRes.isInvalid())
3051      return QualType();
3052    Cond = move(CondRes);
3053  }
3054
3055  // Assume r-value.
3056  VK = VK_RValue;
3057  OK = OK_Ordinary;
3058
3059  // Either of the arguments dependent?
3060  if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
3061    return Context.DependentTy;
3062
3063  // C++0x 5.16p2
3064  //   If either the second or the third operand has type (cv) void, ...
3065  QualType LTy = LHS.get()->getType();
3066  QualType RTy = RHS.get()->getType();
3067  bool LVoid = LTy->isVoidType();
3068  bool RVoid = RTy->isVoidType();
3069  if (LVoid || RVoid) {
3070    //   ... then the [l2r] conversions are performed on the second and third
3071    //   operands ...
3072    LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3073    RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3074    if (LHS.isInvalid() || RHS.isInvalid())
3075      return QualType();
3076    LTy = LHS.get()->getType();
3077    RTy = RHS.get()->getType();
3078
3079    //   ... and one of the following shall hold:
3080    //   -- The second or the third operand (but not both) is a throw-
3081    //      expression; the result is of the type of the other and is an rvalue.
3082    bool LThrow = isa<CXXThrowExpr>(LHS.get());
3083    bool RThrow = isa<CXXThrowExpr>(RHS.get());
3084    if (LThrow && !RThrow)
3085      return RTy;
3086    if (RThrow && !LThrow)
3087      return LTy;
3088
3089    //   -- Both the second and third operands have type void; the result is of
3090    //      type void and is an rvalue.
3091    if (LVoid && RVoid)
3092      return Context.VoidTy;
3093
3094    // Neither holds, error.
3095    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3096      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3097      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3098    return QualType();
3099  }
3100
3101  // Neither is void.
3102
3103  // C++0x 5.16p3
3104  //   Otherwise, if the second and third operand have different types, and
3105  //   either has (cv) class type, and attempt is made to convert each of those
3106  //   operands to the other.
3107  if (!Context.hasSameType(LTy, RTy) &&
3108      (LTy->isRecordType() || RTy->isRecordType())) {
3109    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3110    // These return true if a single direction is already ambiguous.
3111    QualType L2RType, R2LType;
3112    bool HaveL2R, HaveR2L;
3113    if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
3114      return QualType();
3115    if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
3116      return QualType();
3117
3118    //   If both can be converted, [...] the program is ill-formed.
3119    if (HaveL2R && HaveR2L) {
3120      Diag(QuestionLoc, diag::err_conditional_ambiguous)
3121        << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3122      return QualType();
3123    }
3124
3125    //   If exactly one conversion is possible, that conversion is applied to
3126    //   the chosen operand and the converted operands are used in place of the
3127    //   original operands for the remainder of this section.
3128    if (HaveL2R) {
3129      if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
3130        return QualType();
3131      LTy = LHS.get()->getType();
3132    } else if (HaveR2L) {
3133      if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
3134        return QualType();
3135      RTy = RHS.get()->getType();
3136    }
3137  }
3138
3139  // C++0x 5.16p4
3140  //   If the second and third operands are glvalues of the same value
3141  //   category and have the same type, the result is of that type and
3142  //   value category and it is a bit-field if the second or the third
3143  //   operand is a bit-field, or if both are bit-fields.
3144  // We only extend this to bitfields, not to the crazy other kinds of
3145  // l-values.
3146  bool Same = Context.hasSameType(LTy, RTy);
3147  if (Same &&
3148      LHS.get()->isGLValue() &&
3149      LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3150      LHS.get()->isOrdinaryOrBitFieldObject() &&
3151      RHS.get()->isOrdinaryOrBitFieldObject()) {
3152    VK = LHS.get()->getValueKind();
3153    if (LHS.get()->getObjectKind() == OK_BitField ||
3154        RHS.get()->getObjectKind() == OK_BitField)
3155      OK = OK_BitField;
3156    return LTy;
3157  }
3158
3159  // C++0x 5.16p5
3160  //   Otherwise, the result is an rvalue. If the second and third operands
3161  //   do not have the same type, and either has (cv) class type, ...
3162  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3163    //   ... overload resolution is used to determine the conversions (if any)
3164    //   to be applied to the operands. If the overload resolution fails, the
3165    //   program is ill-formed.
3166    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3167      return QualType();
3168  }
3169
3170  // C++0x 5.16p6
3171  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3172  //   conversions are performed on the second and third operands.
3173  LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3174  RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3175  if (LHS.isInvalid() || RHS.isInvalid())
3176    return QualType();
3177  LTy = LHS.get()->getType();
3178  RTy = RHS.get()->getType();
3179
3180  //   After those conversions, one of the following shall hold:
3181  //   -- The second and third operands have the same type; the result
3182  //      is of that type. If the operands have class type, the result
3183  //      is a prvalue temporary of the result type, which is
3184  //      copy-initialized from either the second operand or the third
3185  //      operand depending on the value of the first operand.
3186  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3187    if (LTy->isRecordType()) {
3188      // The operands have class type. Make a temporary copy.
3189      InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
3190      ExprResult LHSCopy = PerformCopyInitialization(Entity,
3191                                                     SourceLocation(),
3192                                                     LHS);
3193      if (LHSCopy.isInvalid())
3194        return QualType();
3195
3196      ExprResult RHSCopy = PerformCopyInitialization(Entity,
3197                                                     SourceLocation(),
3198                                                     RHS);
3199      if (RHSCopy.isInvalid())
3200        return QualType();
3201
3202      LHS = LHSCopy;
3203      RHS = RHSCopy;
3204    }
3205
3206    return LTy;
3207  }
3208
3209  // Extension: conditional operator involving vector types.
3210  if (LTy->isVectorType() || RTy->isVectorType())
3211    return CheckVectorOperands(QuestionLoc, LHS, RHS);
3212
3213  //   -- The second and third operands have arithmetic or enumeration type;
3214  //      the usual arithmetic conversions are performed to bring them to a
3215  //      common type, and the result is of that type.
3216  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3217    UsualArithmeticConversions(LHS, RHS);
3218    if (LHS.isInvalid() || RHS.isInvalid())
3219      return QualType();
3220    return LHS.get()->getType();
3221  }
3222
3223  //   -- The second and third operands have pointer type, or one has pointer
3224  //      type and the other is a null pointer constant; pointer conversions
3225  //      and qualification conversions are performed to bring them to their
3226  //      composite pointer type. The result is of the composite pointer type.
3227  //   -- The second and third operands have pointer to member type, or one has
3228  //      pointer to member type and the other is a null pointer constant;
3229  //      pointer to member conversions and qualification conversions are
3230  //      performed to bring them to a common type, whose cv-qualification
3231  //      shall match the cv-qualification of either the second or the third
3232  //      operand. The result is of the common type.
3233  bool NonStandardCompositeType = false;
3234  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
3235                              isSFINAEContext()? 0 : &NonStandardCompositeType);
3236  if (!Composite.isNull()) {
3237    if (NonStandardCompositeType)
3238      Diag(QuestionLoc,
3239           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3240        << LTy << RTy << Composite
3241        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3242
3243    return Composite;
3244  }
3245
3246  // Similarly, attempt to find composite type of two objective-c pointers.
3247  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3248  if (!Composite.isNull())
3249    return Composite;
3250
3251  // Check if we are using a null with a non-pointer type.
3252  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3253    return QualType();
3254
3255  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3256    << LHS.get()->getType() << RHS.get()->getType()
3257    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3258  return QualType();
3259}
3260
3261/// \brief Find a merged pointer type and convert the two expressions to it.
3262///
3263/// This finds the composite pointer type (or member pointer type) for @p E1
3264/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3265/// type and returns it.
3266/// It does not emit diagnostics.
3267///
3268/// \param Loc The location of the operator requiring these two expressions to
3269/// be converted to the composite pointer type.
3270///
3271/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3272/// a non-standard (but still sane) composite type to which both expressions
3273/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3274/// will be set true.
3275QualType Sema::FindCompositePointerType(SourceLocation Loc,
3276                                        Expr *&E1, Expr *&E2,
3277                                        bool *NonStandardCompositeType) {
3278  if (NonStandardCompositeType)
3279    *NonStandardCompositeType = false;
3280
3281  assert(getLangOptions().CPlusPlus && "This function assumes C++");
3282  QualType T1 = E1->getType(), T2 = E2->getType();
3283
3284  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3285      !T2->isAnyPointerType() && !T2->isMemberPointerType())
3286   return QualType();
3287
3288  // C++0x 5.9p2
3289  //   Pointer conversions and qualification conversions are performed on
3290  //   pointer operands to bring them to their composite pointer type. If
3291  //   one operand is a null pointer constant, the composite pointer type is
3292  //   the type of the other operand.
3293  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3294    if (T2->isMemberPointerType())
3295      E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
3296    else
3297      E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
3298    return T2;
3299  }
3300  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3301    if (T1->isMemberPointerType())
3302      E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
3303    else
3304      E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
3305    return T1;
3306  }
3307
3308  // Now both have to be pointers or member pointers.
3309  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3310      (!T2->isPointerType() && !T2->isMemberPointerType()))
3311    return QualType();
3312
3313  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
3314  //   the other has type "pointer to cv2 T" and the composite pointer type is
3315  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3316  //   Otherwise, the composite pointer type is a pointer type similar to the
3317  //   type of one of the operands, with a cv-qualification signature that is
3318  //   the union of the cv-qualification signatures of the operand types.
3319  // In practice, the first part here is redundant; it's subsumed by the second.
3320  // What we do here is, we build the two possible composite types, and try the
3321  // conversions in both directions. If only one works, or if the two composite
3322  // types are the same, we have succeeded.
3323  // FIXME: extended qualifiers?
3324  typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3325  QualifierVector QualifierUnion;
3326  typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3327      ContainingClassVector;
3328  ContainingClassVector MemberOfClass;
3329  QualType Composite1 = Context.getCanonicalType(T1),
3330           Composite2 = Context.getCanonicalType(T2);
3331  unsigned NeedConstBefore = 0;
3332  do {
3333    const PointerType *Ptr1, *Ptr2;
3334    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3335        (Ptr2 = Composite2->getAs<PointerType>())) {
3336      Composite1 = Ptr1->getPointeeType();
3337      Composite2 = Ptr2->getPointeeType();
3338
3339      // If we're allowed to create a non-standard composite type, keep track
3340      // of where we need to fill in additional 'const' qualifiers.
3341      if (NonStandardCompositeType &&
3342          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3343        NeedConstBefore = QualifierUnion.size();
3344
3345      QualifierUnion.push_back(
3346                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3347      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3348      continue;
3349    }
3350
3351    const MemberPointerType *MemPtr1, *MemPtr2;
3352    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3353        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3354      Composite1 = MemPtr1->getPointeeType();
3355      Composite2 = MemPtr2->getPointeeType();
3356
3357      // If we're allowed to create a non-standard composite type, keep track
3358      // of where we need to fill in additional 'const' qualifiers.
3359      if (NonStandardCompositeType &&
3360          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3361        NeedConstBefore = QualifierUnion.size();
3362
3363      QualifierUnion.push_back(
3364                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3365      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3366                                             MemPtr2->getClass()));
3367      continue;
3368    }
3369
3370    // FIXME: block pointer types?
3371
3372    // Cannot unwrap any more types.
3373    break;
3374  } while (true);
3375
3376  if (NeedConstBefore && NonStandardCompositeType) {
3377    // Extension: Add 'const' to qualifiers that come before the first qualifier
3378    // mismatch, so that our (non-standard!) composite type meets the
3379    // requirements of C++ [conv.qual]p4 bullet 3.
3380    for (unsigned I = 0; I != NeedConstBefore; ++I) {
3381      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3382        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3383        *NonStandardCompositeType = true;
3384      }
3385    }
3386  }
3387
3388  // Rewrap the composites as pointers or member pointers with the union CVRs.
3389  ContainingClassVector::reverse_iterator MOC
3390    = MemberOfClass.rbegin();
3391  for (QualifierVector::reverse_iterator
3392         I = QualifierUnion.rbegin(),
3393         E = QualifierUnion.rend();
3394       I != E; (void)++I, ++MOC) {
3395    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
3396    if (MOC->first && MOC->second) {
3397      // Rebuild member pointer type
3398      Composite1 = Context.getMemberPointerType(
3399                                    Context.getQualifiedType(Composite1, Quals),
3400                                    MOC->first);
3401      Composite2 = Context.getMemberPointerType(
3402                                    Context.getQualifiedType(Composite2, Quals),
3403                                    MOC->second);
3404    } else {
3405      // Rebuild pointer type
3406      Composite1
3407        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3408      Composite2
3409        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
3410    }
3411  }
3412
3413  // Try to convert to the first composite pointer type.
3414  InitializedEntity Entity1
3415    = InitializedEntity::InitializeTemporary(Composite1);
3416  InitializationKind Kind
3417    = InitializationKind::CreateCopy(Loc, SourceLocation());
3418  InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3419  InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
3420
3421  if (E1ToC1 && E2ToC1) {
3422    // Conversion to Composite1 is viable.
3423    if (!Context.hasSameType(Composite1, Composite2)) {
3424      // Composite2 is a different type from Composite1. Check whether
3425      // Composite2 is also viable.
3426      InitializedEntity Entity2
3427        = InitializedEntity::InitializeTemporary(Composite2);
3428      InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3429      InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3430      if (E1ToC2 && E2ToC2) {
3431        // Both Composite1 and Composite2 are viable and are different;
3432        // this is an ambiguity.
3433        return QualType();
3434      }
3435    }
3436
3437    // Convert E1 to Composite1
3438    ExprResult E1Result
3439      = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
3440    if (E1Result.isInvalid())
3441      return QualType();
3442    E1 = E1Result.takeAs<Expr>();
3443
3444    // Convert E2 to Composite1
3445    ExprResult E2Result
3446      = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
3447    if (E2Result.isInvalid())
3448      return QualType();
3449    E2 = E2Result.takeAs<Expr>();
3450
3451    return Composite1;
3452  }
3453
3454  // Check whether Composite2 is viable.
3455  InitializedEntity Entity2
3456    = InitializedEntity::InitializeTemporary(Composite2);
3457  InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3458  InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3459  if (!E1ToC2 || !E2ToC2)
3460    return QualType();
3461
3462  // Convert E1 to Composite2
3463  ExprResult E1Result
3464    = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
3465  if (E1Result.isInvalid())
3466    return QualType();
3467  E1 = E1Result.takeAs<Expr>();
3468
3469  // Convert E2 to Composite2
3470  ExprResult E2Result
3471    = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
3472  if (E2Result.isInvalid())
3473    return QualType();
3474  E2 = E2Result.takeAs<Expr>();
3475
3476  return Composite2;
3477}
3478
3479ExprResult Sema::MaybeBindToTemporary(Expr *E) {
3480  if (!E)
3481    return ExprError();
3482
3483  if (!Context.getLangOptions().CPlusPlus)
3484    return Owned(E);
3485
3486  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3487
3488  const RecordType *RT = E->getType()->getAs<RecordType>();
3489  if (!RT)
3490    return Owned(E);
3491
3492  // If the result is a glvalue, we shouldn't bind it.
3493  if (E->Classify(Context).isGLValue())
3494    return Owned(E);
3495
3496  // That should be enough to guarantee that this type is complete.
3497  // If it has a trivial destructor, we can avoid the extra copy.
3498  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3499  if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
3500    return Owned(E);
3501
3502  CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
3503  ExprTemporaries.push_back(Temp);
3504  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
3505    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
3506    CheckDestructorAccess(E->getExprLoc(), Destructor,
3507                          PDiag(diag::err_access_dtor_temp)
3508                            << E->getType());
3509  }
3510  // FIXME: Add the temporary to the temporaries vector.
3511  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3512}
3513
3514Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
3515  assert(SubExpr && "sub expression can't be null!");
3516
3517  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3518  assert(ExprTemporaries.size() >= FirstTemporary);
3519  if (ExprTemporaries.size() == FirstTemporary)
3520    return SubExpr;
3521
3522  Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3523                                     &ExprTemporaries[FirstTemporary],
3524                                     ExprTemporaries.size() - FirstTemporary);
3525  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3526                        ExprTemporaries.end());
3527
3528  return E;
3529}
3530
3531ExprResult
3532Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
3533  if (SubExpr.isInvalid())
3534    return ExprError();
3535
3536  return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
3537}
3538
3539Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
3540  assert(SubStmt && "sub statement can't be null!");
3541
3542  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3543  assert(ExprTemporaries.size() >= FirstTemporary);
3544  if (ExprTemporaries.size() == FirstTemporary)
3545    return SubStmt;
3546
3547  // FIXME: In order to attach the temporaries, wrap the statement into
3548  // a StmtExpr; currently this is only used for asm statements.
3549  // This is hacky, either create a new CXXStmtWithTemporaries statement or
3550  // a new AsmStmtWithTemporaries.
3551  CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3552                                                      SourceLocation(),
3553                                                      SourceLocation());
3554  Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3555                                   SourceLocation());
3556  return MaybeCreateExprWithCleanups(E);
3557}
3558
3559ExprResult
3560Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
3561                                   tok::TokenKind OpKind, ParsedType &ObjectType,
3562                                   bool &MayBePseudoDestructor) {
3563  // Since this might be a postfix expression, get rid of ParenListExprs.
3564  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3565  if (Result.isInvalid()) return ExprError();
3566  Base = Result.get();
3567
3568  QualType BaseType = Base->getType();
3569  MayBePseudoDestructor = false;
3570  if (BaseType->isDependentType()) {
3571    // If we have a pointer to a dependent type and are using the -> operator,
3572    // the object type is the type that the pointer points to. We might still
3573    // have enough information about that type to do something useful.
3574    if (OpKind == tok::arrow)
3575      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3576        BaseType = Ptr->getPointeeType();
3577
3578    ObjectType = ParsedType::make(BaseType);
3579    MayBePseudoDestructor = true;
3580    return Owned(Base);
3581  }
3582
3583  // C++ [over.match.oper]p8:
3584  //   [...] When operator->returns, the operator-> is applied  to the value
3585  //   returned, with the original second operand.
3586  if (OpKind == tok::arrow) {
3587    // The set of types we've considered so far.
3588    llvm::SmallPtrSet<CanQualType,8> CTypes;
3589    llvm::SmallVector<SourceLocation, 8> Locations;
3590    CTypes.insert(Context.getCanonicalType(BaseType));
3591
3592    while (BaseType->isRecordType()) {
3593      Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3594      if (Result.isInvalid())
3595        return ExprError();
3596      Base = Result.get();
3597      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
3598        Locations.push_back(OpCall->getDirectCallee()->getLocation());
3599      BaseType = Base->getType();
3600      CanQualType CBaseType = Context.getCanonicalType(BaseType);
3601      if (!CTypes.insert(CBaseType)) {
3602        Diag(OpLoc, diag::err_operator_arrow_circular);
3603        for (unsigned i = 0; i < Locations.size(); i++)
3604          Diag(Locations[i], diag::note_declared_at);
3605        return ExprError();
3606      }
3607    }
3608
3609    if (BaseType->isPointerType())
3610      BaseType = BaseType->getPointeeType();
3611  }
3612
3613  // We could end up with various non-record types here, such as extended
3614  // vector types or Objective-C interfaces. Just return early and let
3615  // ActOnMemberReferenceExpr do the work.
3616  if (!BaseType->isRecordType()) {
3617    // C++ [basic.lookup.classref]p2:
3618    //   [...] If the type of the object expression is of pointer to scalar
3619    //   type, the unqualified-id is looked up in the context of the complete
3620    //   postfix-expression.
3621    //
3622    // This also indicates that we should be parsing a
3623    // pseudo-destructor-name.
3624    ObjectType = ParsedType();
3625    MayBePseudoDestructor = true;
3626    return Owned(Base);
3627  }
3628
3629  // The object type must be complete (or dependent).
3630  if (!BaseType->isDependentType() &&
3631      RequireCompleteType(OpLoc, BaseType,
3632                          PDiag(diag::err_incomplete_member_access)))
3633    return ExprError();
3634
3635  // C++ [basic.lookup.classref]p2:
3636  //   If the id-expression in a class member access (5.2.5) is an
3637  //   unqualified-id, and the type of the object expression is of a class
3638  //   type C (or of pointer to a class type C), the unqualified-id is looked
3639  //   up in the scope of class C. [...]
3640  ObjectType = ParsedType::make(BaseType);
3641  return move(Base);
3642}
3643
3644ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
3645                                                   Expr *MemExpr) {
3646  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
3647  Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3648    << isa<CXXPseudoDestructorExpr>(MemExpr)
3649    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
3650
3651  return ActOnCallExpr(/*Scope*/ 0,
3652                       MemExpr,
3653                       /*LPLoc*/ ExpectedLParenLoc,
3654                       MultiExprArg(),
3655                       /*RPLoc*/ ExpectedLParenLoc);
3656}
3657
3658ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
3659                                           SourceLocation OpLoc,
3660                                           tok::TokenKind OpKind,
3661                                           const CXXScopeSpec &SS,
3662                                           TypeSourceInfo *ScopeTypeInfo,
3663                                           SourceLocation CCLoc,
3664                                           SourceLocation TildeLoc,
3665                                         PseudoDestructorTypeStorage Destructed,
3666                                           bool HasTrailingLParen) {
3667  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
3668
3669  // C++ [expr.pseudo]p2:
3670  //   The left-hand side of the dot operator shall be of scalar type. The
3671  //   left-hand side of the arrow operator shall be of pointer to scalar type.
3672  //   This scalar type is the object type.
3673  QualType ObjectType = Base->getType();
3674  if (OpKind == tok::arrow) {
3675    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3676      ObjectType = Ptr->getPointeeType();
3677    } else if (!Base->isTypeDependent()) {
3678      // The user wrote "p->" when she probably meant "p."; fix it.
3679      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3680        << ObjectType << true
3681        << FixItHint::CreateReplacement(OpLoc, ".");
3682      if (isSFINAEContext())
3683        return ExprError();
3684
3685      OpKind = tok::period;
3686    }
3687  }
3688
3689  if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3690    Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
3691      << ObjectType << Base->getSourceRange();
3692    return ExprError();
3693  }
3694
3695  // C++ [expr.pseudo]p2:
3696  //   [...] The cv-unqualified versions of the object type and of the type
3697  //   designated by the pseudo-destructor-name shall be the same type.
3698  if (DestructedTypeInfo) {
3699    QualType DestructedType = DestructedTypeInfo->getType();
3700    SourceLocation DestructedTypeStart
3701      = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
3702    if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3703        !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3704      Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
3705        << ObjectType << DestructedType << Base->getSourceRange()
3706        << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
3707
3708      // Recover by setting the destructed type to the object type.
3709      DestructedType = ObjectType;
3710      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3711                                                           DestructedTypeStart);
3712      Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3713    }
3714  }
3715
3716  // C++ [expr.pseudo]p2:
3717  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3718  //   form
3719  //
3720  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
3721  //
3722  //   shall designate the same scalar type.
3723  if (ScopeTypeInfo) {
3724    QualType ScopeType = ScopeTypeInfo->getType();
3725    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
3726        !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
3727
3728      Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
3729           diag::err_pseudo_dtor_type_mismatch)
3730        << ObjectType << ScopeType << Base->getSourceRange()
3731        << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
3732
3733      ScopeType = QualType();
3734      ScopeTypeInfo = 0;
3735    }
3736  }
3737
3738  Expr *Result
3739    = new (Context) CXXPseudoDestructorExpr(Context, Base,
3740                                            OpKind == tok::arrow, OpLoc,
3741                                            SS.getWithLocInContext(Context),
3742                                            ScopeTypeInfo,
3743                                            CCLoc,
3744                                            TildeLoc,
3745                                            Destructed);
3746
3747  if (HasTrailingLParen)
3748    return Owned(Result);
3749
3750  return DiagnoseDtorReference(Destructed.getLocation(), Result);
3751}
3752
3753ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
3754                                           SourceLocation OpLoc,
3755                                           tok::TokenKind OpKind,
3756                                           CXXScopeSpec &SS,
3757                                           UnqualifiedId &FirstTypeName,
3758                                           SourceLocation CCLoc,
3759                                           SourceLocation TildeLoc,
3760                                           UnqualifiedId &SecondTypeName,
3761                                           bool HasTrailingLParen) {
3762  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3763          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3764         "Invalid first type name in pseudo-destructor");
3765  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3766          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3767         "Invalid second type name in pseudo-destructor");
3768
3769  // C++ [expr.pseudo]p2:
3770  //   The left-hand side of the dot operator shall be of scalar type. The
3771  //   left-hand side of the arrow operator shall be of pointer to scalar type.
3772  //   This scalar type is the object type.
3773  QualType ObjectType = Base->getType();
3774  if (OpKind == tok::arrow) {
3775    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3776      ObjectType = Ptr->getPointeeType();
3777    } else if (!ObjectType->isDependentType()) {
3778      // The user wrote "p->" when she probably meant "p."; fix it.
3779      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3780        << ObjectType << true
3781        << FixItHint::CreateReplacement(OpLoc, ".");
3782      if (isSFINAEContext())
3783        return ExprError();
3784
3785      OpKind = tok::period;
3786    }
3787  }
3788
3789  // Compute the object type that we should use for name lookup purposes. Only
3790  // record types and dependent types matter.
3791  ParsedType ObjectTypePtrForLookup;
3792  if (!SS.isSet()) {
3793    if (ObjectType->isRecordType())
3794      ObjectTypePtrForLookup = ParsedType::make(ObjectType);
3795    else if (ObjectType->isDependentType())
3796      ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
3797  }
3798
3799  // Convert the name of the type being destructed (following the ~) into a
3800  // type (with source-location information).
3801  QualType DestructedType;
3802  TypeSourceInfo *DestructedTypeInfo = 0;
3803  PseudoDestructorTypeStorage Destructed;
3804  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
3805    ParsedType T = getTypeName(*SecondTypeName.Identifier,
3806                               SecondTypeName.StartLocation,
3807                               S, &SS, true, false, ObjectTypePtrForLookup);
3808    if (!T &&
3809        ((SS.isSet() && !computeDeclContext(SS, false)) ||
3810         (!SS.isSet() && ObjectType->isDependentType()))) {
3811      // The name of the type being destroyed is a dependent name, and we
3812      // couldn't find anything useful in scope. Just store the identifier and
3813      // it's location, and we'll perform (qualified) name lookup again at
3814      // template instantiation time.
3815      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3816                                               SecondTypeName.StartLocation);
3817    } else if (!T) {
3818      Diag(SecondTypeName.StartLocation,
3819           diag::err_pseudo_dtor_destructor_non_type)
3820        << SecondTypeName.Identifier << ObjectType;
3821      if (isSFINAEContext())
3822        return ExprError();
3823
3824      // Recover by assuming we had the right type all along.
3825      DestructedType = ObjectType;
3826    } else
3827      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
3828  } else {
3829    // Resolve the template-id to a type.
3830    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
3831    ASTTemplateArgsPtr TemplateArgsPtr(*this,
3832                                       TemplateId->getTemplateArgs(),
3833                                       TemplateId->NumArgs);
3834    TypeResult T = ActOnTemplateIdType(TemplateId->SS,
3835                                       TemplateId->Template,
3836                                       TemplateId->TemplateNameLoc,
3837                                       TemplateId->LAngleLoc,
3838                                       TemplateArgsPtr,
3839                                       TemplateId->RAngleLoc);
3840    if (T.isInvalid() || !T.get()) {
3841      // Recover by assuming we had the right type all along.
3842      DestructedType = ObjectType;
3843    } else
3844      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
3845  }
3846
3847  // If we've performed some kind of recovery, (re-)build the type source
3848  // information.
3849  if (!DestructedType.isNull()) {
3850    if (!DestructedTypeInfo)
3851      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
3852                                                  SecondTypeName.StartLocation);
3853    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3854  }
3855
3856  // Convert the name of the scope type (the type prior to '::') into a type.
3857  TypeSourceInfo *ScopeTypeInfo = 0;
3858  QualType ScopeType;
3859  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3860      FirstTypeName.Identifier) {
3861    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
3862      ParsedType T = getTypeName(*FirstTypeName.Identifier,
3863                                 FirstTypeName.StartLocation,
3864                                 S, &SS, true, false, ObjectTypePtrForLookup);
3865      if (!T) {
3866        Diag(FirstTypeName.StartLocation,
3867             diag::err_pseudo_dtor_destructor_non_type)
3868          << FirstTypeName.Identifier << ObjectType;
3869
3870        if (isSFINAEContext())
3871          return ExprError();
3872
3873        // Just drop this type. It's unnecessary anyway.
3874        ScopeType = QualType();
3875      } else
3876        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
3877    } else {
3878      // Resolve the template-id to a type.
3879      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
3880      ASTTemplateArgsPtr TemplateArgsPtr(*this,
3881                                         TemplateId->getTemplateArgs(),
3882                                         TemplateId->NumArgs);
3883      TypeResult T = ActOnTemplateIdType(TemplateId->SS,
3884                                         TemplateId->Template,
3885                                         TemplateId->TemplateNameLoc,
3886                                         TemplateId->LAngleLoc,
3887                                         TemplateArgsPtr,
3888                                         TemplateId->RAngleLoc);
3889      if (T.isInvalid() || !T.get()) {
3890        // Recover by dropping this type.
3891        ScopeType = QualType();
3892      } else
3893        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
3894    }
3895  }
3896
3897  if (!ScopeType.isNull() && !ScopeTypeInfo)
3898    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3899                                                  FirstTypeName.StartLocation);
3900
3901
3902  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
3903                                   ScopeTypeInfo, CCLoc, TildeLoc,
3904                                   Destructed, HasTrailingLParen);
3905}
3906
3907ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
3908                                        CXXMethodDecl *Method) {
3909  ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
3910                                          FoundDecl, Method);
3911  if (Exp.isInvalid())
3912    return true;
3913
3914  MemberExpr *ME =
3915      new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
3916                               SourceLocation(), Method->getType(),
3917                               VK_RValue, OK_Ordinary);
3918  QualType ResultType = Method->getResultType();
3919  ExprValueKind VK = Expr::getValueKindForType(ResultType);
3920  ResultType = ResultType.getNonLValueExprType(Context);
3921
3922  MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
3923  CXXMemberCallExpr *CE =
3924    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
3925                                    Exp.get()->getLocEnd());
3926  return CE;
3927}
3928
3929ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3930                                      SourceLocation RParen) {
3931  return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3932                                             Operand->CanThrow(Context),
3933                                             KeyLoc, RParen));
3934}
3935
3936ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3937                                   Expr *Operand, SourceLocation RParen) {
3938  return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
3939}
3940
3941/// Perform the conversions required for an expression used in a
3942/// context that ignores the result.
3943ExprResult Sema::IgnoredValueConversions(Expr *E) {
3944  // C99 6.3.2.1:
3945  //   [Except in specific positions,] an lvalue that does not have
3946  //   array type is converted to the value stored in the
3947  //   designated object (and is no longer an lvalue).
3948  if (E->isRValue()) return Owned(E);
3949
3950  // We always want to do this on ObjC property references.
3951  if (E->getObjectKind() == OK_ObjCProperty) {
3952    ExprResult Res = ConvertPropertyForRValue(E);
3953    if (Res.isInvalid()) return Owned(E);
3954    E = Res.take();
3955    if (E->isRValue()) return Owned(E);
3956  }
3957
3958  // Otherwise, this rule does not apply in C++, at least not for the moment.
3959  if (getLangOptions().CPlusPlus) return Owned(E);
3960
3961  // GCC seems to also exclude expressions of incomplete enum type.
3962  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3963    if (!T->getDecl()->isComplete()) {
3964      // FIXME: stupid workaround for a codegen bug!
3965      E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
3966      return Owned(E);
3967    }
3968  }
3969
3970  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
3971  if (Res.isInvalid())
3972    return Owned(E);
3973  E = Res.take();
3974
3975  if (!E->getType()->isVoidType())
3976    RequireCompleteType(E->getExprLoc(), E->getType(),
3977                        diag::err_incomplete_type);
3978  return Owned(E);
3979}
3980
3981ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
3982  ExprResult FullExpr = Owned(FE);
3983
3984  if (!FullExpr.get())
3985    return ExprError();
3986
3987  if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
3988    return ExprError();
3989
3990  // 13.4.1 ... An overloaded function name shall not be used without arguments
3991  //         in contexts other than those listed [i.e list of targets].
3992  //
3993  //  void foo(); void foo(int);
3994  //  template<class T> void fooT(); template<class T> void fooT(int);
3995
3996  //  Therefore these should error:
3997  //  foo;
3998  //  fooT<int>;
3999
4000  if (FullExpr.get()->getType() == Context.OverloadTy) {
4001    ExprResult Fixed
4002      = ResolveAndFixSingleFunctionTemplateSpecialization(FullExpr.get(),
4003                                        /*DoFunctionPointerConversion=*/false,
4004                                                          /*Complain=*/true,
4005                                                    FullExpr.get()->getSourceRange(),
4006                                                          QualType(),
4007                                                 diag::err_addr_ovl_ambiguous);
4008    if (Fixed.isInvalid())
4009      return ExprError();
4010
4011    FullExpr = Fixed.get();
4012  }
4013
4014
4015  FullExpr = IgnoredValueConversions(FullExpr.take());
4016  if (FullExpr.isInvalid())
4017    return ExprError();
4018
4019  CheckImplicitConversions(FullExpr.get());
4020  return MaybeCreateExprWithCleanups(FullExpr);
4021}
4022
4023StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4024  if (!FullStmt) return StmtError();
4025
4026  return MaybeCreateStmtWithCleanups(FullStmt);
4027}
4028