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