SemaExprCXX.cpp revision 944c37abb8acd1e14e73176922ee351db6a0f62f
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 "Sema.h"
15#include "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/TypeLoc.h"
21#include "clang/Basic/PartialDiagnostic.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Template.h"
26#include "llvm/ADT/STLExtras.h"
27using namespace clang;
28
29Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30                                        IdentifierInfo &II,
31                                        SourceLocation NameLoc,
32                                        Scope *S, CXXScopeSpec &SS,
33                                        TypeTy *ObjectTypePtr,
34                                        bool EnteringContext) {
35  // Determine where to perform name lookup.
36
37  // FIXME: This area of the standard is very messy, and the current
38  // wording is rather unclear about which scopes we search for the
39  // destructor name; see core issues 399 and 555. Issue 399 in
40  // particular shows where the current description of destructor name
41  // lookup is completely out of line with existing practice, e.g.,
42  // this appears to be ill-formed:
43  //
44  //   namespace N {
45  //     template <typename T> struct S {
46  //       ~S();
47  //     };
48  //   }
49  //
50  //   void f(N::S<int>* s) {
51  //     s->N::S<int>::~S();
52  //   }
53  //
54  // See also PR6358 and PR6359.
55  QualType SearchType;
56  DeclContext *LookupCtx = 0;
57  bool isDependent = false;
58  bool LookInScope = false;
59
60  // If we have an object type, it's because we are in a
61  // pseudo-destructor-expression or a member access expression, and
62  // we know what type we're looking for.
63  if (ObjectTypePtr)
64    SearchType = GetTypeFromParser(ObjectTypePtr);
65
66  if (SS.isSet()) {
67    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68
69    bool AlreadySearched = false;
70    bool LookAtPrefix = true;
71    if (!getLangOptions().CPlusPlus0x) {
72      // C++ [basic.lookup.qual]p6:
73      //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
74      //   the type-names are looked up as types in the scope designated by the
75      //   nested-name-specifier. In a qualified-id of the form:
76      //
77      //     ::[opt] nested-name-specifier  ̃ class-name
78      //
79      //   where the nested-name-specifier designates a namespace scope, and in
80      //   a qualified-id of the form:
81      //
82      //     ::opt nested-name-specifier class-name ::  ̃ class-name
83      //
84      //   the class-names are looked up as types in the scope designated by
85      //   the nested-name-specifier.
86      //
87      // Here, we check the first case (completely) and determine whether the
88      // code below is permitted to look at the prefix of the
89      // nested-name-specifier (as we do in C++0x).
90      DeclContext *DC = computeDeclContext(SS, EnteringContext);
91      if (DC && DC->isFileContext()) {
92        AlreadySearched = true;
93        LookupCtx = DC;
94        isDependent = false;
95      } else if (DC && isa<CXXRecordDecl>(DC))
96        LookAtPrefix = false;
97    }
98
99    // C++0x [basic.lookup.qual]p6:
100    //   If a pseudo-destructor-name (5.2.4) contains a
101    //   nested-name-specifier, the type-names are looked up as types
102    //   in the scope designated by the nested-name-specifier. Similarly, in
103    //   a qualified-id of the form:
104    //
105    //     :: [opt] nested-name-specifier[opt] class-name :: ~class-name
106    //
107    //   the second class-name is looked up in the same scope as the first.
108    //
109    // To implement this, we look at the prefix of the
110    // nested-name-specifier we were given, and determine the lookup
111    // context from that.
112    //
113    // We also fold in the second case from the C++03 rules quoted further
114    // above.
115    NestedNameSpecifier *Prefix = 0;
116    if (AlreadySearched) {
117      // Nothing left to do.
118    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119      CXXScopeSpec PrefixSS;
120      PrefixSS.setScopeRep(Prefix);
121      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122      isDependent = isDependentScopeSpecifier(PrefixSS);
123    } else if (getLangOptions().CPlusPlus0x &&
124               (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125      if (!LookupCtx->isTranslationUnit())
126        LookupCtx = LookupCtx->getParent();
127      isDependent = LookupCtx && LookupCtx->isDependentContext();
128    } else if (ObjectTypePtr) {
129      LookupCtx = computeDeclContext(SearchType);
130      isDependent = SearchType->isDependentType();
131    } else {
132      LookupCtx = computeDeclContext(SS, EnteringContext);
133      isDependent = LookupCtx && LookupCtx->isDependentContext();
134    }
135
136    LookInScope = false;
137  } else if (ObjectTypePtr) {
138    // C++ [basic.lookup.classref]p3:
139    //   If the unqualified-id is ~type-name, the type-name is looked up
140    //   in the context of the entire postfix-expression. If the type T
141    //   of the object expression is of a class type C, the type-name is
142    //   also looked up in the scope of class C. At least one of the
143    //   lookups shall find a name that refers to (possibly
144    //   cv-qualified) T.
145    LookupCtx = computeDeclContext(SearchType);
146    isDependent = SearchType->isDependentType();
147    assert((isDependent || !SearchType->isIncompleteType()) &&
148           "Caller should have completed object type");
149
150    LookInScope = true;
151  } else {
152    // Perform lookup into the current scope (only).
153    LookInScope = true;
154  }
155
156  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157  for (unsigned Step = 0; Step != 2; ++Step) {
158    // Look for the name first in the computed lookup context (if we
159    // have one) and, if that fails to find a match, in the sope (if
160    // we're allowed to look there).
161    Found.clear();
162    if (Step == 0 && LookupCtx)
163      LookupQualifiedName(Found, LookupCtx);
164    else if (Step == 1 && LookInScope && S)
165      LookupName(Found, S);
166    else
167      continue;
168
169    // FIXME: Should we be suppressing ambiguities here?
170    if (Found.isAmbiguous())
171      return 0;
172
173    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174      QualType T = Context.getTypeDeclType(Type);
175
176      if (SearchType.isNull() || SearchType->isDependentType() ||
177          Context.hasSameUnqualifiedType(T, SearchType)) {
178        // We found our type!
179
180        return T.getAsOpaquePtr();
181      }
182    }
183
184    // If the name that we found is a class template name, and it is
185    // the same name as the template name in the last part of the
186    // nested-name-specifier (if present) or the object type, then
187    // this is the destructor for that class.
188    // FIXME: This is a workaround until we get real drafting for core
189    // issue 399, for which there isn't even an obvious direction.
190    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
191      QualType MemberOfType;
192      if (SS.isSet()) {
193        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
194          // Figure out the type of the context, if it has one.
195          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196            MemberOfType = Context.getTypeDeclType(Record);
197        }
198      }
199      if (MemberOfType.isNull())
200        MemberOfType = SearchType;
201
202      if (MemberOfType.isNull())
203        continue;
204
205      // We're referring into a class template specialization. If the
206      // class template we found is the same as the template being
207      // specialized, we found what we are looking for.
208      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
209        if (ClassTemplateSpecializationDecl *Spec
210              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
211          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
212                Template->getCanonicalDecl())
213            return MemberOfType.getAsOpaquePtr();
214        }
215
216        continue;
217      }
218
219      // We're referring to an unresolved class template
220      // specialization. Determine whether we class template we found
221      // is the same as the template being specialized or, if we don't
222      // know which template is being specialized, that it at least
223      // has the same name.
224      if (const TemplateSpecializationType *SpecType
225            = MemberOfType->getAs<TemplateSpecializationType>()) {
226        TemplateName SpecName = SpecType->getTemplateName();
227
228        // The class template we found is the same template being
229        // specialized.
230        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
231          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
232            return MemberOfType.getAsOpaquePtr();
233
234          continue;
235        }
236
237        // The class template we found has the same name as the
238        // (dependent) template name being specialized.
239        if (DependentTemplateName *DepTemplate
240                                    = SpecName.getAsDependentTemplateName()) {
241          if (DepTemplate->isIdentifier() &&
242              DepTemplate->getIdentifier() == Template->getIdentifier())
243            return MemberOfType.getAsOpaquePtr();
244
245          continue;
246        }
247      }
248    }
249  }
250
251  if (isDependent) {
252    // We didn't find our type, but that's okay: it's dependent
253    // anyway.
254    NestedNameSpecifier *NNS = 0;
255    SourceRange Range;
256    if (SS.isSet()) {
257      NNS = (NestedNameSpecifier *)SS.getScopeRep();
258      Range = SourceRange(SS.getRange().getBegin(), NameLoc);
259    } else {
260      NNS = NestedNameSpecifier::Create(Context, &II);
261      Range = SourceRange(NameLoc);
262    }
263
264    return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
265  }
266
267  if (ObjectTypePtr)
268    Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
269      << &II;
270  else
271    Diag(NameLoc, diag::err_destructor_class_name);
272
273  return 0;
274}
275
276/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
277Action::OwningExprResult
278Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
279                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
280  if (!StdNamespace)
281    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
282
283  if (isType) {
284    // C++ [expr.typeid]p4:
285    //   The top-level cv-qualifiers of the lvalue expression or the type-id
286    //   that is the operand of typeid are always ignored.
287    // FIXME: Preserve type source info.
288    // FIXME: Preserve the type before we stripped the cv-qualifiers?
289    QualType T = GetTypeFromParser(TyOrExpr);
290    if (T.isNull())
291      return ExprError();
292
293    // C++ [expr.typeid]p4:
294    //   If the type of the type-id is a class type or a reference to a class
295    //   type, the class shall be completely-defined.
296    QualType CheckT = T;
297    if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
298      CheckT = RefType->getPointeeType();
299
300    if (CheckT->getAs<RecordType>() &&
301        RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
302      return ExprError();
303
304    TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
305  }
306
307  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
308  LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
309  LookupQualifiedName(R, StdNamespace);
310  RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
311  if (!TypeInfoRecordDecl)
312    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
313
314  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
315
316  if (!isType) {
317    bool isUnevaluatedOperand = true;
318    Expr *E = static_cast<Expr *>(TyOrExpr);
319    if (E && !E->isTypeDependent()) {
320      QualType T = E->getType();
321      if (const RecordType *RecordT = T->getAs<RecordType>()) {
322        CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
323        // C++ [expr.typeid]p3:
324        //   [...] If the type of the expression is a class type, the class
325        //   shall be completely-defined.
326        if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
327          return ExprError();
328
329        // C++ [expr.typeid]p3:
330        //   When typeid is applied to an expression other than an lvalue of a
331        //   polymorphic class type [...] [the] expression is an unevaluated
332        //   operand. [...]
333        if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
334          isUnevaluatedOperand = false;
335      }
336
337      // C++ [expr.typeid]p4:
338      //   [...] If the type of the type-id is a reference to a possibly
339      //   cv-qualified type, the result of the typeid expression refers to a
340      //   std::type_info object representing the cv-unqualified referenced
341      //   type.
342      if (T.hasQualifiers()) {
343        ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
344                          E->isLvalue(Context));
345        TyOrExpr = E;
346      }
347    }
348
349    // If this is an unevaluated operand, clear out the set of
350    // declaration references we have been computing and eliminate any
351    // temporaries introduced in its computation.
352    if (isUnevaluatedOperand)
353      ExprEvalContexts.back().Context = Unevaluated;
354  }
355
356  return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
357                                           TypeInfoType.withConst(),
358                                           SourceRange(OpLoc, RParenLoc)));
359}
360
361/// ActOnCXXBoolLiteral - Parse {true,false} literals.
362Action::OwningExprResult
363Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
364  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
365         "Unknown C++ Boolean value!");
366  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
367                                                Context.BoolTy, OpLoc));
368}
369
370/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
371Action::OwningExprResult
372Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
373  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
374}
375
376/// ActOnCXXThrow - Parse throw expressions.
377Action::OwningExprResult
378Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
379  Expr *Ex = E.takeAs<Expr>();
380  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
381    return ExprError();
382  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
383}
384
385/// CheckCXXThrowOperand - Validate the operand of a throw.
386bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
387  // C++ [except.throw]p3:
388  //   A throw-expression initializes a temporary object, called the exception
389  //   object, the type of which is determined by removing any top-level
390  //   cv-qualifiers from the static type of the operand of throw and adjusting
391  //   the type from "array of T" or "function returning T" to "pointer to T"
392  //   or "pointer to function returning T", [...]
393  if (E->getType().hasQualifiers())
394    ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
395                      E->isLvalue(Context) == Expr::LV_Valid);
396
397  DefaultFunctionArrayConversion(E);
398
399  //   If the type of the exception would be an incomplete type or a pointer
400  //   to an incomplete type other than (cv) void the program is ill-formed.
401  QualType Ty = E->getType();
402  int isPointer = 0;
403  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
404    Ty = Ptr->getPointeeType();
405    isPointer = 1;
406  }
407  if (!isPointer || !Ty->isVoidType()) {
408    if (RequireCompleteType(ThrowLoc, Ty,
409                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
410                                            : diag::err_throw_incomplete)
411                              << E->getSourceRange()))
412      return true;
413
414    if (RequireNonAbstractType(ThrowLoc, E->getType(),
415                               PDiag(diag::err_throw_abstract_type)
416                                 << E->getSourceRange()))
417      return true;
418
419    // FIXME: This is just a hack to mark the copy constructor referenced.
420    // This should go away when the next FIXME is fixed.
421    const RecordType *RT = Ty->getAs<RecordType>();
422    if (!RT)
423      return false;
424
425    const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
426    if (RD->hasTrivialCopyConstructor())
427      return false;
428    CXXConstructorDecl *CopyCtor = RD->getCopyConstructor(Context, 0);
429    MarkDeclarationReferenced(ThrowLoc, CopyCtor);
430  }
431
432  // FIXME: Construct a temporary here.
433  return false;
434}
435
436Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
437  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
438  /// is a non-lvalue expression whose value is the address of the object for
439  /// which the function is called.
440
441  if (!isa<FunctionDecl>(CurContext))
442    return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
443
444  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
445    if (MD->isInstance())
446      return Owned(new (Context) CXXThisExpr(ThisLoc,
447                                             MD->getThisType(Context),
448                                             /*isImplicit=*/false));
449
450  return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
451}
452
453/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
454/// Can be interpreted either as function-style casting ("int(x)")
455/// or class type construction ("ClassType(x,y,z)")
456/// or creation of a value-initialized type ("int()").
457Action::OwningExprResult
458Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
459                                SourceLocation LParenLoc,
460                                MultiExprArg exprs,
461                                SourceLocation *CommaLocs,
462                                SourceLocation RParenLoc) {
463  if (!TypeRep)
464    return ExprError();
465
466  TypeSourceInfo *TInfo;
467  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
468  if (!TInfo)
469    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
470  unsigned NumExprs = exprs.size();
471  Expr **Exprs = (Expr**)exprs.get();
472  SourceLocation TyBeginLoc = TypeRange.getBegin();
473  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
474
475  if (Ty->isDependentType() ||
476      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
477    exprs.release();
478
479    return Owned(CXXUnresolvedConstructExpr::Create(Context,
480                                                    TypeRange.getBegin(), Ty,
481                                                    LParenLoc,
482                                                    Exprs, NumExprs,
483                                                    RParenLoc));
484  }
485
486  if (Ty->isArrayType())
487    return ExprError(Diag(TyBeginLoc,
488                          diag::err_value_init_for_array_type) << FullRange);
489  if (!Ty->isVoidType() &&
490      RequireCompleteType(TyBeginLoc, Ty,
491                          PDiag(diag::err_invalid_incomplete_type_use)
492                            << FullRange))
493    return ExprError();
494
495  if (RequireNonAbstractType(TyBeginLoc, Ty,
496                             diag::err_allocation_of_abstract_type))
497    return ExprError();
498
499
500  // C++ [expr.type.conv]p1:
501  // If the expression list is a single expression, the type conversion
502  // expression is equivalent (in definedness, and if defined in meaning) to the
503  // corresponding cast expression.
504  //
505  if (NumExprs == 1) {
506    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
507    if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, /*FunctionalStyle=*/true))
508      return ExprError();
509
510    exprs.release();
511
512    return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
513                                                     TInfo, TyBeginLoc, Kind,
514                                                     Exprs[0], RParenLoc));
515  }
516
517  if (const RecordType *RT = Ty->getAs<RecordType>()) {
518    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
519
520    if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
521        !Record->hasTrivialDestructor()) {
522      InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
523      InitializationKind Kind
524        = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
525                                                      LParenLoc, RParenLoc)
526                   : InitializationKind::CreateValue(TypeRange.getBegin(),
527                                                     LParenLoc, RParenLoc);
528      InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
529      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
530                                                move(exprs));
531
532      // FIXME: Improve AST representation?
533      return move(Result);
534    }
535
536    // Fall through to value-initialize an object of class type that
537    // doesn't have a user-declared default constructor.
538  }
539
540  // C++ [expr.type.conv]p1:
541  // If the expression list specifies more than a single value, the type shall
542  // be a class with a suitably declared constructor.
543  //
544  if (NumExprs > 1)
545    return ExprError(Diag(CommaLocs[0],
546                          diag::err_builtin_func_cast_more_than_one_arg)
547      << FullRange);
548
549  assert(NumExprs == 0 && "Expected 0 expressions");
550  // C++ [expr.type.conv]p2:
551  // The expression T(), where T is a simple-type-specifier for a non-array
552  // complete object type or the (possibly cv-qualified) void type, creates an
553  // rvalue of the specified type, which is value-initialized.
554  //
555  exprs.release();
556  return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
557}
558
559
560/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
561/// @code new (memory) int[size][4] @endcode
562/// or
563/// @code ::new Foo(23, "hello") @endcode
564/// For the interpretation of this heap of arguments, consult the base version.
565Action::OwningExprResult
566Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
567                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
568                  SourceLocation PlacementRParen, bool ParenTypeId,
569                  Declarator &D, SourceLocation ConstructorLParen,
570                  MultiExprArg ConstructorArgs,
571                  SourceLocation ConstructorRParen) {
572  Expr *ArraySize = 0;
573  // If the specified type is an array, unwrap it and save the expression.
574  if (D.getNumTypeObjects() > 0 &&
575      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
576    DeclaratorChunk &Chunk = D.getTypeObject(0);
577    if (Chunk.Arr.hasStatic)
578      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
579        << D.getSourceRange());
580    if (!Chunk.Arr.NumElts)
581      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
582        << D.getSourceRange());
583
584    if (ParenTypeId) {
585      // Can't have dynamic array size when the type-id is in parentheses.
586      Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
587      if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
588          !NumElts->isIntegerConstantExpr(Context)) {
589        Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
590          << NumElts->getSourceRange();
591        return ExprError();
592      }
593    }
594
595    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
596    D.DropFirstTypeObject();
597  }
598
599  // Every dimension shall be of constant size.
600  if (ArraySize) {
601    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
602      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
603        break;
604
605      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
606      if (Expr *NumElts = (Expr *)Array.NumElts) {
607        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
608            !NumElts->isIntegerConstantExpr(Context)) {
609          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
610            << NumElts->getSourceRange();
611          return ExprError();
612        }
613      }
614    }
615  }
616
617  //FIXME: Store TypeSourceInfo in CXXNew expression.
618  TypeSourceInfo *TInfo = 0;
619  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
620  if (D.isInvalidType())
621    return ExprError();
622
623  return BuildCXXNew(StartLoc, UseGlobal,
624                     PlacementLParen,
625                     move(PlacementArgs),
626                     PlacementRParen,
627                     ParenTypeId,
628                     AllocType,
629                     D.getSourceRange().getBegin(),
630                     D.getSourceRange(),
631                     Owned(ArraySize),
632                     ConstructorLParen,
633                     move(ConstructorArgs),
634                     ConstructorRParen);
635}
636
637Sema::OwningExprResult
638Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
639                  SourceLocation PlacementLParen,
640                  MultiExprArg PlacementArgs,
641                  SourceLocation PlacementRParen,
642                  bool ParenTypeId,
643                  QualType AllocType,
644                  SourceLocation TypeLoc,
645                  SourceRange TypeRange,
646                  ExprArg ArraySizeE,
647                  SourceLocation ConstructorLParen,
648                  MultiExprArg ConstructorArgs,
649                  SourceLocation ConstructorRParen) {
650  if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
651    return ExprError();
652
653  QualType ResultType = Context.getPointerType(AllocType);
654
655  // That every array dimension except the first is constant was already
656  // checked by the type check above.
657
658  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
659  //   or enumeration type with a non-negative value."
660  Expr *ArraySize = (Expr *)ArraySizeE.get();
661  if (ArraySize && !ArraySize->isTypeDependent()) {
662    QualType SizeType = ArraySize->getType();
663    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
664      return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
665                            diag::err_array_size_not_integral)
666        << SizeType << ArraySize->getSourceRange());
667    // Let's see if this is a constant < 0. If so, we reject it out of hand.
668    // We don't care about special rules, so we tell the machinery it's not
669    // evaluated - it gives us a result in more cases.
670    if (!ArraySize->isValueDependent()) {
671      llvm::APSInt Value;
672      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
673        if (Value < llvm::APSInt(
674                        llvm::APInt::getNullValue(Value.getBitWidth()),
675                                 Value.isUnsigned()))
676          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
677                           diag::err_typecheck_negative_array_size)
678            << ArraySize->getSourceRange());
679      }
680    }
681
682    ImpCastExprToType(ArraySize, Context.getSizeType(),
683                      CastExpr::CK_IntegralCast);
684  }
685
686  FunctionDecl *OperatorNew = 0;
687  FunctionDecl *OperatorDelete = 0;
688  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
689  unsigned NumPlaceArgs = PlacementArgs.size();
690
691  if (!AllocType->isDependentType() &&
692      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
693      FindAllocationFunctions(StartLoc,
694                              SourceRange(PlacementLParen, PlacementRParen),
695                              UseGlobal, AllocType, ArraySize, PlaceArgs,
696                              NumPlaceArgs, OperatorNew, OperatorDelete))
697    return ExprError();
698  llvm::SmallVector<Expr *, 8> AllPlaceArgs;
699  if (OperatorNew) {
700    // Add default arguments, if any.
701    const FunctionProtoType *Proto =
702      OperatorNew->getType()->getAs<FunctionProtoType>();
703    VariadicCallType CallType =
704      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
705    bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
706                                          Proto, 1, PlaceArgs, NumPlaceArgs,
707                                          AllPlaceArgs, CallType);
708    if (Invalid)
709      return ExprError();
710
711    NumPlaceArgs = AllPlaceArgs.size();
712    if (NumPlaceArgs > 0)
713      PlaceArgs = &AllPlaceArgs[0];
714  }
715
716  bool Init = ConstructorLParen.isValid();
717  // --- Choosing a constructor ---
718  CXXConstructorDecl *Constructor = 0;
719  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
720  unsigned NumConsArgs = ConstructorArgs.size();
721  ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
722
723  if (!AllocType->isDependentType() &&
724      !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
725    // C++0x [expr.new]p15:
726    //   A new-expression that creates an object of type T initializes that
727    //   object as follows:
728    InitializationKind Kind
729    //     - If the new-initializer is omitted, the object is default-
730    //       initialized (8.5); if no initialization is performed,
731    //       the object has indeterminate value
732      = !Init? InitializationKind::CreateDefault(TypeLoc)
733    //     - Otherwise, the new-initializer is interpreted according to the
734    //       initialization rules of 8.5 for direct-initialization.
735             : InitializationKind::CreateDirect(TypeLoc,
736                                                ConstructorLParen,
737                                                ConstructorRParen);
738
739    InitializedEntity Entity
740      = InitializedEntity::InitializeNew(StartLoc, AllocType);
741    InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
742    OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
743                                                move(ConstructorArgs));
744    if (FullInit.isInvalid())
745      return ExprError();
746
747    // FullInit is our initializer; walk through it to determine if it's a
748    // constructor call, which CXXNewExpr handles directly.
749    if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
750      if (CXXBindTemporaryExpr *Binder
751            = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
752        FullInitExpr = Binder->getSubExpr();
753      if (CXXConstructExpr *Construct
754                    = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
755        Constructor = Construct->getConstructor();
756        for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
757                                         AEnd = Construct->arg_end();
758             A != AEnd; ++A)
759          ConvertedConstructorArgs.push_back(A->Retain());
760      } else {
761        // Take the converted initializer.
762        ConvertedConstructorArgs.push_back(FullInit.release());
763      }
764    } else {
765      // No initialization required.
766    }
767
768    // Take the converted arguments and use them for the new expression.
769    NumConsArgs = ConvertedConstructorArgs.size();
770    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
771  }
772
773  // Mark the new and delete operators as referenced.
774  if (OperatorNew)
775    MarkDeclarationReferenced(StartLoc, OperatorNew);
776  if (OperatorDelete)
777    MarkDeclarationReferenced(StartLoc, OperatorDelete);
778
779  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
780
781  PlacementArgs.release();
782  ConstructorArgs.release();
783  ArraySizeE.release();
784  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
785                                        PlaceArgs, NumPlaceArgs, ParenTypeId,
786                                        ArraySize, Constructor, Init,
787                                        ConsArgs, NumConsArgs, OperatorDelete,
788                                        ResultType, StartLoc,
789                                        Init ? ConstructorRParen :
790                                               SourceLocation()));
791}
792
793/// CheckAllocatedType - Checks that a type is suitable as the allocated type
794/// in a new-expression.
795/// dimension off and stores the size expression in ArraySize.
796bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
797                              SourceRange R) {
798  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
799  //   abstract class type or array thereof.
800  if (AllocType->isFunctionType())
801    return Diag(Loc, diag::err_bad_new_type)
802      << AllocType << 0 << R;
803  else if (AllocType->isReferenceType())
804    return Diag(Loc, diag::err_bad_new_type)
805      << AllocType << 1 << R;
806  else if (!AllocType->isDependentType() &&
807           RequireCompleteType(Loc, AllocType,
808                               PDiag(diag::err_new_incomplete_type)
809                                 << R))
810    return true;
811  else if (RequireNonAbstractType(Loc, AllocType,
812                                  diag::err_allocation_of_abstract_type))
813    return true;
814
815  return false;
816}
817
818/// \brief Determine whether the given function is a non-placement
819/// deallocation function.
820static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
821  if (FD->isInvalidDecl())
822    return false;
823
824  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
825    return Method->isUsualDeallocationFunction();
826
827  return ((FD->getOverloadedOperator() == OO_Delete ||
828           FD->getOverloadedOperator() == OO_Array_Delete) &&
829          FD->getNumParams() == 1);
830}
831
832/// FindAllocationFunctions - Finds the overloads of operator new and delete
833/// that are appropriate for the allocation.
834bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
835                                   bool UseGlobal, QualType AllocType,
836                                   bool IsArray, Expr **PlaceArgs,
837                                   unsigned NumPlaceArgs,
838                                   FunctionDecl *&OperatorNew,
839                                   FunctionDecl *&OperatorDelete) {
840  // --- Choosing an allocation function ---
841  // C++ 5.3.4p8 - 14 & 18
842  // 1) If UseGlobal is true, only look in the global scope. Else, also look
843  //   in the scope of the allocated class.
844  // 2) If an array size is given, look for operator new[], else look for
845  //   operator new.
846  // 3) The first argument is always size_t. Append the arguments from the
847  //   placement form.
848
849  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
850  // We don't care about the actual value of this argument.
851  // FIXME: Should the Sema create the expression and embed it in the syntax
852  // tree? Or should the consumer just recalculate the value?
853  IntegerLiteral Size(llvm::APInt::getNullValue(
854                      Context.Target.getPointerWidth(0)),
855                      Context.getSizeType(),
856                      SourceLocation());
857  AllocArgs[0] = &Size;
858  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
859
860  // C++ [expr.new]p8:
861  //   If the allocated type is a non-array type, the allocation
862  //   function’s name is operator new and the deallocation function’s
863  //   name is operator delete. If the allocated type is an array
864  //   type, the allocation function’s name is operator new[] and the
865  //   deallocation function’s name is operator delete[].
866  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
867                                        IsArray ? OO_Array_New : OO_New);
868  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
869                                        IsArray ? OO_Array_Delete : OO_Delete);
870
871  if (AllocType->isRecordType() && !UseGlobal) {
872    CXXRecordDecl *Record
873      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
874    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
875                          AllocArgs.size(), Record, /*AllowMissing=*/true,
876                          OperatorNew))
877      return true;
878  }
879  if (!OperatorNew) {
880    // Didn't find a member overload. Look for a global one.
881    DeclareGlobalNewDelete();
882    DeclContext *TUDecl = Context.getTranslationUnitDecl();
883    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
884                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
885                          OperatorNew))
886      return true;
887  }
888
889  // FindAllocationOverload can change the passed in arguments, so we need to
890  // copy them back.
891  if (NumPlaceArgs > 0)
892    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
893
894  // C++ [expr.new]p19:
895  //
896  //   If the new-expression begins with a unary :: operator, the
897  //   deallocation function’s name is looked up in the global
898  //   scope. Otherwise, if the allocated type is a class type T or an
899  //   array thereof, the deallocation function’s name is looked up in
900  //   the scope of T. If this lookup fails to find the name, or if
901  //   the allocated type is not a class type or array thereof, the
902  //   deallocation function’s name is looked up in the global scope.
903  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
904  if (AllocType->isRecordType() && !UseGlobal) {
905    CXXRecordDecl *RD
906      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
907    LookupQualifiedName(FoundDelete, RD);
908  }
909  if (FoundDelete.isAmbiguous())
910    return true; // FIXME: clean up expressions?
911
912  if (FoundDelete.empty()) {
913    DeclareGlobalNewDelete();
914    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
915  }
916
917  FoundDelete.suppressDiagnostics();
918
919  llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
920
921  if (NumPlaceArgs > 0) {
922    // C++ [expr.new]p20:
923    //   A declaration of a placement deallocation function matches the
924    //   declaration of a placement allocation function if it has the
925    //   same number of parameters and, after parameter transformations
926    //   (8.3.5), all parameter types except the first are
927    //   identical. [...]
928    //
929    // To perform this comparison, we compute the function type that
930    // the deallocation function should have, and use that type both
931    // for template argument deduction and for comparison purposes.
932    QualType ExpectedFunctionType;
933    {
934      const FunctionProtoType *Proto
935        = OperatorNew->getType()->getAs<FunctionProtoType>();
936      llvm::SmallVector<QualType, 4> ArgTypes;
937      ArgTypes.push_back(Context.VoidPtrTy);
938      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
939        ArgTypes.push_back(Proto->getArgType(I));
940
941      ExpectedFunctionType
942        = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
943                                  ArgTypes.size(),
944                                  Proto->isVariadic(),
945                                  0, false, false, 0, 0,
946                                  FunctionType::ExtInfo());
947    }
948
949    for (LookupResult::iterator D = FoundDelete.begin(),
950                             DEnd = FoundDelete.end();
951         D != DEnd; ++D) {
952      FunctionDecl *Fn = 0;
953      if (FunctionTemplateDecl *FnTmpl
954            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
955        // Perform template argument deduction to try to match the
956        // expected function type.
957        TemplateDeductionInfo Info(Context, StartLoc);
958        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
959          continue;
960      } else
961        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
962
963      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
964        Matches.push_back(std::make_pair(D.getPair(), Fn));
965    }
966  } else {
967    // C++ [expr.new]p20:
968    //   [...] Any non-placement deallocation function matches a
969    //   non-placement allocation function. [...]
970    for (LookupResult::iterator D = FoundDelete.begin(),
971                             DEnd = FoundDelete.end();
972         D != DEnd; ++D) {
973      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
974        if (isNonPlacementDeallocationFunction(Fn))
975          Matches.push_back(std::make_pair(D.getPair(), Fn));
976    }
977  }
978
979  // C++ [expr.new]p20:
980  //   [...] If the lookup finds a single matching deallocation
981  //   function, that function will be called; otherwise, no
982  //   deallocation function will be called.
983  if (Matches.size() == 1) {
984    OperatorDelete = Matches[0].second;
985
986    // C++0x [expr.new]p20:
987    //   If the lookup finds the two-parameter form of a usual
988    //   deallocation function (3.7.4.2) and that function, considered
989    //   as a placement deallocation function, would have been
990    //   selected as a match for the allocation function, the program
991    //   is ill-formed.
992    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
993        isNonPlacementDeallocationFunction(OperatorDelete)) {
994      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
995        << SourceRange(PlaceArgs[0]->getLocStart(),
996                       PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
997      Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
998        << DeleteName;
999    } else {
1000      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1001                            Matches[0].first);
1002    }
1003  }
1004
1005  return false;
1006}
1007
1008/// FindAllocationOverload - Find an fitting overload for the allocation
1009/// function in the specified scope.
1010bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1011                                  DeclarationName Name, Expr** Args,
1012                                  unsigned NumArgs, DeclContext *Ctx,
1013                                  bool AllowMissing, FunctionDecl *&Operator) {
1014  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1015  LookupQualifiedName(R, Ctx);
1016  if (R.empty()) {
1017    if (AllowMissing)
1018      return false;
1019    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1020      << Name << Range;
1021  }
1022
1023  if (R.isAmbiguous())
1024    return true;
1025
1026  R.suppressDiagnostics();
1027
1028  OverloadCandidateSet Candidates(StartLoc);
1029  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1030       Alloc != AllocEnd; ++Alloc) {
1031    // Even member operator new/delete are implicitly treated as
1032    // static, so don't use AddMemberCandidate.
1033    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1034
1035    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1036      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1037                                   /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1038                                   Candidates,
1039                                   /*SuppressUserConversions=*/false);
1040      continue;
1041    }
1042
1043    FunctionDecl *Fn = cast<FunctionDecl>(D);
1044    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1045                         /*SuppressUserConversions=*/false);
1046  }
1047
1048  // Do the resolution.
1049  OverloadCandidateSet::iterator Best;
1050  switch(BestViableFunction(Candidates, StartLoc, Best)) {
1051  case OR_Success: {
1052    // Got one!
1053    FunctionDecl *FnDecl = Best->Function;
1054    // The first argument is size_t, and the first parameter must be size_t,
1055    // too. This is checked on declaration and can be assumed. (It can't be
1056    // asserted on, though, since invalid decls are left in there.)
1057    // Watch out for variadic allocator function.
1058    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1059    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1060      OwningExprResult Result
1061        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1062                                                       FnDecl->getParamDecl(i)),
1063                                    SourceLocation(),
1064                                    Owned(Args[i]->Retain()));
1065      if (Result.isInvalid())
1066        return true;
1067
1068      Args[i] = Result.takeAs<Expr>();
1069    }
1070    Operator = FnDecl;
1071    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1072    return false;
1073  }
1074
1075  case OR_No_Viable_Function:
1076    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1077      << Name << Range;
1078    PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
1079    return true;
1080
1081  case OR_Ambiguous:
1082    Diag(StartLoc, diag::err_ovl_ambiguous_call)
1083      << Name << Range;
1084    PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
1085    return true;
1086
1087  case OR_Deleted:
1088    Diag(StartLoc, diag::err_ovl_deleted_call)
1089      << Best->Function->isDeleted()
1090      << Name << Range;
1091    PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
1092    return true;
1093  }
1094  assert(false && "Unreachable, bad result from BestViableFunction");
1095  return true;
1096}
1097
1098
1099/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1100/// delete. These are:
1101/// @code
1102///   void* operator new(std::size_t) throw(std::bad_alloc);
1103///   void* operator new[](std::size_t) throw(std::bad_alloc);
1104///   void operator delete(void *) throw();
1105///   void operator delete[](void *) throw();
1106/// @endcode
1107/// Note that the placement and nothrow forms of new are *not* implicitly
1108/// declared. Their use requires including \<new\>.
1109void Sema::DeclareGlobalNewDelete() {
1110  if (GlobalNewDeleteDeclared)
1111    return;
1112
1113  // C++ [basic.std.dynamic]p2:
1114  //   [...] The following allocation and deallocation functions (18.4) are
1115  //   implicitly declared in global scope in each translation unit of a
1116  //   program
1117  //
1118  //     void* operator new(std::size_t) throw(std::bad_alloc);
1119  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1120  //     void  operator delete(void*) throw();
1121  //     void  operator delete[](void*) throw();
1122  //
1123  //   These implicit declarations introduce only the function names operator
1124  //   new, operator new[], operator delete, operator delete[].
1125  //
1126  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1127  // "std" or "bad_alloc" as necessary to form the exception specification.
1128  // However, we do not make these implicit declarations visible to name
1129  // lookup.
1130  if (!StdNamespace) {
1131    // The "std" namespace has not yet been defined, so build one implicitly.
1132    StdNamespace = NamespaceDecl::Create(Context,
1133                                         Context.getTranslationUnitDecl(),
1134                                         SourceLocation(),
1135                                         &PP.getIdentifierTable().get("std"));
1136    StdNamespace->setImplicit(true);
1137  }
1138
1139  if (!StdBadAlloc) {
1140    // The "std::bad_alloc" class has not yet been declared, so build it
1141    // implicitly.
1142    StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1143                                        StdNamespace,
1144                                        SourceLocation(),
1145                                      &PP.getIdentifierTable().get("bad_alloc"),
1146                                        SourceLocation(), 0);
1147    StdBadAlloc->setImplicit(true);
1148  }
1149
1150  GlobalNewDeleteDeclared = true;
1151
1152  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1153  QualType SizeT = Context.getSizeType();
1154  bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1155
1156  DeclareGlobalAllocationFunction(
1157      Context.DeclarationNames.getCXXOperatorName(OO_New),
1158      VoidPtr, SizeT, AssumeSaneOperatorNew);
1159  DeclareGlobalAllocationFunction(
1160      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1161      VoidPtr, SizeT, AssumeSaneOperatorNew);
1162  DeclareGlobalAllocationFunction(
1163      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1164      Context.VoidTy, VoidPtr);
1165  DeclareGlobalAllocationFunction(
1166      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1167      Context.VoidTy, VoidPtr);
1168}
1169
1170/// DeclareGlobalAllocationFunction - Declares a single implicit global
1171/// allocation function if it doesn't already exist.
1172void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1173                                           QualType Return, QualType Argument,
1174                                           bool AddMallocAttr) {
1175  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1176
1177  // Check if this function is already declared.
1178  {
1179    DeclContext::lookup_iterator Alloc, AllocEnd;
1180    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1181         Alloc != AllocEnd; ++Alloc) {
1182      // Only look at non-template functions, as it is the predefined,
1183      // non-templated allocation function we are trying to declare here.
1184      if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1185        QualType InitialParamType =
1186          Context.getCanonicalType(
1187            Func->getParamDecl(0)->getType().getUnqualifiedType());
1188        // FIXME: Do we need to check for default arguments here?
1189        if (Func->getNumParams() == 1 && InitialParamType == Argument)
1190          return;
1191      }
1192    }
1193  }
1194
1195  QualType BadAllocType;
1196  bool HasBadAllocExceptionSpec
1197    = (Name.getCXXOverloadedOperator() == OO_New ||
1198       Name.getCXXOverloadedOperator() == OO_Array_New);
1199  if (HasBadAllocExceptionSpec) {
1200    assert(StdBadAlloc && "Must have std::bad_alloc declared");
1201    BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1202  }
1203
1204  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1205                                            true, false,
1206                                            HasBadAllocExceptionSpec? 1 : 0,
1207                                            &BadAllocType,
1208                                            FunctionType::ExtInfo());
1209  FunctionDecl *Alloc =
1210    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
1211                         FnType, /*TInfo=*/0, FunctionDecl::None,
1212                         FunctionDecl::None, false, true);
1213  Alloc->setImplicit();
1214
1215  if (AddMallocAttr)
1216    Alloc->addAttr(::new (Context) MallocAttr());
1217
1218  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1219                                           0, Argument, /*TInfo=*/0,
1220                                           VarDecl::None,
1221                                           VarDecl::None, 0);
1222  Alloc->setParams(&Param, 1);
1223
1224  // FIXME: Also add this declaration to the IdentifierResolver, but
1225  // make sure it is at the end of the chain to coincide with the
1226  // global scope.
1227  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
1228}
1229
1230bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1231                                    DeclarationName Name,
1232                                    FunctionDecl* &Operator) {
1233  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1234  // Try to find operator delete/operator delete[] in class scope.
1235  LookupQualifiedName(Found, RD);
1236
1237  if (Found.isAmbiguous())
1238    return true;
1239
1240  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1241       F != FEnd; ++F) {
1242    if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1243      if (Delete->isUsualDeallocationFunction()) {
1244        Operator = Delete;
1245        return false;
1246      }
1247  }
1248
1249  // We did find operator delete/operator delete[] declarations, but
1250  // none of them were suitable.
1251  if (!Found.empty()) {
1252    Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1253      << Name << RD;
1254
1255    for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1256         F != FEnd; ++F) {
1257      Diag((*F)->getLocation(),
1258           diag::note_delete_member_function_declared_here)
1259        << Name;
1260    }
1261
1262    return true;
1263  }
1264
1265  // Look for a global declaration.
1266  DeclareGlobalNewDelete();
1267  DeclContext *TUDecl = Context.getTranslationUnitDecl();
1268
1269  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1270  Expr* DeallocArgs[1];
1271  DeallocArgs[0] = &Null;
1272  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1273                             DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1274                             Operator))
1275    return true;
1276
1277  assert(Operator && "Did not find a deallocation function!");
1278  return false;
1279}
1280
1281/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1282/// @code ::delete ptr; @endcode
1283/// or
1284/// @code delete [] ptr; @endcode
1285Action::OwningExprResult
1286Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1287                     bool ArrayForm, ExprArg Operand) {
1288  // C++ [expr.delete]p1:
1289  //   The operand shall have a pointer type, or a class type having a single
1290  //   conversion function to a pointer type. The result has type void.
1291  //
1292  // DR599 amends "pointer type" to "pointer to object type" in both cases.
1293
1294  FunctionDecl *OperatorDelete = 0;
1295
1296  Expr *Ex = (Expr *)Operand.get();
1297  if (!Ex->isTypeDependent()) {
1298    QualType Type = Ex->getType();
1299
1300    if (const RecordType *Record = Type->getAs<RecordType>()) {
1301      llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1302
1303      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1304      const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1305      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1306             E = Conversions->end(); I != E; ++I) {
1307        NamedDecl *D = I.getDecl();
1308        if (isa<UsingShadowDecl>(D))
1309          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1310
1311        // Skip over templated conversion functions; they aren't considered.
1312        if (isa<FunctionTemplateDecl>(D))
1313          continue;
1314
1315        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1316
1317        QualType ConvType = Conv->getConversionType().getNonReferenceType();
1318        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1319          if (ConvPtrType->getPointeeType()->isObjectType())
1320            ObjectPtrConversions.push_back(Conv);
1321      }
1322      if (ObjectPtrConversions.size() == 1) {
1323        // We have a single conversion to a pointer-to-object type. Perform
1324        // that conversion.
1325        // TODO: don't redo the conversion calculation.
1326        Operand.release();
1327        if (!PerformImplicitConversion(Ex,
1328                            ObjectPtrConversions.front()->getConversionType(),
1329                                      AA_Converting)) {
1330          Operand = Owned(Ex);
1331          Type = Ex->getType();
1332        }
1333      }
1334      else if (ObjectPtrConversions.size() > 1) {
1335        Diag(StartLoc, diag::err_ambiguous_delete_operand)
1336              << Type << Ex->getSourceRange();
1337        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1338          NoteOverloadCandidate(ObjectPtrConversions[i]);
1339        return ExprError();
1340      }
1341    }
1342
1343    if (!Type->isPointerType())
1344      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1345        << Type << Ex->getSourceRange());
1346
1347    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1348    if (Pointee->isFunctionType() || Pointee->isVoidType())
1349      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1350        << Type << Ex->getSourceRange());
1351    else if (!Pointee->isDependentType() &&
1352             RequireCompleteType(StartLoc, Pointee,
1353                                 PDiag(diag::warn_delete_incomplete)
1354                                   << Ex->getSourceRange()))
1355      return ExprError();
1356
1357    // C++ [expr.delete]p2:
1358    //   [Note: a pointer to a const type can be the operand of a
1359    //   delete-expression; it is not necessary to cast away the constness
1360    //   (5.2.11) of the pointer expression before it is used as the operand
1361    //   of the delete-expression. ]
1362    ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1363                      CastExpr::CK_NoOp);
1364
1365    // Update the operand.
1366    Operand.take();
1367    Operand = ExprArg(*this, Ex);
1368
1369    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1370                                      ArrayForm ? OO_Array_Delete : OO_Delete);
1371
1372    if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1373      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1374
1375      if (!UseGlobal &&
1376          FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1377        return ExprError();
1378
1379      if (!RD->hasTrivialDestructor())
1380        if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
1381          MarkDeclarationReferenced(StartLoc,
1382                                    const_cast<CXXDestructorDecl*>(Dtor));
1383    }
1384
1385    if (!OperatorDelete) {
1386      // Look for a global declaration.
1387      DeclareGlobalNewDelete();
1388      DeclContext *TUDecl = Context.getTranslationUnitDecl();
1389      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1390                                 &Ex, 1, TUDecl, /*AllowMissing=*/false,
1391                                 OperatorDelete))
1392        return ExprError();
1393    }
1394
1395    // FIXME: Check access and ambiguity of operator delete and destructor.
1396  }
1397
1398  Operand.release();
1399  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1400                                           OperatorDelete, Ex, StartLoc));
1401}
1402
1403/// \brief Check the use of the given variable as a C++ condition in an if,
1404/// while, do-while, or switch statement.
1405Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1406  QualType T = ConditionVar->getType();
1407
1408  // C++ [stmt.select]p2:
1409  //   The declarator shall not specify a function or an array.
1410  if (T->isFunctionType())
1411    return ExprError(Diag(ConditionVar->getLocation(),
1412                          diag::err_invalid_use_of_function_type)
1413                       << ConditionVar->getSourceRange());
1414  else if (T->isArrayType())
1415    return ExprError(Diag(ConditionVar->getLocation(),
1416                          diag::err_invalid_use_of_array_type)
1417                     << ConditionVar->getSourceRange());
1418
1419  return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1420                                   ConditionVar->getLocation(),
1421                                ConditionVar->getType().getNonReferenceType()));
1422}
1423
1424/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1425bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1426  // C++ 6.4p4:
1427  // The value of a condition that is an initialized declaration in a statement
1428  // other than a switch statement is the value of the declared variable
1429  // implicitly converted to type bool. If that conversion is ill-formed, the
1430  // program is ill-formed.
1431  // The value of a condition that is an expression is the value of the
1432  // expression, implicitly converted to bool.
1433  //
1434  return PerformContextuallyConvertToBool(CondExpr);
1435}
1436
1437/// Helper function to determine whether this is the (deprecated) C++
1438/// conversion from a string literal to a pointer to non-const char or
1439/// non-const wchar_t (for narrow and wide string literals,
1440/// respectively).
1441bool
1442Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1443  // Look inside the implicit cast, if it exists.
1444  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1445    From = Cast->getSubExpr();
1446
1447  // A string literal (2.13.4) that is not a wide string literal can
1448  // be converted to an rvalue of type "pointer to char"; a wide
1449  // string literal can be converted to an rvalue of type "pointer
1450  // to wchar_t" (C++ 4.2p2).
1451  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
1452    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1453      if (const BuiltinType *ToPointeeType
1454          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1455        // This conversion is considered only when there is an
1456        // explicit appropriate pointer target type (C++ 4.2p2).
1457        if (!ToPtrType->getPointeeType().hasQualifiers() &&
1458            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1459             (!StrLit->isWide() &&
1460              (ToPointeeType->getKind() == BuiltinType::Char_U ||
1461               ToPointeeType->getKind() == BuiltinType::Char_S))))
1462          return true;
1463      }
1464
1465  return false;
1466}
1467
1468static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1469                                                   SourceLocation CastLoc,
1470                                                   QualType Ty,
1471                                                   CastExpr::CastKind Kind,
1472                                                   CXXMethodDecl *Method,
1473                                                   Sema::ExprArg Arg) {
1474  Expr *From = Arg.takeAs<Expr>();
1475
1476  switch (Kind) {
1477  default: assert(0 && "Unhandled cast kind!");
1478  case CastExpr::CK_ConstructorConversion: {
1479    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1480
1481    if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1482                                  Sema::MultiExprArg(S, (void **)&From, 1),
1483                                  CastLoc, ConstructorArgs))
1484      return S.ExprError();
1485
1486    Sema::OwningExprResult Result =
1487    S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1488                            move_arg(ConstructorArgs));
1489    if (Result.isInvalid())
1490      return S.ExprError();
1491
1492    return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1493  }
1494
1495  case CastExpr::CK_UserDefinedConversion: {
1496    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1497
1498    // Create an implicit call expr that calls it.
1499    // FIXME: pass the FoundDecl for the user-defined conversion here
1500    CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1501    return S.MaybeBindToTemporary(CE);
1502  }
1503  }
1504}
1505
1506/// PerformImplicitConversion - Perform an implicit conversion of the
1507/// expression From to the type ToType using the pre-computed implicit
1508/// conversion sequence ICS. Returns true if there was an error, false
1509/// otherwise. The expression From is replaced with the converted
1510/// expression. Action is the kind of conversion we're performing,
1511/// used in the error message.
1512bool
1513Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1514                                const ImplicitConversionSequence &ICS,
1515                                AssignmentAction Action, bool IgnoreBaseAccess) {
1516  switch (ICS.getKind()) {
1517  case ImplicitConversionSequence::StandardConversion:
1518    if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
1519                                  IgnoreBaseAccess))
1520      return true;
1521    break;
1522
1523  case ImplicitConversionSequence::UserDefinedConversion: {
1524
1525      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1526      CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
1527      QualType BeforeToType;
1528      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1529        CastKind = CastExpr::CK_UserDefinedConversion;
1530
1531        // If the user-defined conversion is specified by a conversion function,
1532        // the initial standard conversion sequence converts the source type to
1533        // the implicit object parameter of the conversion function.
1534        BeforeToType = Context.getTagDeclType(Conv->getParent());
1535      } else if (const CXXConstructorDecl *Ctor =
1536                  dyn_cast<CXXConstructorDecl>(FD)) {
1537        CastKind = CastExpr::CK_ConstructorConversion;
1538        // Do no conversion if dealing with ... for the first conversion.
1539        if (!ICS.UserDefined.EllipsisConversion) {
1540          // If the user-defined conversion is specified by a constructor, the
1541          // initial standard conversion sequence converts the source type to the
1542          // type required by the argument of the constructor
1543          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1544        }
1545      }
1546      else
1547        assert(0 && "Unknown conversion function kind!");
1548      // Whatch out for elipsis conversion.
1549      if (!ICS.UserDefined.EllipsisConversion) {
1550        if (PerformImplicitConversion(From, BeforeToType,
1551                                      ICS.UserDefined.Before, AA_Converting,
1552                                      IgnoreBaseAccess))
1553          return true;
1554      }
1555
1556      OwningExprResult CastArg
1557        = BuildCXXCastArgument(*this,
1558                               From->getLocStart(),
1559                               ToType.getNonReferenceType(),
1560                               CastKind, cast<CXXMethodDecl>(FD),
1561                               Owned(From));
1562
1563      if (CastArg.isInvalid())
1564        return true;
1565
1566      From = CastArg.takeAs<Expr>();
1567
1568      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1569                                       AA_Converting, IgnoreBaseAccess);
1570  }
1571
1572  case ImplicitConversionSequence::AmbiguousConversion:
1573    DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1574                          PDiag(diag::err_typecheck_ambiguous_condition)
1575                            << From->getSourceRange());
1576     return true;
1577
1578  case ImplicitConversionSequence::EllipsisConversion:
1579    assert(false && "Cannot perform an ellipsis conversion");
1580    return false;
1581
1582  case ImplicitConversionSequence::BadConversion:
1583    return true;
1584  }
1585
1586  // Everything went well.
1587  return false;
1588}
1589
1590/// PerformImplicitConversion - Perform an implicit conversion of the
1591/// expression From to the type ToType by following the standard
1592/// conversion sequence SCS. Returns true if there was an error, false
1593/// otherwise. The expression From is replaced with the converted
1594/// expression. Flavor is the context in which we're performing this
1595/// conversion, for use in error messages.
1596bool
1597Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1598                                const StandardConversionSequence& SCS,
1599                                AssignmentAction Action, bool IgnoreBaseAccess) {
1600  // Overall FIXME: we are recomputing too many types here and doing far too
1601  // much extra work. What this means is that we need to keep track of more
1602  // information that is computed when we try the implicit conversion initially,
1603  // so that we don't need to recompute anything here.
1604  QualType FromType = From->getType();
1605
1606  if (SCS.CopyConstructor) {
1607    // FIXME: When can ToType be a reference type?
1608    assert(!ToType->isReferenceType());
1609    if (SCS.Second == ICK_Derived_To_Base) {
1610      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1611      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1612                                  MultiExprArg(*this, (void **)&From, 1),
1613                                  /*FIXME:ConstructLoc*/SourceLocation(),
1614                                  ConstructorArgs))
1615        return true;
1616      OwningExprResult FromResult =
1617        BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1618                              ToType, SCS.CopyConstructor,
1619                              move_arg(ConstructorArgs));
1620      if (FromResult.isInvalid())
1621        return true;
1622      From = FromResult.takeAs<Expr>();
1623      return false;
1624    }
1625    OwningExprResult FromResult =
1626      BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1627                            ToType, SCS.CopyConstructor,
1628                            MultiExprArg(*this, (void**)&From, 1));
1629
1630    if (FromResult.isInvalid())
1631      return true;
1632
1633    From = FromResult.takeAs<Expr>();
1634    return false;
1635  }
1636
1637  // Perform the first implicit conversion.
1638  switch (SCS.First) {
1639  case ICK_Identity:
1640  case ICK_Lvalue_To_Rvalue:
1641    // Nothing to do.
1642    break;
1643
1644  case ICK_Array_To_Pointer:
1645    FromType = Context.getArrayDecayedType(FromType);
1646    ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
1647    break;
1648
1649  case ICK_Function_To_Pointer:
1650    if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
1651      DeclAccessPair Found;
1652      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1653                                                            true, Found);
1654      if (!Fn)
1655        return true;
1656
1657      if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1658        return true;
1659
1660      From = FixOverloadedFunctionReference(From, Found, Fn);
1661      FromType = From->getType();
1662
1663      // If there's already an address-of operator in the expression, we have
1664      // the right type already, and the code below would just introduce an
1665      // invalid additional pointer level.
1666      if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
1667        break;
1668    }
1669    FromType = Context.getPointerType(FromType);
1670    ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
1671    break;
1672
1673  default:
1674    assert(false && "Improper first standard conversion");
1675    break;
1676  }
1677
1678  // Perform the second implicit conversion
1679  switch (SCS.Second) {
1680  case ICK_Identity:
1681    // If both sides are functions (or pointers/references to them), there could
1682    // be incompatible exception declarations.
1683    if (CheckExceptionSpecCompatibility(From, ToType))
1684      return true;
1685    // Nothing else to do.
1686    break;
1687
1688  case ICK_NoReturn_Adjustment:
1689    // If both sides are functions (or pointers/references to them), there could
1690    // be incompatible exception declarations.
1691    if (CheckExceptionSpecCompatibility(From, ToType))
1692      return true;
1693
1694    ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1695                      CastExpr::CK_NoOp);
1696    break;
1697
1698  case ICK_Integral_Promotion:
1699  case ICK_Integral_Conversion:
1700    ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1701    break;
1702
1703  case ICK_Floating_Promotion:
1704  case ICK_Floating_Conversion:
1705    ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1706    break;
1707
1708  case ICK_Complex_Promotion:
1709  case ICK_Complex_Conversion:
1710    ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1711    break;
1712
1713  case ICK_Floating_Integral:
1714    if (ToType->isFloatingType())
1715      ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1716    else
1717      ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1718    break;
1719
1720  case ICK_Complex_Real:
1721    ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1722    break;
1723
1724  case ICK_Compatible_Conversion:
1725    ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
1726    break;
1727
1728  case ICK_Pointer_Conversion: {
1729    if (SCS.IncompatibleObjC) {
1730      // Diagnose incompatible Objective-C conversions
1731      Diag(From->getSourceRange().getBegin(),
1732           diag::ext_typecheck_convert_incompatible_pointer)
1733        << From->getType() << ToType << Action
1734        << From->getSourceRange();
1735    }
1736
1737
1738    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1739    if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
1740      return true;
1741    ImpCastExprToType(From, ToType, Kind);
1742    break;
1743  }
1744
1745  case ICK_Pointer_Member: {
1746    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1747    if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
1748      return true;
1749    if (CheckExceptionSpecCompatibility(From, ToType))
1750      return true;
1751    ImpCastExprToType(From, ToType, Kind);
1752    break;
1753  }
1754  case ICK_Boolean_Conversion: {
1755    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1756    if (FromType->isMemberPointerType())
1757      Kind = CastExpr::CK_MemberPointerToBoolean;
1758
1759    ImpCastExprToType(From, Context.BoolTy, Kind);
1760    break;
1761  }
1762
1763  case ICK_Derived_To_Base:
1764    if (CheckDerivedToBaseConversion(From->getType(),
1765                                     ToType.getNonReferenceType(),
1766                                     From->getLocStart(),
1767                                     From->getSourceRange(),
1768                                     IgnoreBaseAccess))
1769      return true;
1770    ImpCastExprToType(From, ToType.getNonReferenceType(),
1771                      CastExpr::CK_DerivedToBase);
1772    break;
1773
1774  default:
1775    assert(false && "Improper second standard conversion");
1776    break;
1777  }
1778
1779  switch (SCS.Third) {
1780  case ICK_Identity:
1781    // Nothing to do.
1782    break;
1783
1784  case ICK_Qualification:
1785    // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1786    // references.
1787    ImpCastExprToType(From, ToType.getNonReferenceType(),
1788                      CastExpr::CK_NoOp,
1789                      ToType->isLValueReferenceType());
1790
1791    if (SCS.DeprecatedStringLiteralToCharPtr)
1792      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1793        << ToType.getNonReferenceType();
1794
1795    break;
1796
1797  default:
1798    assert(false && "Improper second standard conversion");
1799    break;
1800  }
1801
1802  return false;
1803}
1804
1805Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1806                                                 SourceLocation KWLoc,
1807                                                 SourceLocation LParen,
1808                                                 TypeTy *Ty,
1809                                                 SourceLocation RParen) {
1810  QualType T = GetTypeFromParser(Ty);
1811
1812  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1813  // all traits except __is_class, __is_enum and __is_union require a the type
1814  // to be complete.
1815  if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1816    if (RequireCompleteType(KWLoc, T,
1817                            diag::err_incomplete_type_used_in_type_trait_expr))
1818      return ExprError();
1819  }
1820
1821  // There is no point in eagerly computing the value. The traits are designed
1822  // to be used from type trait templates, so Ty will be a template parameter
1823  // 99% of the time.
1824  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1825                                                RParen, Context.BoolTy));
1826}
1827
1828QualType Sema::CheckPointerToMemberOperands(
1829  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
1830  const char *OpSpelling = isIndirect ? "->*" : ".*";
1831  // C++ 5.5p2
1832  //   The binary operator .* [p3: ->*] binds its second operand, which shall
1833  //   be of type "pointer to member of T" (where T is a completely-defined
1834  //   class type) [...]
1835  QualType RType = rex->getType();
1836  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1837  if (!MemPtr) {
1838    Diag(Loc, diag::err_bad_memptr_rhs)
1839      << OpSpelling << RType << rex->getSourceRange();
1840    return QualType();
1841  }
1842
1843  QualType Class(MemPtr->getClass(), 0);
1844
1845  if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1846    return QualType();
1847
1848  // C++ 5.5p2
1849  //   [...] to its first operand, which shall be of class T or of a class of
1850  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1851  //   such a class]
1852  QualType LType = lex->getType();
1853  if (isIndirect) {
1854    if (const PointerType *Ptr = LType->getAs<PointerType>())
1855      LType = Ptr->getPointeeType().getNonReferenceType();
1856    else {
1857      Diag(Loc, diag::err_bad_memptr_lhs)
1858        << OpSpelling << 1 << LType
1859        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
1860      return QualType();
1861    }
1862  }
1863
1864  if (!Context.hasSameUnqualifiedType(Class, LType)) {
1865    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1866                       /*DetectVirtual=*/false);
1867    // FIXME: Would it be useful to print full ambiguity paths, or is that
1868    // overkill?
1869    if (!IsDerivedFrom(LType, Class, Paths) ||
1870        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1871      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1872        << (int)isIndirect << lex->getType();
1873      return QualType();
1874    }
1875    // Cast LHS to type of use.
1876    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1877    bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1878    ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
1879  }
1880
1881  if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
1882    // Diagnose use of pointer-to-member type which when used as
1883    // the functional cast in a pointer-to-member expression.
1884    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1885     return QualType();
1886  }
1887  // C++ 5.5p2
1888  //   The result is an object or a function of the type specified by the
1889  //   second operand.
1890  // The cv qualifiers are the union of those in the pointer and the left side,
1891  // in accordance with 5.5p5 and 5.2.5.
1892  // FIXME: This returns a dereferenced member function pointer as a normal
1893  // function type. However, the only operation valid on such functions is
1894  // calling them. There's also a GCC extension to get a function pointer to the
1895  // thing, which is another complication, because this type - unlike the type
1896  // that is the result of this expression - takes the class as the first
1897  // argument.
1898  // We probably need a "MemberFunctionClosureType" or something like that.
1899  QualType Result = MemPtr->getPointeeType();
1900  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
1901  return Result;
1902}
1903
1904/// \brief Try to convert a type to another according to C++0x 5.16p3.
1905///
1906/// This is part of the parameter validation for the ? operator. If either
1907/// value operand is a class type, the two operands are attempted to be
1908/// converted to each other. This function does the conversion in one direction.
1909/// It returns true if the program is ill-formed and has already been diagnosed
1910/// as such.
1911static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1912                                SourceLocation QuestionLoc,
1913                                bool &HaveConversion,
1914                                QualType &ToType) {
1915  HaveConversion = false;
1916  ToType = To->getType();
1917
1918  InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1919                                                           SourceLocation());
1920  // C++0x 5.16p3
1921  //   The process for determining whether an operand expression E1 of type T1
1922  //   can be converted to match an operand expression E2 of type T2 is defined
1923  //   as follows:
1924  //   -- If E2 is an lvalue:
1925  bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1926  if (ToIsLvalue) {
1927    //   E1 can be converted to match E2 if E1 can be implicitly converted to
1928    //   type "lvalue reference to T2", subject to the constraint that in the
1929    //   conversion the reference must bind directly to E1.
1930    QualType T = Self.Context.getLValueReferenceType(ToType);
1931    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
1932
1933    InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1934    if (InitSeq.isDirectReferenceBinding()) {
1935      ToType = T;
1936      HaveConversion = true;
1937      return false;
1938    }
1939
1940    if (InitSeq.isAmbiguous())
1941      return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1942  }
1943
1944  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1945  //      -- if E1 and E2 have class type, and the underlying class types are
1946  //         the same or one is a base class of the other:
1947  QualType FTy = From->getType();
1948  QualType TTy = To->getType();
1949  const RecordType *FRec = FTy->getAs<RecordType>();
1950  const RecordType *TRec = TTy->getAs<RecordType>();
1951  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
1952                       Self.IsDerivedFrom(FTy, TTy);
1953  if (FRec && TRec &&
1954      (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1955    //         E1 can be converted to match E2 if the class of T2 is the
1956    //         same type as, or a base class of, the class of T1, and
1957    //         [cv2 > cv1].
1958    if (FRec == TRec || FDerivedFromT) {
1959      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
1960        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1961        InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1962        if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
1963          HaveConversion = true;
1964          return false;
1965        }
1966
1967        if (InitSeq.isAmbiguous())
1968          return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1969      }
1970    }
1971
1972    return false;
1973  }
1974
1975  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
1976  //        implicitly converted to the type that expression E2 would have
1977  //        if E2 were converted to an rvalue (or the type it has, if E2 is
1978  //        an rvalue).
1979  //
1980  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
1981  // to the array-to-pointer or function-to-pointer conversions.
1982  if (!TTy->getAs<TagType>())
1983    TTy = TTy.getUnqualifiedType();
1984
1985  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1986  InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1987  HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
1988  ToType = TTy;
1989  if (InitSeq.isAmbiguous())
1990    return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1991
1992  return false;
1993}
1994
1995/// \brief Try to find a common type for two according to C++0x 5.16p5.
1996///
1997/// This is part of the parameter validation for the ? operator. If either
1998/// value operand is a class type, overload resolution is used to find a
1999/// conversion to a common type.
2000static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2001                                    SourceLocation Loc) {
2002  Expr *Args[2] = { LHS, RHS };
2003  OverloadCandidateSet CandidateSet(Loc);
2004  Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
2005
2006  OverloadCandidateSet::iterator Best;
2007  switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
2008    case OR_Success:
2009      // We found a match. Perform the conversions on the arguments and move on.
2010      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
2011                                         Best->Conversions[0], Sema::AA_Converting) ||
2012          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
2013                                         Best->Conversions[1], Sema::AA_Converting))
2014        break;
2015      return false;
2016
2017    case OR_No_Viable_Function:
2018      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2019        << LHS->getType() << RHS->getType()
2020        << LHS->getSourceRange() << RHS->getSourceRange();
2021      return true;
2022
2023    case OR_Ambiguous:
2024      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2025        << LHS->getType() << RHS->getType()
2026        << LHS->getSourceRange() << RHS->getSourceRange();
2027      // FIXME: Print the possible common types by printing the return types of
2028      // the viable candidates.
2029      break;
2030
2031    case OR_Deleted:
2032      assert(false && "Conditional operator has only built-in overloads");
2033      break;
2034  }
2035  return true;
2036}
2037
2038/// \brief Perform an "extended" implicit conversion as returned by
2039/// TryClassUnification.
2040static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2041  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2042  InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2043                                                           SourceLocation());
2044  InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2045  Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2046                                    Sema::MultiExprArg(Self, (void **)&E, 1));
2047  if (Result.isInvalid())
2048    return true;
2049
2050  E = Result.takeAs<Expr>();
2051  return false;
2052}
2053
2054/// \brief Check the operands of ?: under C++ semantics.
2055///
2056/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2057/// extension. In this case, LHS == Cond. (But they're not aliases.)
2058QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2059                                           SourceLocation QuestionLoc) {
2060  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2061  // interface pointers.
2062
2063  // C++0x 5.16p1
2064  //   The first expression is contextually converted to bool.
2065  if (!Cond->isTypeDependent()) {
2066    if (CheckCXXBooleanCondition(Cond))
2067      return QualType();
2068  }
2069
2070  // Either of the arguments dependent?
2071  if (LHS->isTypeDependent() || RHS->isTypeDependent())
2072    return Context.DependentTy;
2073
2074  CheckSignCompare(LHS, RHS, QuestionLoc);
2075
2076  // C++0x 5.16p2
2077  //   If either the second or the third operand has type (cv) void, ...
2078  QualType LTy = LHS->getType();
2079  QualType RTy = RHS->getType();
2080  bool LVoid = LTy->isVoidType();
2081  bool RVoid = RTy->isVoidType();
2082  if (LVoid || RVoid) {
2083    //   ... then the [l2r] conversions are performed on the second and third
2084    //   operands ...
2085    DefaultFunctionArrayLvalueConversion(LHS);
2086    DefaultFunctionArrayLvalueConversion(RHS);
2087    LTy = LHS->getType();
2088    RTy = RHS->getType();
2089
2090    //   ... and one of the following shall hold:
2091    //   -- The second or the third operand (but not both) is a throw-
2092    //      expression; the result is of the type of the other and is an rvalue.
2093    bool LThrow = isa<CXXThrowExpr>(LHS);
2094    bool RThrow = isa<CXXThrowExpr>(RHS);
2095    if (LThrow && !RThrow)
2096      return RTy;
2097    if (RThrow && !LThrow)
2098      return LTy;
2099
2100    //   -- Both the second and third operands have type void; the result is of
2101    //      type void and is an rvalue.
2102    if (LVoid && RVoid)
2103      return Context.VoidTy;
2104
2105    // Neither holds, error.
2106    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2107      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2108      << LHS->getSourceRange() << RHS->getSourceRange();
2109    return QualType();
2110  }
2111
2112  // Neither is void.
2113
2114  // C++0x 5.16p3
2115  //   Otherwise, if the second and third operand have different types, and
2116  //   either has (cv) class type, and attempt is made to convert each of those
2117  //   operands to the other.
2118  if (!Context.hasSameType(LTy, RTy) &&
2119      (LTy->isRecordType() || RTy->isRecordType())) {
2120    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2121    // These return true if a single direction is already ambiguous.
2122    QualType L2RType, R2LType;
2123    bool HaveL2R, HaveR2L;
2124    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
2125      return QualType();
2126    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
2127      return QualType();
2128
2129    //   If both can be converted, [...] the program is ill-formed.
2130    if (HaveL2R && HaveR2L) {
2131      Diag(QuestionLoc, diag::err_conditional_ambiguous)
2132        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2133      return QualType();
2134    }
2135
2136    //   If exactly one conversion is possible, that conversion is applied to
2137    //   the chosen operand and the converted operands are used in place of the
2138    //   original operands for the remainder of this section.
2139    if (HaveL2R) {
2140      if (ConvertForConditional(*this, LHS, L2RType))
2141        return QualType();
2142      LTy = LHS->getType();
2143    } else if (HaveR2L) {
2144      if (ConvertForConditional(*this, RHS, R2LType))
2145        return QualType();
2146      RTy = RHS->getType();
2147    }
2148  }
2149
2150  // C++0x 5.16p4
2151  //   If the second and third operands are lvalues and have the same type,
2152  //   the result is of that type [...]
2153  bool Same = Context.hasSameType(LTy, RTy);
2154  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2155      RHS->isLvalue(Context) == Expr::LV_Valid)
2156    return LTy;
2157
2158  // C++0x 5.16p5
2159  //   Otherwise, the result is an rvalue. If the second and third operands
2160  //   do not have the same type, and either has (cv) class type, ...
2161  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2162    //   ... overload resolution is used to determine the conversions (if any)
2163    //   to be applied to the operands. If the overload resolution fails, the
2164    //   program is ill-formed.
2165    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2166      return QualType();
2167  }
2168
2169  // C++0x 5.16p6
2170  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2171  //   conversions are performed on the second and third operands.
2172  DefaultFunctionArrayLvalueConversion(LHS);
2173  DefaultFunctionArrayLvalueConversion(RHS);
2174  LTy = LHS->getType();
2175  RTy = RHS->getType();
2176
2177  //   After those conversions, one of the following shall hold:
2178  //   -- The second and third operands have the same type; the result
2179  //      is of that type.
2180  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2181    return LTy;
2182
2183  //   -- The second and third operands have arithmetic or enumeration type;
2184  //      the usual arithmetic conversions are performed to bring them to a
2185  //      common type, and the result is of that type.
2186  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2187    UsualArithmeticConversions(LHS, RHS);
2188    return LHS->getType();
2189  }
2190
2191  //   -- The second and third operands have pointer type, or one has pointer
2192  //      type and the other is a null pointer constant; pointer conversions
2193  //      and qualification conversions are performed to bring them to their
2194  //      composite pointer type. The result is of the composite pointer type.
2195  //   -- The second and third operands have pointer to member type, or one has
2196  //      pointer to member type and the other is a null pointer constant;
2197  //      pointer to member conversions and qualification conversions are
2198  //      performed to bring them to a common type, whose cv-qualification
2199  //      shall match the cv-qualification of either the second or the third
2200  //      operand. The result is of the common type.
2201  bool NonStandardCompositeType = false;
2202  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
2203                              isSFINAEContext()? 0 : &NonStandardCompositeType);
2204  if (!Composite.isNull()) {
2205    if (NonStandardCompositeType)
2206      Diag(QuestionLoc,
2207           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2208        << LTy << RTy << Composite
2209        << LHS->getSourceRange() << RHS->getSourceRange();
2210
2211    return Composite;
2212  }
2213
2214  // Similarly, attempt to find composite type of two objective-c pointers.
2215  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2216  if (!Composite.isNull())
2217    return Composite;
2218
2219  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2220    << LHS->getType() << RHS->getType()
2221    << LHS->getSourceRange() << RHS->getSourceRange();
2222  return QualType();
2223}
2224
2225/// \brief Find a merged pointer type and convert the two expressions to it.
2226///
2227/// This finds the composite pointer type (or member pointer type) for @p E1
2228/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2229/// type and returns it.
2230/// It does not emit diagnostics.
2231///
2232/// \param Loc The location of the operator requiring these two expressions to
2233/// be converted to the composite pointer type.
2234///
2235/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2236/// a non-standard (but still sane) composite type to which both expressions
2237/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2238/// will be set true.
2239QualType Sema::FindCompositePointerType(SourceLocation Loc,
2240                                        Expr *&E1, Expr *&E2,
2241                                        bool *NonStandardCompositeType) {
2242  if (NonStandardCompositeType)
2243    *NonStandardCompositeType = false;
2244
2245  assert(getLangOptions().CPlusPlus && "This function assumes C++");
2246  QualType T1 = E1->getType(), T2 = E2->getType();
2247
2248  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2249      !T2->isAnyPointerType() && !T2->isMemberPointerType())
2250   return QualType();
2251
2252  // C++0x 5.9p2
2253  //   Pointer conversions and qualification conversions are performed on
2254  //   pointer operands to bring them to their composite pointer type. If
2255  //   one operand is a null pointer constant, the composite pointer type is
2256  //   the type of the other operand.
2257  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2258    if (T2->isMemberPointerType())
2259      ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2260    else
2261      ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
2262    return T2;
2263  }
2264  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2265    if (T1->isMemberPointerType())
2266      ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2267    else
2268      ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
2269    return T1;
2270  }
2271
2272  // Now both have to be pointers or member pointers.
2273  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2274      (!T2->isPointerType() && !T2->isMemberPointerType()))
2275    return QualType();
2276
2277  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
2278  //   the other has type "pointer to cv2 T" and the composite pointer type is
2279  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2280  //   Otherwise, the composite pointer type is a pointer type similar to the
2281  //   type of one of the operands, with a cv-qualification signature that is
2282  //   the union of the cv-qualification signatures of the operand types.
2283  // In practice, the first part here is redundant; it's subsumed by the second.
2284  // What we do here is, we build the two possible composite types, and try the
2285  // conversions in both directions. If only one works, or if the two composite
2286  // types are the same, we have succeeded.
2287  // FIXME: extended qualifiers?
2288  typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2289  QualifierVector QualifierUnion;
2290  typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2291      ContainingClassVector;
2292  ContainingClassVector MemberOfClass;
2293  QualType Composite1 = Context.getCanonicalType(T1),
2294           Composite2 = Context.getCanonicalType(T2);
2295  unsigned NeedConstBefore = 0;
2296  do {
2297    const PointerType *Ptr1, *Ptr2;
2298    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2299        (Ptr2 = Composite2->getAs<PointerType>())) {
2300      Composite1 = Ptr1->getPointeeType();
2301      Composite2 = Ptr2->getPointeeType();
2302
2303      // If we're allowed to create a non-standard composite type, keep track
2304      // of where we need to fill in additional 'const' qualifiers.
2305      if (NonStandardCompositeType &&
2306          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2307        NeedConstBefore = QualifierUnion.size();
2308
2309      QualifierUnion.push_back(
2310                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2311      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2312      continue;
2313    }
2314
2315    const MemberPointerType *MemPtr1, *MemPtr2;
2316    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2317        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2318      Composite1 = MemPtr1->getPointeeType();
2319      Composite2 = MemPtr2->getPointeeType();
2320
2321      // If we're allowed to create a non-standard composite type, keep track
2322      // of where we need to fill in additional 'const' qualifiers.
2323      if (NonStandardCompositeType &&
2324          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2325        NeedConstBefore = QualifierUnion.size();
2326
2327      QualifierUnion.push_back(
2328                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2329      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2330                                             MemPtr2->getClass()));
2331      continue;
2332    }
2333
2334    // FIXME: block pointer types?
2335
2336    // Cannot unwrap any more types.
2337    break;
2338  } while (true);
2339
2340  if (NeedConstBefore && NonStandardCompositeType) {
2341    // Extension: Add 'const' to qualifiers that come before the first qualifier
2342    // mismatch, so that our (non-standard!) composite type meets the
2343    // requirements of C++ [conv.qual]p4 bullet 3.
2344    for (unsigned I = 0; I != NeedConstBefore; ++I) {
2345      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2346        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2347        *NonStandardCompositeType = true;
2348      }
2349    }
2350  }
2351
2352  // Rewrap the composites as pointers or member pointers with the union CVRs.
2353  ContainingClassVector::reverse_iterator MOC
2354    = MemberOfClass.rbegin();
2355  for (QualifierVector::reverse_iterator
2356         I = QualifierUnion.rbegin(),
2357         E = QualifierUnion.rend();
2358       I != E; (void)++I, ++MOC) {
2359    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
2360    if (MOC->first && MOC->second) {
2361      // Rebuild member pointer type
2362      Composite1 = Context.getMemberPointerType(
2363                                    Context.getQualifiedType(Composite1, Quals),
2364                                    MOC->first);
2365      Composite2 = Context.getMemberPointerType(
2366                                    Context.getQualifiedType(Composite2, Quals),
2367                                    MOC->second);
2368    } else {
2369      // Rebuild pointer type
2370      Composite1
2371        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2372      Composite2
2373        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
2374    }
2375  }
2376
2377  // Try to convert to the first composite pointer type.
2378  InitializedEntity Entity1
2379    = InitializedEntity::InitializeTemporary(Composite1);
2380  InitializationKind Kind
2381    = InitializationKind::CreateCopy(Loc, SourceLocation());
2382  InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2383  InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
2384
2385  if (E1ToC1 && E2ToC1) {
2386    // Conversion to Composite1 is viable.
2387    if (!Context.hasSameType(Composite1, Composite2)) {
2388      // Composite2 is a different type from Composite1. Check whether
2389      // Composite2 is also viable.
2390      InitializedEntity Entity2
2391        = InitializedEntity::InitializeTemporary(Composite2);
2392      InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2393      InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2394      if (E1ToC2 && E2ToC2) {
2395        // Both Composite1 and Composite2 are viable and are different;
2396        // this is an ambiguity.
2397        return QualType();
2398      }
2399    }
2400
2401    // Convert E1 to Composite1
2402    OwningExprResult E1Result
2403      = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2404    if (E1Result.isInvalid())
2405      return QualType();
2406    E1 = E1Result.takeAs<Expr>();
2407
2408    // Convert E2 to Composite1
2409    OwningExprResult E2Result
2410      = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2411    if (E2Result.isInvalid())
2412      return QualType();
2413    E2 = E2Result.takeAs<Expr>();
2414
2415    return Composite1;
2416  }
2417
2418  // Check whether Composite2 is viable.
2419  InitializedEntity Entity2
2420    = InitializedEntity::InitializeTemporary(Composite2);
2421  InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2422  InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2423  if (!E1ToC2 || !E2ToC2)
2424    return QualType();
2425
2426  // Convert E1 to Composite2
2427  OwningExprResult E1Result
2428    = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2429  if (E1Result.isInvalid())
2430    return QualType();
2431  E1 = E1Result.takeAs<Expr>();
2432
2433  // Convert E2 to Composite2
2434  OwningExprResult E2Result
2435    = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2436  if (E2Result.isInvalid())
2437    return QualType();
2438  E2 = E2Result.takeAs<Expr>();
2439
2440  return Composite2;
2441}
2442
2443Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
2444  if (!Context.getLangOptions().CPlusPlus)
2445    return Owned(E);
2446
2447  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2448
2449  const RecordType *RT = E->getType()->getAs<RecordType>();
2450  if (!RT)
2451    return Owned(E);
2452
2453  // If this is the result of a call expression, our source might
2454  // actually be a reference, in which case we shouldn't bind.
2455  if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2456    QualType Ty = CE->getCallee()->getType();
2457    if (const PointerType *PT = Ty->getAs<PointerType>())
2458      Ty = PT->getPointeeType();
2459    else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2460      Ty = BPT->getPointeeType();
2461
2462    const FunctionType *FTy = Ty->getAs<FunctionType>();
2463    if (FTy->getResultType()->isReferenceType())
2464      return Owned(E);
2465  }
2466
2467  // That should be enough to guarantee that this type is complete.
2468  // If it has a trivial destructor, we can avoid the extra copy.
2469  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2470  if (RD->hasTrivialDestructor())
2471    return Owned(E);
2472
2473  CXXTemporary *Temp = CXXTemporary::Create(Context,
2474                                            RD->getDestructor(Context));
2475  ExprTemporaries.push_back(Temp);
2476  if (CXXDestructorDecl *Destructor =
2477        const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
2478    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
2479    CheckDestructorAccess(E->getExprLoc(), Destructor,
2480                          PDiag(diag::err_access_dtor_temp)
2481                            << E->getType());
2482  }
2483  // FIXME: Add the temporary to the temporaries vector.
2484  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2485}
2486
2487Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
2488  assert(SubExpr && "sub expression can't be null!");
2489
2490  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2491  assert(ExprTemporaries.size() >= FirstTemporary);
2492  if (ExprTemporaries.size() == FirstTemporary)
2493    return SubExpr;
2494
2495  Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
2496                                           &ExprTemporaries[FirstTemporary],
2497                                       ExprTemporaries.size() - FirstTemporary);
2498  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2499                        ExprTemporaries.end());
2500
2501  return E;
2502}
2503
2504Sema::OwningExprResult
2505Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2506  if (SubExpr.isInvalid())
2507    return ExprError();
2508
2509  return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2510}
2511
2512FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2513  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2514  assert(ExprTemporaries.size() >= FirstTemporary);
2515
2516  unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2517  CXXTemporary **Temporaries =
2518    NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2519
2520  FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2521
2522  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2523                        ExprTemporaries.end());
2524
2525  return E;
2526}
2527
2528Sema::OwningExprResult
2529Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2530                                   tok::TokenKind OpKind, TypeTy *&ObjectType,
2531                                   bool &MayBePseudoDestructor) {
2532  // Since this might be a postfix expression, get rid of ParenListExprs.
2533  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2534
2535  Expr *BaseExpr = (Expr*)Base.get();
2536  assert(BaseExpr && "no record expansion");
2537
2538  QualType BaseType = BaseExpr->getType();
2539  MayBePseudoDestructor = false;
2540  if (BaseType->isDependentType()) {
2541    // If we have a pointer to a dependent type and are using the -> operator,
2542    // the object type is the type that the pointer points to. We might still
2543    // have enough information about that type to do something useful.
2544    if (OpKind == tok::arrow)
2545      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2546        BaseType = Ptr->getPointeeType();
2547
2548    ObjectType = BaseType.getAsOpaquePtr();
2549    MayBePseudoDestructor = true;
2550    return move(Base);
2551  }
2552
2553  // C++ [over.match.oper]p8:
2554  //   [...] When operator->returns, the operator-> is applied  to the value
2555  //   returned, with the original second operand.
2556  if (OpKind == tok::arrow) {
2557    // The set of types we've considered so far.
2558    llvm::SmallPtrSet<CanQualType,8> CTypes;
2559    llvm::SmallVector<SourceLocation, 8> Locations;
2560    CTypes.insert(Context.getCanonicalType(BaseType));
2561
2562    while (BaseType->isRecordType()) {
2563      Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
2564      BaseExpr = (Expr*)Base.get();
2565      if (BaseExpr == NULL)
2566        return ExprError();
2567      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
2568        Locations.push_back(OpCall->getDirectCallee()->getLocation());
2569      BaseType = BaseExpr->getType();
2570      CanQualType CBaseType = Context.getCanonicalType(BaseType);
2571      if (!CTypes.insert(CBaseType)) {
2572        Diag(OpLoc, diag::err_operator_arrow_circular);
2573        for (unsigned i = 0; i < Locations.size(); i++)
2574          Diag(Locations[i], diag::note_declared_at);
2575        return ExprError();
2576      }
2577    }
2578
2579    if (BaseType->isPointerType())
2580      BaseType = BaseType->getPointeeType();
2581  }
2582
2583  // We could end up with various non-record types here, such as extended
2584  // vector types or Objective-C interfaces. Just return early and let
2585  // ActOnMemberReferenceExpr do the work.
2586  if (!BaseType->isRecordType()) {
2587    // C++ [basic.lookup.classref]p2:
2588    //   [...] If the type of the object expression is of pointer to scalar
2589    //   type, the unqualified-id is looked up in the context of the complete
2590    //   postfix-expression.
2591    //
2592    // This also indicates that we should be parsing a
2593    // pseudo-destructor-name.
2594    ObjectType = 0;
2595    MayBePseudoDestructor = true;
2596    return move(Base);
2597  }
2598
2599  // The object type must be complete (or dependent).
2600  if (!BaseType->isDependentType() &&
2601      RequireCompleteType(OpLoc, BaseType,
2602                          PDiag(diag::err_incomplete_member_access)))
2603    return ExprError();
2604
2605  // C++ [basic.lookup.classref]p2:
2606  //   If the id-expression in a class member access (5.2.5) is an
2607  //   unqualified-id, and the type of the object expression is of a class
2608  //   type C (or of pointer to a class type C), the unqualified-id is looked
2609  //   up in the scope of class C. [...]
2610  ObjectType = BaseType.getAsOpaquePtr();
2611  return move(Base);
2612}
2613
2614Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2615                                                   ExprArg MemExpr) {
2616  Expr *E = (Expr *) MemExpr.get();
2617  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2618  Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2619    << isa<CXXPseudoDestructorExpr>(E)
2620    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
2621
2622  return ActOnCallExpr(/*Scope*/ 0,
2623                       move(MemExpr),
2624                       /*LPLoc*/ ExpectedLParenLoc,
2625                       Sema::MultiExprArg(*this, 0, 0),
2626                       /*CommaLocs*/ 0,
2627                       /*RPLoc*/ ExpectedLParenLoc);
2628}
2629
2630Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2631                                                       SourceLocation OpLoc,
2632                                                       tok::TokenKind OpKind,
2633                                                       const CXXScopeSpec &SS,
2634                                                 TypeSourceInfo *ScopeTypeInfo,
2635                                                       SourceLocation CCLoc,
2636                                                       SourceLocation TildeLoc,
2637                                         PseudoDestructorTypeStorage Destructed,
2638                                                       bool HasTrailingLParen) {
2639  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
2640
2641  // C++ [expr.pseudo]p2:
2642  //   The left-hand side of the dot operator shall be of scalar type. The
2643  //   left-hand side of the arrow operator shall be of pointer to scalar type.
2644  //   This scalar type is the object type.
2645  Expr *BaseE = (Expr *)Base.get();
2646  QualType ObjectType = BaseE->getType();
2647  if (OpKind == tok::arrow) {
2648    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2649      ObjectType = Ptr->getPointeeType();
2650    } else if (!BaseE->isTypeDependent()) {
2651      // The user wrote "p->" when she probably meant "p."; fix it.
2652      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2653        << ObjectType << true
2654        << FixItHint::CreateReplacement(OpLoc, ".");
2655      if (isSFINAEContext())
2656        return ExprError();
2657
2658      OpKind = tok::period;
2659    }
2660  }
2661
2662  if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2663    Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2664      << ObjectType << BaseE->getSourceRange();
2665    return ExprError();
2666  }
2667
2668  // C++ [expr.pseudo]p2:
2669  //   [...] The cv-unqualified versions of the object type and of the type
2670  //   designated by the pseudo-destructor-name shall be the same type.
2671  if (DestructedTypeInfo) {
2672    QualType DestructedType = DestructedTypeInfo->getType();
2673    SourceLocation DestructedTypeStart
2674      = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2675    if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2676        !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2677      Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2678        << ObjectType << DestructedType << BaseE->getSourceRange()
2679        << DestructedTypeInfo->getTypeLoc().getSourceRange();
2680
2681      // Recover by setting the destructed type to the object type.
2682      DestructedType = ObjectType;
2683      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2684                                                           DestructedTypeStart);
2685      Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2686    }
2687  }
2688
2689  // C++ [expr.pseudo]p2:
2690  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2691  //   form
2692  //
2693  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2694  //
2695  //   shall designate the same scalar type.
2696  if (ScopeTypeInfo) {
2697    QualType ScopeType = ScopeTypeInfo->getType();
2698    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2699        !Context.hasSameType(ScopeType, ObjectType)) {
2700
2701      Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2702           diag::err_pseudo_dtor_type_mismatch)
2703        << ObjectType << ScopeType << BaseE->getSourceRange()
2704        << ScopeTypeInfo->getTypeLoc().getSourceRange();
2705
2706      ScopeType = QualType();
2707      ScopeTypeInfo = 0;
2708    }
2709  }
2710
2711  OwningExprResult Result
2712    = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2713                                                  Base.takeAs<Expr>(),
2714                                                  OpKind == tok::arrow,
2715                                                  OpLoc,
2716                                       (NestedNameSpecifier *) SS.getScopeRep(),
2717                                                  SS.getRange(),
2718                                                  ScopeTypeInfo,
2719                                                  CCLoc,
2720                                                  TildeLoc,
2721                                                  Destructed));
2722
2723  if (HasTrailingLParen)
2724    return move(Result);
2725
2726  return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
2727}
2728
2729Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2730                                                       SourceLocation OpLoc,
2731                                                       tok::TokenKind OpKind,
2732                                                       CXXScopeSpec &SS,
2733                                                  UnqualifiedId &FirstTypeName,
2734                                                       SourceLocation CCLoc,
2735                                                       SourceLocation TildeLoc,
2736                                                 UnqualifiedId &SecondTypeName,
2737                                                       bool HasTrailingLParen) {
2738  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2739          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2740         "Invalid first type name in pseudo-destructor");
2741  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2742          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2743         "Invalid second type name in pseudo-destructor");
2744
2745  Expr *BaseE = (Expr *)Base.get();
2746
2747  // C++ [expr.pseudo]p2:
2748  //   The left-hand side of the dot operator shall be of scalar type. The
2749  //   left-hand side of the arrow operator shall be of pointer to scalar type.
2750  //   This scalar type is the object type.
2751  QualType ObjectType = BaseE->getType();
2752  if (OpKind == tok::arrow) {
2753    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2754      ObjectType = Ptr->getPointeeType();
2755    } else if (!ObjectType->isDependentType()) {
2756      // The user wrote "p->" when she probably meant "p."; fix it.
2757      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2758        << ObjectType << true
2759        << FixItHint::CreateReplacement(OpLoc, ".");
2760      if (isSFINAEContext())
2761        return ExprError();
2762
2763      OpKind = tok::period;
2764    }
2765  }
2766
2767  // Compute the object type that we should use for name lookup purposes. Only
2768  // record types and dependent types matter.
2769  void *ObjectTypePtrForLookup = 0;
2770  if (!SS.isSet()) {
2771    ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2772    if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2773      ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2774  }
2775
2776  // Convert the name of the type being destructed (following the ~) into a
2777  // type (with source-location information).
2778  QualType DestructedType;
2779  TypeSourceInfo *DestructedTypeInfo = 0;
2780  PseudoDestructorTypeStorage Destructed;
2781  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2782    TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2783                            SecondTypeName.StartLocation,
2784                            S, &SS, true, ObjectTypePtrForLookup);
2785    if (!T &&
2786        ((SS.isSet() && !computeDeclContext(SS, false)) ||
2787         (!SS.isSet() && ObjectType->isDependentType()))) {
2788      // The name of the type being destroyed is a dependent name, and we
2789      // couldn't find anything useful in scope. Just store the identifier and
2790      // it's location, and we'll perform (qualified) name lookup again at
2791      // template instantiation time.
2792      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2793                                               SecondTypeName.StartLocation);
2794    } else if (!T) {
2795      Diag(SecondTypeName.StartLocation,
2796           diag::err_pseudo_dtor_destructor_non_type)
2797        << SecondTypeName.Identifier << ObjectType;
2798      if (isSFINAEContext())
2799        return ExprError();
2800
2801      // Recover by assuming we had the right type all along.
2802      DestructedType = ObjectType;
2803    } else
2804      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
2805  } else {
2806    // Resolve the template-id to a type.
2807    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
2808    ASTTemplateArgsPtr TemplateArgsPtr(*this,
2809                                       TemplateId->getTemplateArgs(),
2810                                       TemplateId->NumArgs);
2811    TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2812                                       TemplateId->TemplateNameLoc,
2813                                       TemplateId->LAngleLoc,
2814                                       TemplateArgsPtr,
2815                                       TemplateId->RAngleLoc);
2816    if (T.isInvalid() || !T.get()) {
2817      // Recover by assuming we had the right type all along.
2818      DestructedType = ObjectType;
2819    } else
2820      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
2821  }
2822
2823  // If we've performed some kind of recovery, (re-)build the type source
2824  // information.
2825  if (!DestructedType.isNull()) {
2826    if (!DestructedTypeInfo)
2827      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
2828                                                  SecondTypeName.StartLocation);
2829    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2830  }
2831
2832  // Convert the name of the scope type (the type prior to '::') into a type.
2833  TypeSourceInfo *ScopeTypeInfo = 0;
2834  QualType ScopeType;
2835  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2836      FirstTypeName.Identifier) {
2837    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2838      TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2839                              FirstTypeName.StartLocation,
2840                              S, &SS, false, ObjectTypePtrForLookup);
2841      if (!T) {
2842        Diag(FirstTypeName.StartLocation,
2843             diag::err_pseudo_dtor_destructor_non_type)
2844          << FirstTypeName.Identifier << ObjectType;
2845
2846        if (isSFINAEContext())
2847          return ExprError();
2848
2849        // Just drop this type. It's unnecessary anyway.
2850        ScopeType = QualType();
2851      } else
2852        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
2853    } else {
2854      // Resolve the template-id to a type.
2855      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
2856      ASTTemplateArgsPtr TemplateArgsPtr(*this,
2857                                         TemplateId->getTemplateArgs(),
2858                                         TemplateId->NumArgs);
2859      TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2860                                         TemplateId->TemplateNameLoc,
2861                                         TemplateId->LAngleLoc,
2862                                         TemplateArgsPtr,
2863                                         TemplateId->RAngleLoc);
2864      if (T.isInvalid() || !T.get()) {
2865        // Recover by dropping this type.
2866        ScopeType = QualType();
2867      } else
2868        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
2869    }
2870  }
2871
2872  if (!ScopeType.isNull() && !ScopeTypeInfo)
2873    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2874                                                  FirstTypeName.StartLocation);
2875
2876
2877  return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
2878                                   ScopeTypeInfo, CCLoc, TildeLoc,
2879                                   Destructed, HasTrailingLParen);
2880}
2881
2882CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2883                                                NamedDecl *FoundDecl,
2884                                                CXXMethodDecl *Method) {
2885  if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2886                                          FoundDecl, Method))
2887    assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2888
2889  MemberExpr *ME =
2890      new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2891                               SourceLocation(), Method->getType());
2892  QualType ResultType = Method->getResultType().getNonReferenceType();
2893  MarkDeclarationReferenced(Exp->getLocStart(), Method);
2894  CXXMemberCallExpr *CE =
2895    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2896                                    Exp->getLocEnd());
2897  return CE;
2898}
2899
2900Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2901  Expr *FullExpr = Arg.takeAs<Expr>();
2902  if (FullExpr)
2903    FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
2904
2905  return Owned(FullExpr);
2906}
2907