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