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