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