SemaExprCXX.cpp revision 207619
1234353Sdim//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2218885Sdim//
3218885Sdim//                     The LLVM Compiler Infrastructure
4218885Sdim//
5218885Sdim// This file is distributed under the University of Illinois Open Source
6218885Sdim// License. See LICENSE.TXT for details.
7218885Sdim//
8218885Sdim//===----------------------------------------------------------------------===//
9218885Sdim//
10218885Sdim//  This file implements semantic analysis for C++ expressions.
11218885Sdim//
12218885Sdim//===----------------------------------------------------------------------===//
13218885Sdim
14218885Sdim#include "Sema.h"
15249423Sdim#include "SemaInit.h"
16249423Sdim#include "Lookup.h"
17276479Sdim#include "clang/AST/ASTContext.h"
18239462Sdim#include "clang/AST/CXXInheritance.h"
19224145Sdim#include "clang/AST/ExprCXX.h"
20218885Sdim#include "clang/AST/TypeLoc.h"
21239462Sdim#include "clang/Basic/PartialDiagnostic.h"
22288943Sdim#include "clang/Basic/TargetInfo.h"
23261991Sdim#include "clang/Lex/Preprocessor.h"
24234353Sdim#include "clang/Parse/DeclSpec.h"
25234353Sdim#include "clang/Parse/Template.h"
26218885Sdim#include "llvm/ADT/STLExtras.h"
27218885Sdimusing namespace clang;
28239462Sdim
29218885SdimAction::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30276479Sdim                                        IdentifierInfo &II,
31226633Sdim                                        SourceLocation NameLoc,
32249423Sdim                                        Scope *S, CXXScopeSpec &SS,
33249423Sdim                                        TypeTy *ObjectTypePtr,
34249423Sdim                                        bool EnteringContext) {
35249423Sdim  // Determine where to perform name lookup.
36276479Sdim
37218885Sdim  // FIXME: This area of the standard is very messy, and the current
38276479Sdim  // wording is rather unclear about which scopes we search for the
39261991Sdim  // destructor name; see core issues 399 and 555. Issue 399 in
40276479Sdim  // particular shows where the current description of destructor name
41224145Sdim  // lookup is completely out of line with existing practice, e.g.,
42276479Sdim  // this appears to be ill-formed:
43276479Sdim  //
44288943Sdim  //   namespace N {
45249423Sdim  //     template <typename T> struct S {
46249423Sdim  //       ~S();
47239462Sdim  //     };
48221345Sdim  //   }
49218885Sdim  //
50276479Sdim  //   void f(N::S<int>* s) {
51224145Sdim  //     s->N::S<int>::~S();
52218885Sdim  //   }
53218885Sdim  //
54276479Sdim  // See also PR6358 and PR6359.
55276479Sdim  QualType SearchType;
56280031Sdim  DeclContext *LookupCtx = 0;
57288943Sdim  bool isDependent = false;
58261991Sdim  bool LookInScope = false;
59261991Sdim
60234353Sdim  // If we have an object type, it's because we are in a
61288943Sdim  // pseudo-destructor-expression or a member access expression, and
62276479Sdim  // we know what type we're looking for.
63251662Sdim  if (ObjectTypePtr)
64276479Sdim    SearchType = GetTypeFromParser(ObjectTypePtr);
65251662Sdim
66276479Sdim  if (SS.isSet()) {
67234353Sdim    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68276479Sdim
69276479Sdim    bool AlreadySearched = false;
70276479Sdim    bool LookAtPrefix = true;
71276479Sdim    if (!getLangOptions().CPlusPlus0x) {
72276479Sdim      // C++ [basic.lookup.qual]p6:
73276479Sdim      //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
74276479Sdim      //   the type-names are looked up as types in the scope designated by the
75276479Sdim      //   nested-name-specifier. In a qualified-id of the form:
76276479Sdim      //
77276479Sdim      //     ::[opt] nested-name-specifier  �� class-name
78276479Sdim      //
79261991Sdim      //   where the nested-name-specifier designates a namespace scope, and in
80276479Sdim      //   a qualified-id of the form:
81276479Sdim      //
82276479Sdim      //     ::opt nested-name-specifier class-name ::  �� class-name
83276479Sdim      //
84276479Sdim      //   the class-names are looked up as types in the scope designated by
85234353Sdim      //   the nested-name-specifier.
86234353Sdim      //
87234353Sdim      // Here, we check the first case (completely) and determine whether the
88234353Sdim      // code below is permitted to look at the prefix of the
89243830Sdim      // nested-name-specifier (as we do in C++0x).
90243830Sdim      DeclContext *DC = computeDeclContext(SS, EnteringContext);
91243830Sdim      if (DC && DC->isFileContext()) {
92243830Sdim        AlreadySearched = true;
93243830Sdim        LookupCtx = DC;
94243830Sdim        isDependent = false;
95243830Sdim      } else if (DC && isa<CXXRecordDecl>(DC))
96276479Sdim        LookAtPrefix = false;
97276479Sdim    }
98276479Sdim
99276479Sdim    // C++0x [basic.lookup.qual]p6:
100276479Sdim    //   If a pseudo-destructor-name (5.2.4) contains a
101276479Sdim    //   nested-name-specifier, the type-names are looked up as types
102276479Sdim    //   in the scope designated by the nested-name-specifier. Similarly, in
103276479Sdim    //   a qualified-id of the form:
104276479Sdim    //
105276479Sdim    //     :: [opt] nested-name-specifier[opt] class-name :: ~class-name
106276479Sdim    //
107276479Sdim    //   the second class-name is looked up in the same scope as the first.
108276479Sdim    //
109276479Sdim    // To implement this, we look at the prefix of the
110276479Sdim    // nested-name-specifier we were given, and determine the lookup
111276479Sdim    // context from that.
112276479Sdim    //
113276479Sdim    // We also fold in the second case from the C++03 rules quoted further
114276479Sdim    // above.
115276479Sdim    NestedNameSpecifier *Prefix = 0;
116276479Sdim    if (AlreadySearched) {
117276479Sdim      // Nothing left to do.
118276479Sdim    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119276479Sdim      CXXScopeSpec PrefixSS;
120276479Sdim      PrefixSS.setScopeRep(Prefix);
121276479Sdim      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122276479Sdim      isDependent = isDependentScopeSpecifier(PrefixSS);
123288943Sdim    } else if (getLangOptions().CPlusPlus0x &&
124276479Sdim               (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125276479Sdim      if (!LookupCtx->isTranslationUnit())
126276479Sdim        LookupCtx = LookupCtx->getParent();
127276479Sdim      isDependent = LookupCtx && LookupCtx->isDependentContext();
128276479Sdim    } else if (ObjectTypePtr) {
129276479Sdim      LookupCtx = computeDeclContext(SearchType);
130276479Sdim      isDependent = SearchType->isDependentType();
131276479Sdim    } else {
132224145Sdim      LookupCtx = computeDeclContext(SS, EnteringContext);
133276479Sdim      isDependent = LookupCtx && LookupCtx->isDependentContext();
134280031Sdim    }
135276479Sdim
136234353Sdim    LookInScope = false;
137234353Sdim  } else if (ObjectTypePtr) {
138234353Sdim    // C++ [basic.lookup.classref]p3:
139218885Sdim    //   If the unqualified-id is ~type-name, the type-name is looked up
140224145Sdim    //   in the context of the entire postfix-expression. If the type T
141224145Sdim    //   of the object expression is of a class type C, the type-name is
142224145Sdim    //   also looked up in the scope of class C. At least one of the
143218885Sdim    //   lookups shall find a name that refers to (possibly
144261991Sdim    //   cv-qualified) T.
145261991Sdim    LookupCtx = computeDeclContext(SearchType);
146288943Sdim    isDependent = SearchType->isDependentType();
147261991Sdim    assert((isDependent || !SearchType->isIncompleteType()) &&
148261991Sdim           "Caller should have completed object type");
149261991Sdim
150261991Sdim    LookInScope = true;
151261991Sdim  } else {
152261991Sdim    // Perform lookup into the current scope (only).
153261991Sdim    LookInScope = true;
154261991Sdim  }
155261991Sdim
156261991Sdim  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157261991Sdim  for (unsigned Step = 0; Step != 2; ++Step) {
158261991Sdim    // Look for the name first in the computed lookup context (if we
159261991Sdim    // have one) and, if that fails to find a match, in the sope (if
160261991Sdim    // we're allowed to look there).
161261991Sdim    Found.clear();
162288943Sdim    if (Step == 0 && LookupCtx)
163261991Sdim      LookupQualifiedName(Found, LookupCtx);
164261991Sdim    else if (Step == 1 && LookInScope && S)
165261991Sdim      LookupName(Found, S);
166288943Sdim    else
167261991Sdim      continue;
168261991Sdim
169261991Sdim    // FIXME: Should we be suppressing ambiguities here?
170261991Sdim    if (Found.isAmbiguous())
171261991Sdim      return 0;
172296417Sdim
173261991Sdim    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174261991Sdim      QualType T = Context.getTypeDeclType(Type);
175261991Sdim
176261991Sdim      if (SearchType.isNull() || SearchType->isDependentType() ||
177296417Sdim          Context.hasSameUnqualifiedType(T, SearchType)) {
178239462Sdim        // We found our type!
179234353Sdim
180239462Sdim        return T.getAsOpaquePtr();
181249423Sdim      }
182288943Sdim    }
183249423Sdim
184249423Sdim    // If the name that we found is a class template name, and it is
185276479Sdim    // the same name as the template name in the last part of the
186276479Sdim    // nested-name-specifier (if present) or the object type, then
187276479Sdim    // this is the destructor for that class.
188276479Sdim    // FIXME: This is a workaround until we get real drafting for core
189288943Sdim    // issue 399, for which there isn't even an obvious direction.
190276479Sdim    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
191276479Sdim      QualType MemberOfType;
192276479Sdim      if (SS.isSet()) {
193249423Sdim        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
194249423Sdim          // Figure out the type of the context, if it has one.
195249423Sdim          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196249423Sdim            MemberOfType = Context.getTypeDeclType(Record);
197249423Sdim        }
198249423Sdim      }
199249423Sdim      if (MemberOfType.isNull())
200276479Sdim        MemberOfType = SearchType;
201276479Sdim
202249423Sdim      if (MemberOfType.isNull())
203249423Sdim        continue;
204239462Sdim
205296417Sdim      // We're referring into a class template specialization. If the
206288943Sdim      // class template we found is the same as the template being
207249423Sdim      // specialized, we found what we are looking for.
208224145Sdim      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
209218885Sdim        if (ClassTemplateSpecializationDecl *Spec
210218885Sdim              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
211218885Sdim          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
212218885Sdim                Template->getCanonicalDecl())
213218885Sdim            return MemberOfType.getAsOpaquePtr();
214218885Sdim        }
215218885Sdim
216218885Sdim        continue;
217221345Sdim      }
218218885Sdim
219221345Sdim      // We're referring to an unresolved class template
220221345Sdim      // specialization. Determine whether we class template we found
221218885Sdim      // is the same as the template being specialized or, if we don't
222221345Sdim      // know which template is being specialized, that it at least
223218885Sdim      // has the same name.
224218885Sdim      if (const TemplateSpecializationType *SpecType
225218885Sdim            = MemberOfType->getAs<TemplateSpecializationType>()) {
226218885Sdim        TemplateName SpecName = SpecType->getTemplateName();
227218885Sdim
228218885Sdim        // The class template we found is the same template being
229218885Sdim        // specialized.
230218885Sdim        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
231218885Sdim          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
232218885Sdim            return MemberOfType.getAsOpaquePtr();
233221345Sdim
234221345Sdim          continue;
235221345Sdim        }
236218885Sdim
237218885Sdim        // The class template we found has the same name as the
238218885Sdim        // (dependent) template name being specialized.
239218885Sdim        if (DependentTemplateName *DepTemplate
240218885Sdim                                    = SpecName.getAsDependentTemplateName()) {
241218885Sdim          if (DepTemplate->isIdentifier() &&
242218885Sdim              DepTemplate->getIdentifier() == Template->getIdentifier())
243218885Sdim            return MemberOfType.getAsOpaquePtr();
244218885Sdim
245221345Sdim          continue;
246218885Sdim        }
247276479Sdim      }
248218885Sdim    }
249223017Sdim  }
250223017Sdim
251218885Sdim  if (isDependent) {
252218885Sdim    // We didn't find our type, but that's okay: it's dependent
253218885Sdim    // anyway.
254288943Sdim    NestedNameSpecifier *NNS = 0;
255218885Sdim    SourceRange Range;
256223017Sdim    if (SS.isSet()) {
257261991Sdim      NNS = (NestedNameSpecifier *)SS.getScopeRep();
258239462Sdim      Range = SourceRange(SS.getRange().getBegin(), NameLoc);
259239462Sdim    } else {
260223017Sdim      NNS = NestedNameSpecifier::Create(Context, &II);
261223017Sdim      Range = SourceRange(NameLoc);
262223017Sdim    }
263288943Sdim
264288943Sdim    return CheckTypenameType(ETK_None, NNS, II, Range).getAsOpaquePtr();
265288943Sdim  }
266223017Sdim
267288943Sdim  if (ObjectTypePtr)
268288943Sdim    Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
269288943Sdim      << &II;
270288943Sdim  else
271288943Sdim    Diag(NameLoc, diag::err_destructor_class_name);
272288943Sdim
273223017Sdim  return 0;
274223017Sdim}
275223017Sdim
276288943Sdim/// \brief Build a C++ typeid expression with a type operand.
277288943SdimSema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
278218885Sdim                                            SourceLocation TypeidLoc,
279218885Sdim                                            TypeSourceInfo *Operand,
280223017Sdim                                            SourceLocation RParenLoc) {
281223017Sdim  // C++ [expr.typeid]p4:
282223017Sdim  //   The top-level cv-qualifiers of the lvalue expression or the type-id
283218885Sdim  //   that is the operand of typeid are always ignored.
284223017Sdim  //   If the type of the type-id is a class type or a reference to a class
285223017Sdim  //   type, the class shall be completely-defined.
286223017Sdim  QualType T = Operand->getType().getNonReferenceType();
287276479Sdim  if (T->getAs<RecordType>() &&
288218885Sdim      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
289276479Sdim    return ExprError();
290218885Sdim
291218885Sdim  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
292276479Sdim                                           Operand,
293218885Sdim                                           SourceRange(TypeidLoc, RParenLoc)));
294218885Sdim}
295218885Sdim
296218885Sdim/// \brief Build a C++ typeid expression with an expression operand.
297218885SdimSema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
298218885Sdim                                            SourceLocation TypeidLoc,
299218885Sdim                                            ExprArg Operand,
300218885Sdim                                            SourceLocation RParenLoc) {
301288943Sdim  bool isUnevaluatedOperand = true;
302218885Sdim  Expr *E = static_cast<Expr *>(Operand.get());
303218885Sdim  if (E && !E->isTypeDependent()) {
304218885Sdim    QualType T = E->getType();
305218885Sdim    if (const RecordType *RecordT = T->getAs<RecordType>()) {
306218885Sdim      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
307276479Sdim      // C++ [expr.typeid]p3:
308218885Sdim      //   [...] If the type of the expression is a class type, the class
309218885Sdim      //   shall be completely-defined.
310218885Sdim      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
311221345Sdim        return ExprError();
312288943Sdim
313277320Sdim      // C++ [expr.typeid]p3:
314277320Sdim      //   When typeid is applied to an expression other than an lvalue of a
315277320Sdim      //   polymorphic class type [...] [the] expression is an unevaluated
316277320Sdim      //   operand. [...]
317243830Sdim      if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
318218885Sdim        isUnevaluatedOperand = false;
319221345Sdim    }
320218885Sdim
321218885Sdim    // C++ [expr.typeid]p4:
322276479Sdim    //   [...] If the type of the type-id is a reference to a possibly
323249423Sdim    //   cv-qualified type, the result of the typeid expression refers to a
324276479Sdim    //   std::type_info object representing the cv-unqualified referenced
325276479Sdim    //   type.
326276479Sdim    if (T.hasQualifiers()) {
327276479Sdim      ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
328276479Sdim                        E->isLvalue(Context));
329249423Sdim      Operand.release();
330276479Sdim      Operand = Owned(E);
331276479Sdim    }
332276479Sdim  }
333276479Sdim
334276479Sdim  // If this is an unevaluated operand, clear out the set of
335276479Sdim  // declaration references we have been computing and eliminate any
336276479Sdim  // temporaries introduced in its computation.
337276479Sdim  if (isUnevaluatedOperand)
338276479Sdim    ExprEvalContexts.back().Context = Unevaluated;
339276479Sdim
340288943Sdim  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
341218885Sdim                                           Operand.takeAs<Expr>(),
342218885Sdim                                           SourceRange(TypeidLoc, RParenLoc)));
343218885Sdim}
344218885Sdim
345218885Sdim/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
346276479SdimAction::OwningExprResult
347276479SdimSema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
348261991Sdim                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
349234353Sdim  // Find the std::type_info type.
350288943Sdim  if (!StdNamespace)
351251662Sdim    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
352251662Sdim
353221345Sdim  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
354276479Sdim  LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
355276479Sdim  LookupQualifiedName(R, StdNamespace);
356276479Sdim  RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
357276479Sdim  if (!TypeInfoRecordDecl)
358276479Sdim    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
359276479Sdim
360276479Sdim  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
361234353Sdim
362218885Sdim  if (isType) {
363218885Sdim    // The operand is a type; handle it as such.
364218885Sdim    TypeSourceInfo *TInfo = 0;
365218885Sdim    QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
366218885Sdim    if (T.isNull())
367276479Sdim      return ExprError();
368276479Sdim
369218885Sdim    if (!TInfo)
370218885Sdim      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
371221345Sdim
372276479Sdim    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
373276479Sdim  }
374276479Sdim
375276479Sdim  // The operand is an expression.
376234353Sdim  return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
377276479Sdim}
378261991Sdim
379261991Sdim/// ActOnCXXBoolLiteral - Parse {true,false} literals.
380261991SdimAction::OwningExprResult
381261991SdimSema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
382261991Sdim  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
383288943Sdim         "Unknown C++ Boolean value!");
384218885Sdim  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
385218885Sdim                                                Context.BoolTy, OpLoc));
386288943Sdim}
387288943Sdim
388288943Sdim/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
389288943SdimAction::OwningExprResult
390288943SdimSema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
391288943Sdim  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
392218885Sdim}
393218885Sdim
394218885Sdim/// ActOnCXXThrow - Parse throw expressions.
395221345SdimAction::OwningExprResult
396221345SdimSema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
397218885Sdim  Expr *Ex = E.takeAs<Expr>();
398218885Sdim  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
399218885Sdim    return ExprError();
400218885Sdim  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
401218885Sdim}
402218885Sdim
403218885Sdim/// CheckCXXThrowOperand - Validate the operand of a throw.
404218885Sdimbool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
405221345Sdim  // C++ [except.throw]p3:
406221345Sdim  //   A throw-expression initializes a temporary object, called the exception
407221345Sdim  //   object, the type of which is determined by removing any top-level
408296417Sdim  //   cv-qualifiers from the static type of the operand of throw and adjusting
409221345Sdim  //   the type from "array of T" or "function returning T" to "pointer to T"
410221345Sdim  //   or "pointer to function returning T", [...]
411221345Sdim  if (E->getType().hasQualifiers())
412221345Sdim    ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
413221345Sdim                      E->isLvalue(Context) == Expr::LV_Valid);
414234353Sdim
415221345Sdim  DefaultFunctionArrayConversion(E);
416234353Sdim
417221345Sdim  //   If the type of the exception would be an incomplete type or a pointer
418221345Sdim  //   to an incomplete type other than (cv) void the program is ill-formed.
419221345Sdim  QualType Ty = E->getType();
420221345Sdim  bool isPointer = false;
421234353Sdim  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
422221345Sdim    Ty = Ptr->getPointeeType();
423221345Sdim    isPointer = true;
424221345Sdim  }
425234353Sdim  if (!isPointer || !Ty->isVoidType()) {
426221345Sdim    if (RequireCompleteType(ThrowLoc, Ty,
427221345Sdim                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
428221345Sdim                                            : diag::err_throw_incomplete)
429234353Sdim                              << E->getSourceRange()))
430221345Sdim      return true;
431234353Sdim
432218885Sdim    if (RequireNonAbstractType(ThrowLoc, E->getType(),
433218885Sdim                               PDiag(diag::err_throw_abstract_type)
434218885Sdim                                 << E->getSourceRange()))
435239462Sdim      return true;
436288943Sdim  }
437218885Sdim
438218885Sdim  // Initialize the exception result.  This implicitly weeds out
439239462Sdim  // abstract types or types with inaccessible copy constructors.
440239462Sdim  InitializedEntity Entity =
441218885Sdim    InitializedEntity::InitializeException(ThrowLoc, E->getType());
442239462Sdim  OwningExprResult Res = PerformCopyInitialization(Entity,
443239462Sdim                                                   SourceLocation(),
444239462Sdim                                                   Owned(E));
445239462Sdim  if (Res.isInvalid())
446239462Sdim    return true;
447239462Sdim  E = Res.takeAs<Expr>();
448239462Sdim  return false;
449239462Sdim}
450288943Sdim
451239462SdimAction::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
452239462Sdim  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
453239462Sdim  /// is a non-lvalue expression whose value is the address of the object for
454239462Sdim  /// which the function is called.
455288943Sdim
456239462Sdim  if (!isa<FunctionDecl>(CurContext))
457239462Sdim    return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
458239462Sdim
459239462Sdim  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
460239462Sdim    if (MD->isInstance())
461239462Sdim      return Owned(new (Context) CXXThisExpr(ThisLoc,
462239462Sdim                                             MD->getThisType(Context),
463239462Sdim                                             /*isImplicit=*/false));
464239462Sdim
465239462Sdim  return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
466239462Sdim}
467239462Sdim
468239462Sdim/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
469277320Sdim/// Can be interpreted either as function-style casting ("int(x)")
470239462Sdim/// or class type construction ("ClassType(x,y,z)")
471277320Sdim/// or creation of a value-initialized type ("int()").
472277320SdimAction::OwningExprResult
473277320SdimSema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
474277320Sdim                                SourceLocation LParenLoc,
475239462Sdim                                MultiExprArg exprs,
476239462Sdim                                SourceLocation *CommaLocs,
477239462Sdim                                SourceLocation RParenLoc) {
478239462Sdim  if (!TypeRep)
479239462Sdim    return ExprError();
480239462Sdim
481239462Sdim  TypeSourceInfo *TInfo;
482239462Sdim  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
483239462Sdim  if (!TInfo)
484239462Sdim    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
485239462Sdim  unsigned NumExprs = exprs.size();
486239462Sdim  Expr **Exprs = (Expr**)exprs.get();
487239462Sdim  SourceLocation TyBeginLoc = TypeRange.getBegin();
488239462Sdim  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
489239462Sdim
490239462Sdim  if (Ty->isDependentType() ||
491239462Sdim      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
492239462Sdim    exprs.release();
493239462Sdim
494239462Sdim    return Owned(CXXUnresolvedConstructExpr::Create(Context,
495239462Sdim                                                    TypeRange.getBegin(), Ty,
496239462Sdim                                                    LParenLoc,
497239462Sdim                                                    Exprs, NumExprs,
498239462Sdim                                                    RParenLoc));
499239462Sdim  }
500239462Sdim
501239462Sdim  if (Ty->isArrayType())
502239462Sdim    return ExprError(Diag(TyBeginLoc,
503239462Sdim                          diag::err_value_init_for_array_type) << FullRange);
504239462Sdim  if (!Ty->isVoidType() &&
505239462Sdim      RequireCompleteType(TyBeginLoc, Ty,
506239462Sdim                          PDiag(diag::err_invalid_incomplete_type_use)
507239462Sdim                            << FullRange))
508239462Sdim    return ExprError();
509239462Sdim
510239462Sdim  if (RequireNonAbstractType(TyBeginLoc, Ty,
511239462Sdim                             diag::err_allocation_of_abstract_type))
512239462Sdim    return ExprError();
513239462Sdim
514239462Sdim
515239462Sdim  // C++ [expr.type.conv]p1:
516239462Sdim  // If the expression list is a single expression, the type conversion
517239462Sdim  // expression is equivalent (in definedness, and if defined in meaning) to the
518239462Sdim  // corresponding cast expression.
519239462Sdim  //
520239462Sdim  if (NumExprs == 1) {
521239462Sdim    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
522261991Sdim    CXXBaseSpecifierArray BasePath;
523261991Sdim    if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
524261991Sdim                       /*FunctionalStyle=*/true))
525261991Sdim      return ExprError();
526261991Sdim
527239462Sdim    exprs.release();
528239462Sdim
529239462Sdim    return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
530239462Sdim                                                     TInfo, TyBeginLoc, Kind,
531218885Sdim                                                     Exprs[0], BasePath,
532218885Sdim                                                     RParenLoc));
533218885Sdim  }
534224145Sdim
535224145Sdim  if (const RecordType *RT = Ty->getAs<RecordType>()) {
536224145Sdim    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
537224145Sdim
538288943Sdim    if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
539288943Sdim        !Record->hasTrivialDestructor()) {
540288943Sdim      InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
541288943Sdim      InitializationKind Kind
542288943Sdim        = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
543288943Sdim                                                      LParenLoc, RParenLoc)
544288943Sdim                   : InitializationKind::CreateValue(TypeRange.getBegin(),
545251662Sdim                                                     LParenLoc, RParenLoc);
546251662Sdim      InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
547251662Sdim      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
548288943Sdim                                                move(exprs));
549251662Sdim
550251662Sdim      // FIXME: Improve AST representation?
551288943Sdim      return move(Result);
552288943Sdim    }
553251662Sdim
554234353Sdim    // Fall through to value-initialize an object of class type that
555288943Sdim    // doesn't have a user-declared default constructor.
556239462Sdim  }
557224145Sdim
558224145Sdim  // C++ [expr.type.conv]p1:
559224145Sdim  // If the expression list specifies more than a single value, the type shall
560218885Sdim  // be a class with a suitably declared constructor.
561218885Sdim  //
562218885Sdim  if (NumExprs > 1)
563218885Sdim    return ExprError(Diag(CommaLocs[0],
564218885Sdim                          diag::err_builtin_func_cast_more_than_one_arg)
565218885Sdim      << FullRange);
566218885Sdim
567218885Sdim  assert(NumExprs == 0 && "Expected 0 expressions");
568218885Sdim  // C++ [expr.type.conv]p2:
569218885Sdim  // The expression T(), where T is a simple-type-specifier for a non-array
570218885Sdim  // complete object type or the (possibly cv-qualified) void type, creates an
571221345Sdim  // rvalue of the specified type, which is value-initialized.
572221345Sdim  //
573221345Sdim  exprs.release();
574223017Sdim  return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
575223017Sdim}
576223017Sdim
577223017Sdim
578226633Sdim/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
579226633Sdim/// @code new (memory) int[size][4] @endcode
580226633Sdim/// or
581226633Sdim/// @code ::new Foo(23, "hello") @endcode
582226633Sdim/// For the interpretation of this heap of arguments, consult the base version.
583218885SdimAction::OwningExprResult
584218885SdimSema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
585218885Sdim                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
586218885Sdim                  SourceLocation PlacementRParen, bool ParenTypeId,
587224145Sdim                  Declarator &D, SourceLocation ConstructorLParen,
588234353Sdim                  MultiExprArg ConstructorArgs,
589218885Sdim                  SourceLocation ConstructorRParen) {
590218885Sdim  Expr *ArraySize = 0;
591218885Sdim  // If the specified type is an array, unwrap it and save the expression.
592223017Sdim  if (D.getNumTypeObjects() > 0 &&
593218885Sdim      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
594218885Sdim    DeclaratorChunk &Chunk = D.getTypeObject(0);
595218885Sdim    if (Chunk.Arr.hasStatic)
596288943Sdim      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
597218885Sdim        << D.getSourceRange());
598218885Sdim    if (!Chunk.Arr.NumElts)
599218885Sdim      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
600288943Sdim        << D.getSourceRange());
601218885Sdim
602218885Sdim    if (ParenTypeId) {
603221345Sdim      // Can't have dynamic array size when the type-id is in parentheses.
604239462Sdim      Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
605221345Sdim      if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
606221345Sdim          !NumElts->isIntegerConstantExpr(Context)) {
607221345Sdim        Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
608221345Sdim          << NumElts->getSourceRange();
609218885Sdim        return ExprError();
610296417Sdim      }
611218885Sdim    }
612218885Sdim
613218885Sdim    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
614218885Sdim    D.DropFirstTypeObject();
615221345Sdim  }
616218885Sdim
617218885Sdim  // Every dimension shall be of constant size.
618218885Sdim  if (ArraySize) {
619218885Sdim    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
620218885Sdim      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
621218885Sdim        break;
622218885Sdim
623218885Sdim      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
624218885Sdim      if (Expr *NumElts = (Expr *)Array.NumElts) {
625218885Sdim        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
626218885Sdim            !NumElts->isIntegerConstantExpr(Context)) {
627218885Sdim          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
628221345Sdim            << NumElts->getSourceRange();
629218885Sdim          return ExprError();
630218885Sdim        }
631218885Sdim      }
632261991Sdim    }
633261991Sdim  }
634261991Sdim
635261991Sdim  //FIXME: Store TypeSourceInfo in CXXNew expression.
636261991Sdim  TypeSourceInfo *TInfo = 0;
637261991Sdim  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
638261991Sdim  if (D.isInvalidType())
639261991Sdim    return ExprError();
640261991Sdim
641218885Sdim  return BuildCXXNew(StartLoc, UseGlobal,
642224145Sdim                     PlacementLParen,
643221345Sdim                     move(PlacementArgs),
644221345Sdim                     PlacementRParen,
645218885Sdim                     ParenTypeId,
646280031Sdim                     AllocType,
647280031Sdim                     D.getSourceRange().getBegin(),
648280031Sdim                     D.getSourceRange(),
649280031Sdim                     Owned(ArraySize),
650280031Sdim                     ConstructorLParen,
651280031Sdim                     move(ConstructorArgs),
652280031Sdim                     ConstructorRParen);
653280031Sdim}
654280031Sdim
655280031SdimSema::OwningExprResult
656280031SdimSema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
657280031Sdim                  SourceLocation PlacementLParen,
658224145Sdim                  MultiExprArg PlacementArgs,
659224145Sdim                  SourceLocation PlacementRParen,
660218885Sdim                  bool ParenTypeId,
661218885Sdim                  QualType AllocType,
662218885Sdim                  SourceLocation TypeLoc,
663218885Sdim                  SourceRange TypeRange,
664218885Sdim                  ExprArg ArraySizeE,
665224145Sdim                  SourceLocation ConstructorLParen,
666224145Sdim                  MultiExprArg ConstructorArgs,
667224145Sdim                  SourceLocation ConstructorRParen) {
668224145Sdim  if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
669224145Sdim    return ExprError();
670224145Sdim
671224145Sdim  QualType ResultType = Context.getPointerType(AllocType);
672224145Sdim
673224145Sdim  // That every array dimension except the first is constant was already
674224145Sdim  // checked by the type check above.
675218885Sdim
676218885Sdim  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
677239462Sdim  //   or enumeration type with a non-negative value."
678221345Sdim  Expr *ArraySize = (Expr *)ArraySizeE.get();
679218885Sdim  if (ArraySize && !ArraySize->isTypeDependent()) {
680218885Sdim    QualType SizeType = ArraySize->getType();
681280031Sdim    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
682280031Sdim      return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
683280031Sdim                            diag::err_array_size_not_integral)
684280031Sdim        << SizeType << ArraySize->getSourceRange());
685280031Sdim    // Let's see if this is a constant < 0. If so, we reject it out of hand.
686280031Sdim    // We don't care about special rules, so we tell the machinery it's not
687280031Sdim    // evaluated - it gives us a result in more cases.
688280031Sdim    if (!ArraySize->isValueDependent()) {
689218885Sdim      llvm::APSInt Value;
690288943Sdim      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
691288943Sdim        if (Value < llvm::APSInt(
692288943Sdim                        llvm::APInt::getNullValue(Value.getBitWidth()),
693288943Sdim                                 Value.isUnsigned()))
694288943Sdim          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
695288943Sdim                           diag::err_typecheck_negative_array_size)
696288943Sdim            << ArraySize->getSourceRange());
697288943Sdim      }
698288943Sdim    }
699288943Sdim
700288943Sdim    ImpCastExprToType(ArraySize, Context.getSizeType(),
701288943Sdim                      CastExpr::CK_IntegralCast);
702288943Sdim  }
703288943Sdim
704276479Sdim  FunctionDecl *OperatorNew = 0;
705276479Sdim  FunctionDecl *OperatorDelete = 0;
706276479Sdim  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
707276479Sdim  unsigned NumPlaceArgs = PlacementArgs.size();
708276479Sdim
709276479Sdim  if (!AllocType->isDependentType() &&
710276479Sdim      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
711288943Sdim      FindAllocationFunctions(StartLoc,
712276479Sdim                              SourceRange(PlacementLParen, PlacementRParen),
713261991Sdim                              UseGlobal, AllocType, ArraySize, PlaceArgs,
714261991Sdim                              NumPlaceArgs, OperatorNew, OperatorDelete))
715218885Sdim    return ExprError();
716276479Sdim  llvm::SmallVector<Expr *, 8> AllPlaceArgs;
717288943Sdim  if (OperatorNew) {
718288943Sdim    // Add default arguments, if any.
719218885Sdim    const FunctionProtoType *Proto =
720276479Sdim      OperatorNew->getType()->getAs<FunctionProtoType>();
721276479Sdim    VariadicCallType CallType =
722276479Sdim      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
723288943Sdim
724288943Sdim    if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
725276479Sdim                               Proto, 1, PlaceArgs, NumPlaceArgs,
726218885Sdim                               AllPlaceArgs, CallType))
727276479Sdim      return ExprError();
728288943Sdim
729288943Sdim    NumPlaceArgs = AllPlaceArgs.size();
730288943Sdim    if (NumPlaceArgs > 0)
731288943Sdim      PlaceArgs = &AllPlaceArgs[0];
732276479Sdim  }
733288943Sdim
734288943Sdim  bool Init = ConstructorLParen.isValid();
735218885Sdim  // --- Choosing a constructor ---
736218885Sdim  CXXConstructorDecl *Constructor = 0;
737288943Sdim  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
738249423Sdim  unsigned NumConsArgs = ConstructorArgs.size();
739276479Sdim  ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
740276479Sdim
741276479Sdim  // Array 'new' can't have any initializers.
742288943Sdim  if (NumConsArgs && ArraySize) {
743276479Sdim    SourceRange InitRange(ConsArgs[0]->getLocStart(),
744276479Sdim                          ConsArgs[NumConsArgs - 1]->getLocEnd());
745276479Sdim
746276479Sdim    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
747276479Sdim    return ExprError();
748288943Sdim  }
749288943Sdim
750218885Sdim  if (!AllocType->isDependentType() &&
751218885Sdim      !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
752288943Sdim    // C++0x [expr.new]p15:
753280031Sdim    //   A new-expression that creates an object of type T initializes that
754280031Sdim    //   object as follows:
755280031Sdim    InitializationKind Kind
756280031Sdim    //     - If the new-initializer is omitted, the object is default-
757280031Sdim    //       initialized (8.5); if no initialization is performed,
758280031Sdim    //       the object has indeterminate value
759280031Sdim      = !Init? InitializationKind::CreateDefault(TypeLoc)
760280031Sdim    //     - Otherwise, the new-initializer is interpreted according to the
761280031Sdim    //       initialization rules of 8.5 for direct-initialization.
762280031Sdim             : InitializationKind::CreateDirect(TypeLoc,
763280031Sdim                                                ConstructorLParen,
764280031Sdim                                                ConstructorRParen);
765288943Sdim
766280031Sdim    InitializedEntity Entity
767280031Sdim      = InitializedEntity::InitializeNew(StartLoc, AllocType);
768280031Sdim    InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
769280031Sdim    OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
770288943Sdim                                                move(ConstructorArgs));
771280031Sdim    if (FullInit.isInvalid())
772280031Sdim      return ExprError();
773280031Sdim
774288943Sdim    // FullInit is our initializer; walk through it to determine if it's a
775276479Sdim    // constructor call, which CXXNewExpr handles directly.
776276479Sdim    if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
777276479Sdim      if (CXXBindTemporaryExpr *Binder
778288943Sdim            = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
779288943Sdim        FullInitExpr = Binder->getSubExpr();
780276479Sdim      if (CXXConstructExpr *Construct
781249423Sdim                    = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
782288943Sdim        Constructor = Construct->getConstructor();
783288943Sdim        for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
784276479Sdim                                         AEnd = Construct->arg_end();
785276479Sdim             A != AEnd; ++A)
786288943Sdim          ConvertedConstructorArgs.push_back(A->Retain());
787288943Sdim      } else {
788276479Sdim        // Take the converted initializer.
789249423Sdim        ConvertedConstructorArgs.push_back(FullInit.release());
790288943Sdim      }
791288943Sdim    } else {
792276479Sdim      // No initialization required.
793276479Sdim    }
794276479Sdim
795276479Sdim    // Take the converted arguments and use them for the new expression.
796276479Sdim    NumConsArgs = ConvertedConstructorArgs.size();
797276479Sdim    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
798276479Sdim  }
799276479Sdim
800276479Sdim  // Mark the new and delete operators as referenced.
801276479Sdim  if (OperatorNew)
802276479Sdim    MarkDeclarationReferenced(StartLoc, OperatorNew);
803276479Sdim  if (OperatorDelete)
804276479Sdim    MarkDeclarationReferenced(StartLoc, OperatorDelete);
805288943Sdim
806288943Sdim  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
807288943Sdim
808276479Sdim  PlacementArgs.release();
809261991Sdim  ConstructorArgs.release();
810288943Sdim  ArraySizeE.release();
811288943Sdim  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
812276479Sdim                                        PlaceArgs, NumPlaceArgs, ParenTypeId,
813276479Sdim                                        ArraySize, Constructor, Init,
814276479Sdim                                        ConsArgs, NumConsArgs, OperatorDelete,
815288943Sdim                                        ResultType, StartLoc,
816288943Sdim                                        Init ? ConstructorRParen :
817288943Sdim                                               SourceLocation()));
818288943Sdim}
819276479Sdim
820261991Sdim/// CheckAllocatedType - Checks that a type is suitable as the allocated type
821288943Sdim/// in a new-expression.
822288943Sdim/// dimension off and stores the size expression in ArraySize.
823276479Sdimbool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
824276479Sdim                              SourceRange R) {
825276479Sdim  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
826276479Sdim  //   abstract class type or array thereof.
827276479Sdim  if (AllocType->isFunctionType())
828276479Sdim    return Diag(Loc, diag::err_bad_new_type)
829276479Sdim      << AllocType << 0 << R;
830288943Sdim  else if (AllocType->isReferenceType())
831288943Sdim    return Diag(Loc, diag::err_bad_new_type)
832276479Sdim      << AllocType << 1 << R;
833261991Sdim  else if (!AllocType->isDependentType() &&
834288943Sdim           RequireCompleteType(Loc, AllocType,
835288943Sdim                               PDiag(diag::err_new_incomplete_type)
836276479Sdim                                 << R))
837276479Sdim    return true;
838276479Sdim  else if (RequireNonAbstractType(Loc, AllocType,
839276479Sdim                                  diag::err_allocation_of_abstract_type))
840276479Sdim    return true;
841288943Sdim
842276479Sdim  return false;
843276479Sdim}
844288943Sdim
845276479Sdim/// \brief Determine whether the given function is a non-placement
846276479Sdim/// deallocation function.
847288943Sdimstatic bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
848288943Sdim  if (FD->isInvalidDecl())
849276479Sdim    return false;
850276479Sdim
851288943Sdim  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
852276479Sdim    return Method->isUsualDeallocationFunction();
853276479Sdim
854288943Sdim  return ((FD->getOverloadedOperator() == OO_Delete ||
855288943Sdim           FD->getOverloadedOperator() == OO_Array_Delete) &&
856276479Sdim          FD->getNumParams() == 1);
857276479Sdim}
858288943Sdim
859288943Sdim/// FindAllocationFunctions - Finds the overloads of operator new and delete
860276479Sdim/// that are appropriate for the allocation.
861276479Sdimbool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
862276479Sdim                                   bool UseGlobal, QualType AllocType,
863276479Sdim                                   bool IsArray, Expr **PlaceArgs,
864276479Sdim                                   unsigned NumPlaceArgs,
865261991Sdim                                   FunctionDecl *&OperatorNew,
866288943Sdim                                   FunctionDecl *&OperatorDelete) {
867288943Sdim  // --- Choosing an allocation function ---
868288943Sdim  // C++ 5.3.4p8 - 14 & 18
869276479Sdim  // 1) If UseGlobal is true, only look in the global scope. Else, also look
870276479Sdim  //   in the scope of the allocated class.
871276479Sdim  // 2) If an array size is given, look for operator new[], else look for
872276479Sdim  //   operator new.
873288943Sdim  // 3) The first argument is always size_t. Append the arguments from the
874276479Sdim  //   placement form.
875276479Sdim
876288943Sdim  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
877276479Sdim  // We don't care about the actual value of this argument.
878276479Sdim  // FIXME: Should the Sema create the expression and embed it in the syntax
879288943Sdim  // tree? Or should the consumer just recalculate the value?
880276479Sdim  IntegerLiteral Size(llvm::APInt::getNullValue(
881276479Sdim                      Context.Target.getPointerWidth(0)),
882288943Sdim                      Context.getSizeType(),
883288943Sdim                      SourceLocation());
884276479Sdim  AllocArgs[0] = &Size;
885276479Sdim  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
886276479Sdim
887276479Sdim  // C++ [expr.new]p8:
888276479Sdim  //   If the allocated type is a non-array type, the allocation
889261991Sdim  //   function���s name is operator new and the deallocation function���s
890276479Sdim  //   name is operator delete. If the allocated type is an array
891276479Sdim  //   type, the allocation function���s name is operator new[] and the
892288943Sdim  //   deallocation function���s name is operator delete[].
893276479Sdim  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
894288943Sdim                                        IsArray ? OO_Array_New : OO_New);
895288943Sdim  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
896288943Sdim                                        IsArray ? OO_Array_Delete : OO_Delete);
897288943Sdim
898288943Sdim  if (AllocType->isRecordType() && !UseGlobal) {
899288943Sdim    CXXRecordDecl *Record
900288943Sdim      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
901288943Sdim    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
902288943Sdim                          AllocArgs.size(), Record, /*AllowMissing=*/true,
903276479Sdim                          OperatorNew))
904276479Sdim      return true;
905276479Sdim  }
906288943Sdim  if (!OperatorNew) {
907276479Sdim    // Didn't find a member overload. Look for a global one.
908276479Sdim    DeclareGlobalNewDelete();
909276479Sdim    DeclContext *TUDecl = Context.getTranslationUnitDecl();
910276479Sdim    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
911276479Sdim                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
912276479Sdim                          OperatorNew))
913276479Sdim      return true;
914276479Sdim  }
915276479Sdim
916276479Sdim  // We don't need an operator delete if we're running under
917276479Sdim  // -fno-exceptions.
918276479Sdim  if (!getLangOptions().Exceptions) {
919276479Sdim    OperatorDelete = 0;
920276479Sdim    return false;
921276479Sdim  }
922276479Sdim
923276479Sdim  // FindAllocationOverload can change the passed in arguments, so we need to
924276479Sdim  // copy them back.
925276479Sdim  if (NumPlaceArgs > 0)
926276479Sdim    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
927276479Sdim
928276479Sdim  // C++ [expr.new]p19:
929276479Sdim  //
930276479Sdim  //   If the new-expression begins with a unary :: operator, the
931276479Sdim  //   deallocation function���s name is looked up in the global
932276479Sdim  //   scope. Otherwise, if the allocated type is a class type T or an
933276479Sdim  //   array thereof, the deallocation function���s name is looked up in
934276479Sdim  //   the scope of T. If this lookup fails to find the name, or if
935276479Sdim  //   the allocated type is not a class type or array thereof, the
936276479Sdim  //   deallocation function���s name is looked up in the global scope.
937276479Sdim  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
938276479Sdim  if (AllocType->isRecordType() && !UseGlobal) {
939276479Sdim    CXXRecordDecl *RD
940276479Sdim      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
941276479Sdim    LookupQualifiedName(FoundDelete, RD);
942276479Sdim  }
943276479Sdim  if (FoundDelete.isAmbiguous())
944276479Sdim    return true; // FIXME: clean up expressions?
945276479Sdim
946276479Sdim  if (FoundDelete.empty()) {
947276479Sdim    DeclareGlobalNewDelete();
948276479Sdim    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
949276479Sdim  }
950276479Sdim
951276479Sdim  FoundDelete.suppressDiagnostics();
952276479Sdim
953276479Sdim  llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
954288943Sdim
955288943Sdim  if (NumPlaceArgs > 0) {
956276479Sdim    // C++ [expr.new]p20:
957276479Sdim    //   A declaration of a placement deallocation function matches the
958276479Sdim    //   declaration of a placement allocation function if it has the
959288943Sdim    //   same number of parameters and, after parameter transformations
960276479Sdim    //   (8.3.5), all parameter types except the first are
961276479Sdim    //   identical. [...]
962276479Sdim    //
963288943Sdim    // To perform this comparison, we compute the function type that
964276479Sdim    // the deallocation function should have, and use that type both
965288943Sdim    // for template argument deduction and for comparison purposes.
966288943Sdim    QualType ExpectedFunctionType;
967276479Sdim    {
968276479Sdim      const FunctionProtoType *Proto
969276479Sdim        = OperatorNew->getType()->getAs<FunctionProtoType>();
970288943Sdim      llvm::SmallVector<QualType, 4> ArgTypes;
971276479Sdim      ArgTypes.push_back(Context.VoidPtrTy);
972276479Sdim      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
973276479Sdim        ArgTypes.push_back(Proto->getArgType(I));
974276479Sdim
975276479Sdim      ExpectedFunctionType
976276479Sdim        = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
977276479Sdim                                  ArgTypes.size(),
978276479Sdim                                  Proto->isVariadic(),
979276479Sdim                                  0, false, false, 0, 0,
980276479Sdim                                  FunctionType::ExtInfo());
981276479Sdim    }
982276479Sdim
983276479Sdim    for (LookupResult::iterator D = FoundDelete.begin(),
984288943Sdim                             DEnd = FoundDelete.end();
985288943Sdim         D != DEnd; ++D) {
986276479Sdim      FunctionDecl *Fn = 0;
987276479Sdim      if (FunctionTemplateDecl *FnTmpl
988288943Sdim            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
989288943Sdim        // Perform template argument deduction to try to match the
990288943Sdim        // expected function type.
991288943Sdim        TemplateDeductionInfo Info(Context, StartLoc);
992288943Sdim        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
993288943Sdim          continue;
994288943Sdim      } else
995276479Sdim        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
996276479Sdim
997276479Sdim      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
998276479Sdim        Matches.push_back(std::make_pair(D.getPair(), Fn));
999276479Sdim    }
1000276479Sdim  } else {
1001276479Sdim    // C++ [expr.new]p20:
1002276479Sdim    //   [...] Any non-placement deallocation function matches a
1003276479Sdim    //   non-placement allocation function. [...]
1004276479Sdim    for (LookupResult::iterator D = FoundDelete.begin(),
1005276479Sdim                             DEnd = FoundDelete.end();
1006276479Sdim         D != DEnd; ++D) {
1007276479Sdim      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1008276479Sdim        if (isNonPlacementDeallocationFunction(Fn))
1009276479Sdim          Matches.push_back(std::make_pair(D.getPair(), Fn));
1010276479Sdim    }
1011296417Sdim  }
1012276479Sdim
1013288943Sdim  // C++ [expr.new]p20:
1014276479Sdim  //   [...] If the lookup finds a single matching deallocation
1015276479Sdim  //   function, that function will be called; otherwise, no
1016276479Sdim  //   deallocation function will be called.
1017288943Sdim  if (Matches.size() == 1) {
1018276479Sdim    OperatorDelete = Matches[0].second;
1019276479Sdim
1020288943Sdim    // C++0x [expr.new]p20:
1021276479Sdim    //   If the lookup finds the two-parameter form of a usual
1022276479Sdim    //   deallocation function (3.7.4.2) and that function, considered
1023276479Sdim    //   as a placement deallocation function, would have been
1024276479Sdim    //   selected as a match for the allocation function, the program
1025276479Sdim    //   is ill-formed.
1026288943Sdim    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1027276479Sdim        isNonPlacementDeallocationFunction(OperatorDelete)) {
1028288943Sdim      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1029288943Sdim        << SourceRange(PlaceArgs[0]->getLocStart(),
1030288943Sdim                       PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1031288943Sdim      Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1032288943Sdim        << DeleteName;
1033288943Sdim    } else {
1034276479Sdim      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1035288943Sdim                            Matches[0].first);
1036261991Sdim    }
1037261991Sdim  }
1038261991Sdim
1039276479Sdim  return false;
1040276479Sdim}
1041276479Sdim
1042276479Sdim/// FindAllocationOverload - Find an fitting overload for the allocation
1043276479Sdim/// function in the specified scope.
1044276479Sdimbool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1045276479Sdim                                  DeclarationName Name, Expr** Args,
1046276479Sdim                                  unsigned NumArgs, DeclContext *Ctx,
1047276479Sdim                                  bool AllowMissing, FunctionDecl *&Operator) {
1048276479Sdim  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1049276479Sdim  LookupQualifiedName(R, Ctx);
1050276479Sdim  if (R.empty()) {
1051288943Sdim    if (AllowMissing)
1052249423Sdim      return false;
1053249423Sdim    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1054224145Sdim      << Name << Range;
1055224145Sdim  }
1056224145Sdim
1057224145Sdim  if (R.isAmbiguous())
1058224145Sdim    return true;
1059276479Sdim
1060276479Sdim  R.suppressDiagnostics();
1061276479Sdim
1062276479Sdim  OverloadCandidateSet Candidates(StartLoc);
1063276479Sdim  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1064276479Sdim       Alloc != AllocEnd; ++Alloc) {
1065276479Sdim    // Even member operator new/delete are implicitly treated as
1066276479Sdim    // static, so don't use AddMemberCandidate.
1067276479Sdim    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1068276479Sdim
1069276479Sdim    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1070276479Sdim      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1071276479Sdim                                   /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1072276479Sdim                                   Candidates,
1073276479Sdim                                   /*SuppressUserConversions=*/false);
1074276479Sdim      continue;
1075276479Sdim    }
1076276479Sdim
1077276479Sdim    FunctionDecl *Fn = cast<FunctionDecl>(D);
1078276479Sdim    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1079276479Sdim                         /*SuppressUserConversions=*/false);
1080276479Sdim  }
1081276479Sdim
1082276479Sdim  // Do the resolution.
1083276479Sdim  OverloadCandidateSet::iterator Best;
1084276479Sdim  switch(BestViableFunction(Candidates, StartLoc, Best)) {
1085276479Sdim  case OR_Success: {
1086276479Sdim    // Got one!
1087218885Sdim    FunctionDecl *FnDecl = Best->Function;
1088221345Sdim    // The first argument is size_t, and the first parameter must be size_t,
1089218885Sdim    // too. This is checked on declaration and can be assumed. (It can't be
1090218885Sdim    // asserted on, though, since invalid decls are left in there.)
1091226633Sdim    // Watch out for variadic allocator function.
1092226633Sdim    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1093218885Sdim    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1094      OwningExprResult Result
1095        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1096                                                       FnDecl->getParamDecl(i)),
1097                                    SourceLocation(),
1098                                    Owned(Args[i]->Retain()));
1099      if (Result.isInvalid())
1100        return true;
1101
1102      Args[i] = Result.takeAs<Expr>();
1103    }
1104    Operator = FnDecl;
1105    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1106    return false;
1107  }
1108
1109  case OR_No_Viable_Function:
1110    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1111      << Name << Range;
1112    PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
1113    return true;
1114
1115  case OR_Ambiguous:
1116    Diag(StartLoc, diag::err_ovl_ambiguous_call)
1117      << Name << Range;
1118    PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
1119    return true;
1120
1121  case OR_Deleted:
1122    Diag(StartLoc, diag::err_ovl_deleted_call)
1123      << Best->Function->isDeleted()
1124      << Name << Range;
1125    PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
1126    return true;
1127  }
1128  assert(false && "Unreachable, bad result from BestViableFunction");
1129  return true;
1130}
1131
1132
1133/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1134/// delete. These are:
1135/// @code
1136///   void* operator new(std::size_t) throw(std::bad_alloc);
1137///   void* operator new[](std::size_t) throw(std::bad_alloc);
1138///   void operator delete(void *) throw();
1139///   void operator delete[](void *) throw();
1140/// @endcode
1141/// Note that the placement and nothrow forms of new are *not* implicitly
1142/// declared. Their use requires including \<new\>.
1143void Sema::DeclareGlobalNewDelete() {
1144  if (GlobalNewDeleteDeclared)
1145    return;
1146
1147  // C++ [basic.std.dynamic]p2:
1148  //   [...] The following allocation and deallocation functions (18.4) are
1149  //   implicitly declared in global scope in each translation unit of a
1150  //   program
1151  //
1152  //     void* operator new(std::size_t) throw(std::bad_alloc);
1153  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1154  //     void  operator delete(void*) throw();
1155  //     void  operator delete[](void*) throw();
1156  //
1157  //   These implicit declarations introduce only the function names operator
1158  //   new, operator new[], operator delete, operator delete[].
1159  //
1160  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1161  // "std" or "bad_alloc" as necessary to form the exception specification.
1162  // However, we do not make these implicit declarations visible to name
1163  // lookup.
1164  if (!StdNamespace) {
1165    // The "std" namespace has not yet been defined, so build one implicitly.
1166    StdNamespace = NamespaceDecl::Create(Context,
1167                                         Context.getTranslationUnitDecl(),
1168                                         SourceLocation(),
1169                                         &PP.getIdentifierTable().get("std"));
1170    StdNamespace->setImplicit(true);
1171  }
1172
1173  if (!StdBadAlloc) {
1174    // The "std::bad_alloc" class has not yet been declared, so build it
1175    // implicitly.
1176    StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1177                                        StdNamespace,
1178                                        SourceLocation(),
1179                                      &PP.getIdentifierTable().get("bad_alloc"),
1180                                        SourceLocation(), 0);
1181    StdBadAlloc->setImplicit(true);
1182  }
1183
1184  GlobalNewDeleteDeclared = true;
1185
1186  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1187  QualType SizeT = Context.getSizeType();
1188  bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1189
1190  DeclareGlobalAllocationFunction(
1191      Context.DeclarationNames.getCXXOperatorName(OO_New),
1192      VoidPtr, SizeT, AssumeSaneOperatorNew);
1193  DeclareGlobalAllocationFunction(
1194      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1195      VoidPtr, SizeT, AssumeSaneOperatorNew);
1196  DeclareGlobalAllocationFunction(
1197      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1198      Context.VoidTy, VoidPtr);
1199  DeclareGlobalAllocationFunction(
1200      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1201      Context.VoidTy, VoidPtr);
1202}
1203
1204/// DeclareGlobalAllocationFunction - Declares a single implicit global
1205/// allocation function if it doesn't already exist.
1206void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1207                                           QualType Return, QualType Argument,
1208                                           bool AddMallocAttr) {
1209  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1210
1211  // Check if this function is already declared.
1212  {
1213    DeclContext::lookup_iterator Alloc, AllocEnd;
1214    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1215         Alloc != AllocEnd; ++Alloc) {
1216      // Only look at non-template functions, as it is the predefined,
1217      // non-templated allocation function we are trying to declare here.
1218      if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1219        QualType InitialParamType =
1220          Context.getCanonicalType(
1221            Func->getParamDecl(0)->getType().getUnqualifiedType());
1222        // FIXME: Do we need to check for default arguments here?
1223        if (Func->getNumParams() == 1 && InitialParamType == Argument)
1224          return;
1225      }
1226    }
1227  }
1228
1229  QualType BadAllocType;
1230  bool HasBadAllocExceptionSpec
1231    = (Name.getCXXOverloadedOperator() == OO_New ||
1232       Name.getCXXOverloadedOperator() == OO_Array_New);
1233  if (HasBadAllocExceptionSpec) {
1234    assert(StdBadAlloc && "Must have std::bad_alloc declared");
1235    BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1236  }
1237
1238  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1239                                            true, false,
1240                                            HasBadAllocExceptionSpec? 1 : 0,
1241                                            &BadAllocType,
1242                                            FunctionType::ExtInfo());
1243  FunctionDecl *Alloc =
1244    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
1245                         FnType, /*TInfo=*/0, FunctionDecl::None,
1246                         FunctionDecl::None, false, true);
1247  Alloc->setImplicit();
1248
1249  if (AddMallocAttr)
1250    Alloc->addAttr(::new (Context) MallocAttr());
1251
1252  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1253                                           0, Argument, /*TInfo=*/0,
1254                                           VarDecl::None,
1255                                           VarDecl::None, 0);
1256  Alloc->setParams(&Param, 1);
1257
1258  // FIXME: Also add this declaration to the IdentifierResolver, but
1259  // make sure it is at the end of the chain to coincide with the
1260  // global scope.
1261  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
1262}
1263
1264bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1265                                    DeclarationName Name,
1266                                    FunctionDecl* &Operator) {
1267  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1268  // Try to find operator delete/operator delete[] in class scope.
1269  LookupQualifiedName(Found, RD);
1270
1271  if (Found.isAmbiguous())
1272    return true;
1273
1274  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1275       F != FEnd; ++F) {
1276    if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1277      if (Delete->isUsualDeallocationFunction()) {
1278        Operator = Delete;
1279        return false;
1280      }
1281  }
1282
1283  // We did find operator delete/operator delete[] declarations, but
1284  // none of them were suitable.
1285  if (!Found.empty()) {
1286    Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1287      << Name << RD;
1288
1289    for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1290         F != FEnd; ++F) {
1291      Diag((*F)->getLocation(), diag::note_member_declared_here)
1292        << Name;
1293    }
1294
1295    return true;
1296  }
1297
1298  // Look for a global declaration.
1299  DeclareGlobalNewDelete();
1300  DeclContext *TUDecl = Context.getTranslationUnitDecl();
1301
1302  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1303  Expr* DeallocArgs[1];
1304  DeallocArgs[0] = &Null;
1305  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1306                             DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1307                             Operator))
1308    return true;
1309
1310  assert(Operator && "Did not find a deallocation function!");
1311  return false;
1312}
1313
1314/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1315/// @code ::delete ptr; @endcode
1316/// or
1317/// @code delete [] ptr; @endcode
1318Action::OwningExprResult
1319Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1320                     bool ArrayForm, ExprArg Operand) {
1321  // C++ [expr.delete]p1:
1322  //   The operand shall have a pointer type, or a class type having a single
1323  //   conversion function to a pointer type. The result has type void.
1324  //
1325  // DR599 amends "pointer type" to "pointer to object type" in both cases.
1326
1327  FunctionDecl *OperatorDelete = 0;
1328
1329  Expr *Ex = (Expr *)Operand.get();
1330  if (!Ex->isTypeDependent()) {
1331    QualType Type = Ex->getType();
1332
1333    if (const RecordType *Record = Type->getAs<RecordType>()) {
1334      llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1335
1336      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1337      const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1338      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1339             E = Conversions->end(); I != E; ++I) {
1340        NamedDecl *D = I.getDecl();
1341        if (isa<UsingShadowDecl>(D))
1342          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1343
1344        // Skip over templated conversion functions; they aren't considered.
1345        if (isa<FunctionTemplateDecl>(D))
1346          continue;
1347
1348        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1349
1350        QualType ConvType = Conv->getConversionType().getNonReferenceType();
1351        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1352          if (ConvPtrType->getPointeeType()->isObjectType())
1353            ObjectPtrConversions.push_back(Conv);
1354      }
1355      if (ObjectPtrConversions.size() == 1) {
1356        // We have a single conversion to a pointer-to-object type. Perform
1357        // that conversion.
1358        // TODO: don't redo the conversion calculation.
1359        Operand.release();
1360        if (!PerformImplicitConversion(Ex,
1361                            ObjectPtrConversions.front()->getConversionType(),
1362                                      AA_Converting)) {
1363          Operand = Owned(Ex);
1364          Type = Ex->getType();
1365        }
1366      }
1367      else if (ObjectPtrConversions.size() > 1) {
1368        Diag(StartLoc, diag::err_ambiguous_delete_operand)
1369              << Type << Ex->getSourceRange();
1370        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1371          NoteOverloadCandidate(ObjectPtrConversions[i]);
1372        return ExprError();
1373      }
1374    }
1375
1376    if (!Type->isPointerType())
1377      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1378        << Type << Ex->getSourceRange());
1379
1380    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1381    if (Pointee->isFunctionType() || Pointee->isVoidType())
1382      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1383        << Type << Ex->getSourceRange());
1384    else if (!Pointee->isDependentType() &&
1385             RequireCompleteType(StartLoc, Pointee,
1386                                 PDiag(diag::warn_delete_incomplete)
1387                                   << Ex->getSourceRange()))
1388      return ExprError();
1389
1390    // C++ [expr.delete]p2:
1391    //   [Note: a pointer to a const type can be the operand of a
1392    //   delete-expression; it is not necessary to cast away the constness
1393    //   (5.2.11) of the pointer expression before it is used as the operand
1394    //   of the delete-expression. ]
1395    ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1396                      CastExpr::CK_NoOp);
1397
1398    // Update the operand.
1399    Operand.take();
1400    Operand = ExprArg(*this, Ex);
1401
1402    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1403                                      ArrayForm ? OO_Array_Delete : OO_Delete);
1404
1405    if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1406      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1407
1408      if (!UseGlobal &&
1409          FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1410        return ExprError();
1411
1412      if (!RD->hasTrivialDestructor())
1413        if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
1414          MarkDeclarationReferenced(StartLoc,
1415                                    const_cast<CXXDestructorDecl*>(Dtor));
1416    }
1417
1418    if (!OperatorDelete) {
1419      // Look for a global declaration.
1420      DeclareGlobalNewDelete();
1421      DeclContext *TUDecl = Context.getTranslationUnitDecl();
1422      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1423                                 &Ex, 1, TUDecl, /*AllowMissing=*/false,
1424                                 OperatorDelete))
1425        return ExprError();
1426    }
1427
1428    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1429
1430    // FIXME: Check access and ambiguity of operator delete and destructor.
1431  }
1432
1433  Operand.release();
1434  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1435                                           OperatorDelete, Ex, StartLoc));
1436}
1437
1438/// \brief Check the use of the given variable as a C++ condition in an if,
1439/// while, do-while, or switch statement.
1440Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1441  QualType T = ConditionVar->getType();
1442
1443  // C++ [stmt.select]p2:
1444  //   The declarator shall not specify a function or an array.
1445  if (T->isFunctionType())
1446    return ExprError(Diag(ConditionVar->getLocation(),
1447                          diag::err_invalid_use_of_function_type)
1448                       << ConditionVar->getSourceRange());
1449  else if (T->isArrayType())
1450    return ExprError(Diag(ConditionVar->getLocation(),
1451                          diag::err_invalid_use_of_array_type)
1452                     << ConditionVar->getSourceRange());
1453
1454  return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1455                                   ConditionVar->getLocation(),
1456                                ConditionVar->getType().getNonReferenceType()));
1457}
1458
1459/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1460bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1461  // C++ 6.4p4:
1462  // The value of a condition that is an initialized declaration in a statement
1463  // other than a switch statement is the value of the declared variable
1464  // implicitly converted to type bool. If that conversion is ill-formed, the
1465  // program is ill-formed.
1466  // The value of a condition that is an expression is the value of the
1467  // expression, implicitly converted to bool.
1468  //
1469  return PerformContextuallyConvertToBool(CondExpr);
1470}
1471
1472/// Helper function to determine whether this is the (deprecated) C++
1473/// conversion from a string literal to a pointer to non-const char or
1474/// non-const wchar_t (for narrow and wide string literals,
1475/// respectively).
1476bool
1477Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1478  // Look inside the implicit cast, if it exists.
1479  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1480    From = Cast->getSubExpr();
1481
1482  // A string literal (2.13.4) that is not a wide string literal can
1483  // be converted to an rvalue of type "pointer to char"; a wide
1484  // string literal can be converted to an rvalue of type "pointer
1485  // to wchar_t" (C++ 4.2p2).
1486  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
1487    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1488      if (const BuiltinType *ToPointeeType
1489          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1490        // This conversion is considered only when there is an
1491        // explicit appropriate pointer target type (C++ 4.2p2).
1492        if (!ToPtrType->getPointeeType().hasQualifiers() &&
1493            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1494             (!StrLit->isWide() &&
1495              (ToPointeeType->getKind() == BuiltinType::Char_U ||
1496               ToPointeeType->getKind() == BuiltinType::Char_S))))
1497          return true;
1498      }
1499
1500  return false;
1501}
1502
1503static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1504                                                   SourceLocation CastLoc,
1505                                                   QualType Ty,
1506                                                   CastExpr::CastKind Kind,
1507                                                   CXXMethodDecl *Method,
1508                                                   Sema::ExprArg Arg) {
1509  Expr *From = Arg.takeAs<Expr>();
1510
1511  switch (Kind) {
1512  default: assert(0 && "Unhandled cast kind!");
1513  case CastExpr::CK_ConstructorConversion: {
1514    ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1515
1516    if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1517                                  Sema::MultiExprArg(S, (void **)&From, 1),
1518                                  CastLoc, ConstructorArgs))
1519      return S.ExprError();
1520
1521    Sema::OwningExprResult Result =
1522    S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1523                            move_arg(ConstructorArgs));
1524    if (Result.isInvalid())
1525      return S.ExprError();
1526
1527    return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1528  }
1529
1530  case CastExpr::CK_UserDefinedConversion: {
1531    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1532
1533    // Create an implicit call expr that calls it.
1534    // FIXME: pass the FoundDecl for the user-defined conversion here
1535    CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1536    return S.MaybeBindToTemporary(CE);
1537  }
1538  }
1539}
1540
1541/// PerformImplicitConversion - Perform an implicit conversion of the
1542/// expression From to the type ToType using the pre-computed implicit
1543/// conversion sequence ICS. Returns true if there was an error, false
1544/// otherwise. The expression From is replaced with the converted
1545/// expression. Action is the kind of conversion we're performing,
1546/// used in the error message.
1547bool
1548Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1549                                const ImplicitConversionSequence &ICS,
1550                                AssignmentAction Action, bool IgnoreBaseAccess) {
1551  switch (ICS.getKind()) {
1552  case ImplicitConversionSequence::StandardConversion:
1553    if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
1554                                  IgnoreBaseAccess))
1555      return true;
1556    break;
1557
1558  case ImplicitConversionSequence::UserDefinedConversion: {
1559
1560      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1561      CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
1562      QualType BeforeToType;
1563      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1564        CastKind = CastExpr::CK_UserDefinedConversion;
1565
1566        // If the user-defined conversion is specified by a conversion function,
1567        // the initial standard conversion sequence converts the source type to
1568        // the implicit object parameter of the conversion function.
1569        BeforeToType = Context.getTagDeclType(Conv->getParent());
1570      } else if (const CXXConstructorDecl *Ctor =
1571                  dyn_cast<CXXConstructorDecl>(FD)) {
1572        CastKind = CastExpr::CK_ConstructorConversion;
1573        // Do no conversion if dealing with ... for the first conversion.
1574        if (!ICS.UserDefined.EllipsisConversion) {
1575          // If the user-defined conversion is specified by a constructor, the
1576          // initial standard conversion sequence converts the source type to the
1577          // type required by the argument of the constructor
1578          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1579        }
1580      }
1581      else
1582        assert(0 && "Unknown conversion function kind!");
1583      // Whatch out for elipsis conversion.
1584      if (!ICS.UserDefined.EllipsisConversion) {
1585        if (PerformImplicitConversion(From, BeforeToType,
1586                                      ICS.UserDefined.Before, AA_Converting,
1587                                      IgnoreBaseAccess))
1588          return true;
1589      }
1590
1591      OwningExprResult CastArg
1592        = BuildCXXCastArgument(*this,
1593                               From->getLocStart(),
1594                               ToType.getNonReferenceType(),
1595                               CastKind, cast<CXXMethodDecl>(FD),
1596                               Owned(From));
1597
1598      if (CastArg.isInvalid())
1599        return true;
1600
1601      From = CastArg.takeAs<Expr>();
1602
1603      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1604                                       AA_Converting, IgnoreBaseAccess);
1605  }
1606
1607  case ImplicitConversionSequence::AmbiguousConversion:
1608    DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1609                          PDiag(diag::err_typecheck_ambiguous_condition)
1610                            << From->getSourceRange());
1611     return true;
1612
1613  case ImplicitConversionSequence::EllipsisConversion:
1614    assert(false && "Cannot perform an ellipsis conversion");
1615    return false;
1616
1617  case ImplicitConversionSequence::BadConversion:
1618    return true;
1619  }
1620
1621  // Everything went well.
1622  return false;
1623}
1624
1625/// PerformImplicitConversion - Perform an implicit conversion of the
1626/// expression From to the type ToType by following the standard
1627/// conversion sequence SCS. Returns true if there was an error, false
1628/// otherwise. The expression From is replaced with the converted
1629/// expression. Flavor is the context in which we're performing this
1630/// conversion, for use in error messages.
1631bool
1632Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1633                                const StandardConversionSequence& SCS,
1634                                AssignmentAction Action, bool IgnoreBaseAccess) {
1635  // Overall FIXME: we are recomputing too many types here and doing far too
1636  // much extra work. What this means is that we need to keep track of more
1637  // information that is computed when we try the implicit conversion initially,
1638  // so that we don't need to recompute anything here.
1639  QualType FromType = From->getType();
1640
1641  if (SCS.CopyConstructor) {
1642    // FIXME: When can ToType be a reference type?
1643    assert(!ToType->isReferenceType());
1644    if (SCS.Second == ICK_Derived_To_Base) {
1645      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1646      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1647                                  MultiExprArg(*this, (void **)&From, 1),
1648                                  /*FIXME:ConstructLoc*/SourceLocation(),
1649                                  ConstructorArgs))
1650        return true;
1651      OwningExprResult FromResult =
1652        BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1653                              ToType, SCS.CopyConstructor,
1654                              move_arg(ConstructorArgs));
1655      if (FromResult.isInvalid())
1656        return true;
1657      From = FromResult.takeAs<Expr>();
1658      return false;
1659    }
1660    OwningExprResult FromResult =
1661      BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1662                            ToType, SCS.CopyConstructor,
1663                            MultiExprArg(*this, (void**)&From, 1));
1664
1665    if (FromResult.isInvalid())
1666      return true;
1667
1668    From = FromResult.takeAs<Expr>();
1669    return false;
1670  }
1671
1672  // Resolve overloaded function references.
1673  if (Context.hasSameType(FromType, Context.OverloadTy)) {
1674    DeclAccessPair Found;
1675    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1676                                                          true, Found);
1677    if (!Fn)
1678      return true;
1679
1680    if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1681      return true;
1682
1683    From = FixOverloadedFunctionReference(From, Found, Fn);
1684    FromType = From->getType();
1685  }
1686
1687  // Perform the first implicit conversion.
1688  switch (SCS.First) {
1689  case ICK_Identity:
1690  case ICK_Lvalue_To_Rvalue:
1691    // Nothing to do.
1692    break;
1693
1694  case ICK_Array_To_Pointer:
1695    FromType = Context.getArrayDecayedType(FromType);
1696    ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
1697    break;
1698
1699  case ICK_Function_To_Pointer:
1700    FromType = Context.getPointerType(FromType);
1701    ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
1702    break;
1703
1704  default:
1705    assert(false && "Improper first standard conversion");
1706    break;
1707  }
1708
1709  // Perform the second implicit conversion
1710  switch (SCS.Second) {
1711  case ICK_Identity:
1712    // If both sides are functions (or pointers/references to them), there could
1713    // be incompatible exception declarations.
1714    if (CheckExceptionSpecCompatibility(From, ToType))
1715      return true;
1716    // Nothing else to do.
1717    break;
1718
1719  case ICK_NoReturn_Adjustment:
1720    // If both sides are functions (or pointers/references to them), there could
1721    // be incompatible exception declarations.
1722    if (CheckExceptionSpecCompatibility(From, ToType))
1723      return true;
1724
1725    ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1726                      CastExpr::CK_NoOp);
1727    break;
1728
1729  case ICK_Integral_Promotion:
1730  case ICK_Integral_Conversion:
1731    ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1732    break;
1733
1734  case ICK_Floating_Promotion:
1735  case ICK_Floating_Conversion:
1736    ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1737    break;
1738
1739  case ICK_Complex_Promotion:
1740  case ICK_Complex_Conversion:
1741    ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1742    break;
1743
1744  case ICK_Floating_Integral:
1745    if (ToType->isFloatingType())
1746      ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1747    else
1748      ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1749    break;
1750
1751  case ICK_Complex_Real:
1752    ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1753    break;
1754
1755  case ICK_Compatible_Conversion:
1756    ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
1757    break;
1758
1759  case ICK_Pointer_Conversion: {
1760    if (SCS.IncompatibleObjC) {
1761      // Diagnose incompatible Objective-C conversions
1762      Diag(From->getSourceRange().getBegin(),
1763           diag::ext_typecheck_convert_incompatible_pointer)
1764        << From->getType() << ToType << Action
1765        << From->getSourceRange();
1766    }
1767
1768
1769    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1770    CXXBaseSpecifierArray BasePath;
1771    if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
1772      return true;
1773    ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
1774    break;
1775  }
1776
1777  case ICK_Pointer_Member: {
1778    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1779    CXXBaseSpecifierArray BasePath;
1780    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1781                                     IgnoreBaseAccess))
1782      return true;
1783    if (CheckExceptionSpecCompatibility(From, ToType))
1784      return true;
1785    ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
1786    break;
1787  }
1788  case ICK_Boolean_Conversion: {
1789    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1790    if (FromType->isMemberPointerType())
1791      Kind = CastExpr::CK_MemberPointerToBoolean;
1792
1793    ImpCastExprToType(From, Context.BoolTy, Kind);
1794    break;
1795  }
1796
1797  case ICK_Derived_To_Base:
1798    if (CheckDerivedToBaseConversion(From->getType(),
1799                                     ToType.getNonReferenceType(),
1800                                     From->getLocStart(),
1801                                     From->getSourceRange(), 0,
1802                                     IgnoreBaseAccess))
1803      return true;
1804    ImpCastExprToType(From, ToType.getNonReferenceType(),
1805                      CastExpr::CK_DerivedToBase);
1806    break;
1807
1808  default:
1809    assert(false && "Improper second standard conversion");
1810    break;
1811  }
1812
1813  switch (SCS.Third) {
1814  case ICK_Identity:
1815    // Nothing to do.
1816    break;
1817
1818  case ICK_Qualification:
1819    // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1820    // references.
1821    ImpCastExprToType(From, ToType.getNonReferenceType(),
1822                      CastExpr::CK_NoOp, ToType->isLValueReferenceType());
1823
1824    if (SCS.DeprecatedStringLiteralToCharPtr)
1825      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1826        << ToType.getNonReferenceType();
1827
1828    break;
1829
1830  default:
1831    assert(false && "Improper second standard conversion");
1832    break;
1833  }
1834
1835  return false;
1836}
1837
1838Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1839                                                 SourceLocation KWLoc,
1840                                                 SourceLocation LParen,
1841                                                 TypeTy *Ty,
1842                                                 SourceLocation RParen) {
1843  QualType T = GetTypeFromParser(Ty);
1844
1845  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1846  // all traits except __is_class, __is_enum and __is_union require a the type
1847  // to be complete.
1848  if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1849    if (RequireCompleteType(KWLoc, T,
1850                            diag::err_incomplete_type_used_in_type_trait_expr))
1851      return ExprError();
1852  }
1853
1854  // There is no point in eagerly computing the value. The traits are designed
1855  // to be used from type trait templates, so Ty will be a template parameter
1856  // 99% of the time.
1857  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1858                                                RParen, Context.BoolTy));
1859}
1860
1861QualType Sema::CheckPointerToMemberOperands(
1862  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
1863  const char *OpSpelling = isIndirect ? "->*" : ".*";
1864  // C++ 5.5p2
1865  //   The binary operator .* [p3: ->*] binds its second operand, which shall
1866  //   be of type "pointer to member of T" (where T is a completely-defined
1867  //   class type) [...]
1868  QualType RType = rex->getType();
1869  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1870  if (!MemPtr) {
1871    Diag(Loc, diag::err_bad_memptr_rhs)
1872      << OpSpelling << RType << rex->getSourceRange();
1873    return QualType();
1874  }
1875
1876  QualType Class(MemPtr->getClass(), 0);
1877
1878  if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1879    return QualType();
1880
1881  // C++ 5.5p2
1882  //   [...] to its first operand, which shall be of class T or of a class of
1883  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1884  //   such a class]
1885  QualType LType = lex->getType();
1886  if (isIndirect) {
1887    if (const PointerType *Ptr = LType->getAs<PointerType>())
1888      LType = Ptr->getPointeeType().getNonReferenceType();
1889    else {
1890      Diag(Loc, diag::err_bad_memptr_lhs)
1891        << OpSpelling << 1 << LType
1892        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
1893      return QualType();
1894    }
1895  }
1896
1897  if (!Context.hasSameUnqualifiedType(Class, LType)) {
1898    // If we want to check the hierarchy, we need a complete type.
1899    if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1900        << OpSpelling << (int)isIndirect)) {
1901      return QualType();
1902    }
1903    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1904                       /*DetectVirtual=*/false);
1905    // FIXME: Would it be useful to print full ambiguity paths, or is that
1906    // overkill?
1907    if (!IsDerivedFrom(LType, Class, Paths) ||
1908        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1909      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1910        << (int)isIndirect << lex->getType();
1911      return QualType();
1912    }
1913    // Cast LHS to type of use.
1914    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1915    bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1916
1917    CXXBaseSpecifierArray BasePath;
1918    BuildBasePathArray(Paths, BasePath);
1919    ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1920                      BasePath);
1921  }
1922
1923  if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
1924    // Diagnose use of pointer-to-member type which when used as
1925    // the functional cast in a pointer-to-member expression.
1926    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1927     return QualType();
1928  }
1929  // C++ 5.5p2
1930  //   The result is an object or a function of the type specified by the
1931  //   second operand.
1932  // The cv qualifiers are the union of those in the pointer and the left side,
1933  // in accordance with 5.5p5 and 5.2.5.
1934  // FIXME: This returns a dereferenced member function pointer as a normal
1935  // function type. However, the only operation valid on such functions is
1936  // calling them. There's also a GCC extension to get a function pointer to the
1937  // thing, which is another complication, because this type - unlike the type
1938  // that is the result of this expression - takes the class as the first
1939  // argument.
1940  // We probably need a "MemberFunctionClosureType" or something like that.
1941  QualType Result = MemPtr->getPointeeType();
1942  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
1943  return Result;
1944}
1945
1946/// \brief Try to convert a type to another according to C++0x 5.16p3.
1947///
1948/// This is part of the parameter validation for the ? operator. If either
1949/// value operand is a class type, the two operands are attempted to be
1950/// converted to each other. This function does the conversion in one direction.
1951/// It returns true if the program is ill-formed and has already been diagnosed
1952/// as such.
1953static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1954                                SourceLocation QuestionLoc,
1955                                bool &HaveConversion,
1956                                QualType &ToType) {
1957  HaveConversion = false;
1958  ToType = To->getType();
1959
1960  InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1961                                                           SourceLocation());
1962  // C++0x 5.16p3
1963  //   The process for determining whether an operand expression E1 of type T1
1964  //   can be converted to match an operand expression E2 of type T2 is defined
1965  //   as follows:
1966  //   -- If E2 is an lvalue:
1967  bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1968  if (ToIsLvalue) {
1969    //   E1 can be converted to match E2 if E1 can be implicitly converted to
1970    //   type "lvalue reference to T2", subject to the constraint that in the
1971    //   conversion the reference must bind directly to E1.
1972    QualType T = Self.Context.getLValueReferenceType(ToType);
1973    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
1974
1975    InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1976    if (InitSeq.isDirectReferenceBinding()) {
1977      ToType = T;
1978      HaveConversion = true;
1979      return false;
1980    }
1981
1982    if (InitSeq.isAmbiguous())
1983      return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1984  }
1985
1986  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1987  //      -- if E1 and E2 have class type, and the underlying class types are
1988  //         the same or one is a base class of the other:
1989  QualType FTy = From->getType();
1990  QualType TTy = To->getType();
1991  const RecordType *FRec = FTy->getAs<RecordType>();
1992  const RecordType *TRec = TTy->getAs<RecordType>();
1993  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
1994                       Self.IsDerivedFrom(FTy, TTy);
1995  if (FRec && TRec &&
1996      (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1997    //         E1 can be converted to match E2 if the class of T2 is the
1998    //         same type as, or a base class of, the class of T1, and
1999    //         [cv2 > cv1].
2000    if (FRec == TRec || FDerivedFromT) {
2001      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
2002        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2003        InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2004        if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2005          HaveConversion = true;
2006          return false;
2007        }
2008
2009        if (InitSeq.isAmbiguous())
2010          return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2011      }
2012    }
2013
2014    return false;
2015  }
2016
2017  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
2018  //        implicitly converted to the type that expression E2 would have
2019  //        if E2 were converted to an rvalue (or the type it has, if E2 is
2020  //        an rvalue).
2021  //
2022  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2023  // to the array-to-pointer or function-to-pointer conversions.
2024  if (!TTy->getAs<TagType>())
2025    TTy = TTy.getUnqualifiedType();
2026
2027  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2028  InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2029  HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2030  ToType = TTy;
2031  if (InitSeq.isAmbiguous())
2032    return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2033
2034  return false;
2035}
2036
2037/// \brief Try to find a common type for two according to C++0x 5.16p5.
2038///
2039/// This is part of the parameter validation for the ? operator. If either
2040/// value operand is a class type, overload resolution is used to find a
2041/// conversion to a common type.
2042static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2043                                    SourceLocation Loc) {
2044  Expr *Args[2] = { LHS, RHS };
2045  OverloadCandidateSet CandidateSet(Loc);
2046  Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
2047
2048  OverloadCandidateSet::iterator Best;
2049  switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
2050    case OR_Success:
2051      // We found a match. Perform the conversions on the arguments and move on.
2052      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
2053                                         Best->Conversions[0], Sema::AA_Converting) ||
2054          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
2055                                         Best->Conversions[1], Sema::AA_Converting))
2056        break;
2057      return false;
2058
2059    case OR_No_Viable_Function:
2060      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2061        << LHS->getType() << RHS->getType()
2062        << LHS->getSourceRange() << RHS->getSourceRange();
2063      return true;
2064
2065    case OR_Ambiguous:
2066      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2067        << LHS->getType() << RHS->getType()
2068        << LHS->getSourceRange() << RHS->getSourceRange();
2069      // FIXME: Print the possible common types by printing the return types of
2070      // the viable candidates.
2071      break;
2072
2073    case OR_Deleted:
2074      assert(false && "Conditional operator has only built-in overloads");
2075      break;
2076  }
2077  return true;
2078}
2079
2080/// \brief Perform an "extended" implicit conversion as returned by
2081/// TryClassUnification.
2082static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2083  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2084  InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2085                                                           SourceLocation());
2086  InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2087  Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2088                                    Sema::MultiExprArg(Self, (void **)&E, 1));
2089  if (Result.isInvalid())
2090    return true;
2091
2092  E = Result.takeAs<Expr>();
2093  return false;
2094}
2095
2096/// \brief Check the operands of ?: under C++ semantics.
2097///
2098/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2099/// extension. In this case, LHS == Cond. (But they're not aliases.)
2100QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2101                                           SourceLocation QuestionLoc) {
2102  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2103  // interface pointers.
2104
2105  // C++0x 5.16p1
2106  //   The first expression is contextually converted to bool.
2107  if (!Cond->isTypeDependent()) {
2108    if (CheckCXXBooleanCondition(Cond))
2109      return QualType();
2110  }
2111
2112  // Either of the arguments dependent?
2113  if (LHS->isTypeDependent() || RHS->isTypeDependent())
2114    return Context.DependentTy;
2115
2116  CheckSignCompare(LHS, RHS, QuestionLoc);
2117
2118  // C++0x 5.16p2
2119  //   If either the second or the third operand has type (cv) void, ...
2120  QualType LTy = LHS->getType();
2121  QualType RTy = RHS->getType();
2122  bool LVoid = LTy->isVoidType();
2123  bool RVoid = RTy->isVoidType();
2124  if (LVoid || RVoid) {
2125    //   ... then the [l2r] conversions are performed on the second and third
2126    //   operands ...
2127    DefaultFunctionArrayLvalueConversion(LHS);
2128    DefaultFunctionArrayLvalueConversion(RHS);
2129    LTy = LHS->getType();
2130    RTy = RHS->getType();
2131
2132    //   ... and one of the following shall hold:
2133    //   -- The second or the third operand (but not both) is a throw-
2134    //      expression; the result is of the type of the other and is an rvalue.
2135    bool LThrow = isa<CXXThrowExpr>(LHS);
2136    bool RThrow = isa<CXXThrowExpr>(RHS);
2137    if (LThrow && !RThrow)
2138      return RTy;
2139    if (RThrow && !LThrow)
2140      return LTy;
2141
2142    //   -- Both the second and third operands have type void; the result is of
2143    //      type void and is an rvalue.
2144    if (LVoid && RVoid)
2145      return Context.VoidTy;
2146
2147    // Neither holds, error.
2148    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2149      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2150      << LHS->getSourceRange() << RHS->getSourceRange();
2151    return QualType();
2152  }
2153
2154  // Neither is void.
2155
2156  // C++0x 5.16p3
2157  //   Otherwise, if the second and third operand have different types, and
2158  //   either has (cv) class type, and attempt is made to convert each of those
2159  //   operands to the other.
2160  if (!Context.hasSameType(LTy, RTy) &&
2161      (LTy->isRecordType() || RTy->isRecordType())) {
2162    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2163    // These return true if a single direction is already ambiguous.
2164    QualType L2RType, R2LType;
2165    bool HaveL2R, HaveR2L;
2166    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
2167      return QualType();
2168    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
2169      return QualType();
2170
2171    //   If both can be converted, [...] the program is ill-formed.
2172    if (HaveL2R && HaveR2L) {
2173      Diag(QuestionLoc, diag::err_conditional_ambiguous)
2174        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2175      return QualType();
2176    }
2177
2178    //   If exactly one conversion is possible, that conversion is applied to
2179    //   the chosen operand and the converted operands are used in place of the
2180    //   original operands for the remainder of this section.
2181    if (HaveL2R) {
2182      if (ConvertForConditional(*this, LHS, L2RType))
2183        return QualType();
2184      LTy = LHS->getType();
2185    } else if (HaveR2L) {
2186      if (ConvertForConditional(*this, RHS, R2LType))
2187        return QualType();
2188      RTy = RHS->getType();
2189    }
2190  }
2191
2192  // C++0x 5.16p4
2193  //   If the second and third operands are lvalues and have the same type,
2194  //   the result is of that type [...]
2195  bool Same = Context.hasSameType(LTy, RTy);
2196  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2197      RHS->isLvalue(Context) == Expr::LV_Valid)
2198    return LTy;
2199
2200  // C++0x 5.16p5
2201  //   Otherwise, the result is an rvalue. If the second and third operands
2202  //   do not have the same type, and either has (cv) class type, ...
2203  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2204    //   ... overload resolution is used to determine the conversions (if any)
2205    //   to be applied to the operands. If the overload resolution fails, the
2206    //   program is ill-formed.
2207    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2208      return QualType();
2209  }
2210
2211  // C++0x 5.16p6
2212  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2213  //   conversions are performed on the second and third operands.
2214  DefaultFunctionArrayLvalueConversion(LHS);
2215  DefaultFunctionArrayLvalueConversion(RHS);
2216  LTy = LHS->getType();
2217  RTy = RHS->getType();
2218
2219  //   After those conversions, one of the following shall hold:
2220  //   -- The second and third operands have the same type; the result
2221  //      is of that type.
2222  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2223    return LTy;
2224
2225  //   -- The second and third operands have arithmetic or enumeration type;
2226  //      the usual arithmetic conversions are performed to bring them to a
2227  //      common type, and the result is of that type.
2228  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2229    UsualArithmeticConversions(LHS, RHS);
2230    return LHS->getType();
2231  }
2232
2233  //   -- The second and third operands have pointer type, or one has pointer
2234  //      type and the other is a null pointer constant; pointer conversions
2235  //      and qualification conversions are performed to bring them to their
2236  //      composite pointer type. The result is of the composite pointer type.
2237  //   -- The second and third operands have pointer to member type, or one has
2238  //      pointer to member type and the other is a null pointer constant;
2239  //      pointer to member conversions and qualification conversions are
2240  //      performed to bring them to a common type, whose cv-qualification
2241  //      shall match the cv-qualification of either the second or the third
2242  //      operand. The result is of the common type.
2243  bool NonStandardCompositeType = false;
2244  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
2245                              isSFINAEContext()? 0 : &NonStandardCompositeType);
2246  if (!Composite.isNull()) {
2247    if (NonStandardCompositeType)
2248      Diag(QuestionLoc,
2249           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2250        << LTy << RTy << Composite
2251        << LHS->getSourceRange() << RHS->getSourceRange();
2252
2253    return Composite;
2254  }
2255
2256  // Similarly, attempt to find composite type of two objective-c pointers.
2257  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2258  if (!Composite.isNull())
2259    return Composite;
2260
2261  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2262    << LHS->getType() << RHS->getType()
2263    << LHS->getSourceRange() << RHS->getSourceRange();
2264  return QualType();
2265}
2266
2267/// \brief Find a merged pointer type and convert the two expressions to it.
2268///
2269/// This finds the composite pointer type (or member pointer type) for @p E1
2270/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2271/// type and returns it.
2272/// It does not emit diagnostics.
2273///
2274/// \param Loc The location of the operator requiring these two expressions to
2275/// be converted to the composite pointer type.
2276///
2277/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2278/// a non-standard (but still sane) composite type to which both expressions
2279/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2280/// will be set true.
2281QualType Sema::FindCompositePointerType(SourceLocation Loc,
2282                                        Expr *&E1, Expr *&E2,
2283                                        bool *NonStandardCompositeType) {
2284  if (NonStandardCompositeType)
2285    *NonStandardCompositeType = false;
2286
2287  assert(getLangOptions().CPlusPlus && "This function assumes C++");
2288  QualType T1 = E1->getType(), T2 = E2->getType();
2289
2290  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2291      !T2->isAnyPointerType() && !T2->isMemberPointerType())
2292   return QualType();
2293
2294  // C++0x 5.9p2
2295  //   Pointer conversions and qualification conversions are performed on
2296  //   pointer operands to bring them to their composite pointer type. If
2297  //   one operand is a null pointer constant, the composite pointer type is
2298  //   the type of the other operand.
2299  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2300    if (T2->isMemberPointerType())
2301      ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2302    else
2303      ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
2304    return T2;
2305  }
2306  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
2307    if (T1->isMemberPointerType())
2308      ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2309    else
2310      ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
2311    return T1;
2312  }
2313
2314  // Now both have to be pointers or member pointers.
2315  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2316      (!T2->isPointerType() && !T2->isMemberPointerType()))
2317    return QualType();
2318
2319  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
2320  //   the other has type "pointer to cv2 T" and the composite pointer type is
2321  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2322  //   Otherwise, the composite pointer type is a pointer type similar to the
2323  //   type of one of the operands, with a cv-qualification signature that is
2324  //   the union of the cv-qualification signatures of the operand types.
2325  // In practice, the first part here is redundant; it's subsumed by the second.
2326  // What we do here is, we build the two possible composite types, and try the
2327  // conversions in both directions. If only one works, or if the two composite
2328  // types are the same, we have succeeded.
2329  // FIXME: extended qualifiers?
2330  typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2331  QualifierVector QualifierUnion;
2332  typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2333      ContainingClassVector;
2334  ContainingClassVector MemberOfClass;
2335  QualType Composite1 = Context.getCanonicalType(T1),
2336           Composite2 = Context.getCanonicalType(T2);
2337  unsigned NeedConstBefore = 0;
2338  do {
2339    const PointerType *Ptr1, *Ptr2;
2340    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2341        (Ptr2 = Composite2->getAs<PointerType>())) {
2342      Composite1 = Ptr1->getPointeeType();
2343      Composite2 = Ptr2->getPointeeType();
2344
2345      // If we're allowed to create a non-standard composite type, keep track
2346      // of where we need to fill in additional 'const' qualifiers.
2347      if (NonStandardCompositeType &&
2348          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2349        NeedConstBefore = QualifierUnion.size();
2350
2351      QualifierUnion.push_back(
2352                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2353      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2354      continue;
2355    }
2356
2357    const MemberPointerType *MemPtr1, *MemPtr2;
2358    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2359        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2360      Composite1 = MemPtr1->getPointeeType();
2361      Composite2 = MemPtr2->getPointeeType();
2362
2363      // If we're allowed to create a non-standard composite type, keep track
2364      // of where we need to fill in additional 'const' qualifiers.
2365      if (NonStandardCompositeType &&
2366          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2367        NeedConstBefore = QualifierUnion.size();
2368
2369      QualifierUnion.push_back(
2370                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2371      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2372                                             MemPtr2->getClass()));
2373      continue;
2374    }
2375
2376    // FIXME: block pointer types?
2377
2378    // Cannot unwrap any more types.
2379    break;
2380  } while (true);
2381
2382  if (NeedConstBefore && NonStandardCompositeType) {
2383    // Extension: Add 'const' to qualifiers that come before the first qualifier
2384    // mismatch, so that our (non-standard!) composite type meets the
2385    // requirements of C++ [conv.qual]p4 bullet 3.
2386    for (unsigned I = 0; I != NeedConstBefore; ++I) {
2387      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2388        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2389        *NonStandardCompositeType = true;
2390      }
2391    }
2392  }
2393
2394  // Rewrap the composites as pointers or member pointers with the union CVRs.
2395  ContainingClassVector::reverse_iterator MOC
2396    = MemberOfClass.rbegin();
2397  for (QualifierVector::reverse_iterator
2398         I = QualifierUnion.rbegin(),
2399         E = QualifierUnion.rend();
2400       I != E; (void)++I, ++MOC) {
2401    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
2402    if (MOC->first && MOC->second) {
2403      // Rebuild member pointer type
2404      Composite1 = Context.getMemberPointerType(
2405                                    Context.getQualifiedType(Composite1, Quals),
2406                                    MOC->first);
2407      Composite2 = Context.getMemberPointerType(
2408                                    Context.getQualifiedType(Composite2, Quals),
2409                                    MOC->second);
2410    } else {
2411      // Rebuild pointer type
2412      Composite1
2413        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2414      Composite2
2415        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
2416    }
2417  }
2418
2419  // Try to convert to the first composite pointer type.
2420  InitializedEntity Entity1
2421    = InitializedEntity::InitializeTemporary(Composite1);
2422  InitializationKind Kind
2423    = InitializationKind::CreateCopy(Loc, SourceLocation());
2424  InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2425  InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
2426
2427  if (E1ToC1 && E2ToC1) {
2428    // Conversion to Composite1 is viable.
2429    if (!Context.hasSameType(Composite1, Composite2)) {
2430      // Composite2 is a different type from Composite1. Check whether
2431      // Composite2 is also viable.
2432      InitializedEntity Entity2
2433        = InitializedEntity::InitializeTemporary(Composite2);
2434      InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2435      InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2436      if (E1ToC2 && E2ToC2) {
2437        // Both Composite1 and Composite2 are viable and are different;
2438        // this is an ambiguity.
2439        return QualType();
2440      }
2441    }
2442
2443    // Convert E1 to Composite1
2444    OwningExprResult E1Result
2445      = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2446    if (E1Result.isInvalid())
2447      return QualType();
2448    E1 = E1Result.takeAs<Expr>();
2449
2450    // Convert E2 to Composite1
2451    OwningExprResult E2Result
2452      = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2453    if (E2Result.isInvalid())
2454      return QualType();
2455    E2 = E2Result.takeAs<Expr>();
2456
2457    return Composite1;
2458  }
2459
2460  // Check whether Composite2 is viable.
2461  InitializedEntity Entity2
2462    = InitializedEntity::InitializeTemporary(Composite2);
2463  InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2464  InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2465  if (!E1ToC2 || !E2ToC2)
2466    return QualType();
2467
2468  // Convert E1 to Composite2
2469  OwningExprResult E1Result
2470    = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2471  if (E1Result.isInvalid())
2472    return QualType();
2473  E1 = E1Result.takeAs<Expr>();
2474
2475  // Convert E2 to Composite2
2476  OwningExprResult E2Result
2477    = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2478  if (E2Result.isInvalid())
2479    return QualType();
2480  E2 = E2Result.takeAs<Expr>();
2481
2482  return Composite2;
2483}
2484
2485Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
2486  if (!Context.getLangOptions().CPlusPlus)
2487    return Owned(E);
2488
2489  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2490
2491  const RecordType *RT = E->getType()->getAs<RecordType>();
2492  if (!RT)
2493    return Owned(E);
2494
2495  // If this is the result of a call expression, our source might
2496  // actually be a reference, in which case we shouldn't bind.
2497  if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2498    QualType Ty = CE->getCallee()->getType();
2499    if (const PointerType *PT = Ty->getAs<PointerType>())
2500      Ty = PT->getPointeeType();
2501    else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2502      Ty = BPT->getPointeeType();
2503
2504    const FunctionType *FTy = Ty->getAs<FunctionType>();
2505    if (FTy->getResultType()->isReferenceType())
2506      return Owned(E);
2507  }
2508
2509  // That should be enough to guarantee that this type is complete.
2510  // If it has a trivial destructor, we can avoid the extra copy.
2511  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2512  if (RD->hasTrivialDestructor())
2513    return Owned(E);
2514
2515  CXXTemporary *Temp = CXXTemporary::Create(Context,
2516                                            RD->getDestructor(Context));
2517  ExprTemporaries.push_back(Temp);
2518  if (CXXDestructorDecl *Destructor =
2519        const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
2520    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
2521    CheckDestructorAccess(E->getExprLoc(), Destructor,
2522                          PDiag(diag::err_access_dtor_temp)
2523                            << E->getType());
2524  }
2525  // FIXME: Add the temporary to the temporaries vector.
2526  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2527}
2528
2529Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
2530  assert(SubExpr && "sub expression can't be null!");
2531
2532  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2533  assert(ExprTemporaries.size() >= FirstTemporary);
2534  if (ExprTemporaries.size() == FirstTemporary)
2535    return SubExpr;
2536
2537  Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
2538                                           &ExprTemporaries[FirstTemporary],
2539                                       ExprTemporaries.size() - FirstTemporary);
2540  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2541                        ExprTemporaries.end());
2542
2543  return E;
2544}
2545
2546Sema::OwningExprResult
2547Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2548  if (SubExpr.isInvalid())
2549    return ExprError();
2550
2551  return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2552}
2553
2554FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2555  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2556  assert(ExprTemporaries.size() >= FirstTemporary);
2557
2558  unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2559  CXXTemporary **Temporaries =
2560    NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2561
2562  FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2563
2564  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2565                        ExprTemporaries.end());
2566
2567  return E;
2568}
2569
2570Sema::OwningExprResult
2571Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2572                                   tok::TokenKind OpKind, TypeTy *&ObjectType,
2573                                   bool &MayBePseudoDestructor) {
2574  // Since this might be a postfix expression, get rid of ParenListExprs.
2575  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2576
2577  Expr *BaseExpr = (Expr*)Base.get();
2578  assert(BaseExpr && "no record expansion");
2579
2580  QualType BaseType = BaseExpr->getType();
2581  MayBePseudoDestructor = false;
2582  if (BaseType->isDependentType()) {
2583    // If we have a pointer to a dependent type and are using the -> operator,
2584    // the object type is the type that the pointer points to. We might still
2585    // have enough information about that type to do something useful.
2586    if (OpKind == tok::arrow)
2587      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2588        BaseType = Ptr->getPointeeType();
2589
2590    ObjectType = BaseType.getAsOpaquePtr();
2591    MayBePseudoDestructor = true;
2592    return move(Base);
2593  }
2594
2595  // C++ [over.match.oper]p8:
2596  //   [...] When operator->returns, the operator-> is applied  to the value
2597  //   returned, with the original second operand.
2598  if (OpKind == tok::arrow) {
2599    // The set of types we've considered so far.
2600    llvm::SmallPtrSet<CanQualType,8> CTypes;
2601    llvm::SmallVector<SourceLocation, 8> Locations;
2602    CTypes.insert(Context.getCanonicalType(BaseType));
2603
2604    while (BaseType->isRecordType()) {
2605      Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
2606      BaseExpr = (Expr*)Base.get();
2607      if (BaseExpr == NULL)
2608        return ExprError();
2609      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
2610        Locations.push_back(OpCall->getDirectCallee()->getLocation());
2611      BaseType = BaseExpr->getType();
2612      CanQualType CBaseType = Context.getCanonicalType(BaseType);
2613      if (!CTypes.insert(CBaseType)) {
2614        Diag(OpLoc, diag::err_operator_arrow_circular);
2615        for (unsigned i = 0; i < Locations.size(); i++)
2616          Diag(Locations[i], diag::note_declared_at);
2617        return ExprError();
2618      }
2619    }
2620
2621    if (BaseType->isPointerType())
2622      BaseType = BaseType->getPointeeType();
2623  }
2624
2625  // We could end up with various non-record types here, such as extended
2626  // vector types or Objective-C interfaces. Just return early and let
2627  // ActOnMemberReferenceExpr do the work.
2628  if (!BaseType->isRecordType()) {
2629    // C++ [basic.lookup.classref]p2:
2630    //   [...] If the type of the object expression is of pointer to scalar
2631    //   type, the unqualified-id is looked up in the context of the complete
2632    //   postfix-expression.
2633    //
2634    // This also indicates that we should be parsing a
2635    // pseudo-destructor-name.
2636    ObjectType = 0;
2637    MayBePseudoDestructor = true;
2638    return move(Base);
2639  }
2640
2641  // The object type must be complete (or dependent).
2642  if (!BaseType->isDependentType() &&
2643      RequireCompleteType(OpLoc, BaseType,
2644                          PDiag(diag::err_incomplete_member_access)))
2645    return ExprError();
2646
2647  // C++ [basic.lookup.classref]p2:
2648  //   If the id-expression in a class member access (5.2.5) is an
2649  //   unqualified-id, and the type of the object expression is of a class
2650  //   type C (or of pointer to a class type C), the unqualified-id is looked
2651  //   up in the scope of class C. [...]
2652  ObjectType = BaseType.getAsOpaquePtr();
2653  return move(Base);
2654}
2655
2656Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2657                                                   ExprArg MemExpr) {
2658  Expr *E = (Expr *) MemExpr.get();
2659  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2660  Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2661    << isa<CXXPseudoDestructorExpr>(E)
2662    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
2663
2664  return ActOnCallExpr(/*Scope*/ 0,
2665                       move(MemExpr),
2666                       /*LPLoc*/ ExpectedLParenLoc,
2667                       Sema::MultiExprArg(*this, 0, 0),
2668                       /*CommaLocs*/ 0,
2669                       /*RPLoc*/ ExpectedLParenLoc);
2670}
2671
2672Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2673                                                       SourceLocation OpLoc,
2674                                                       tok::TokenKind OpKind,
2675                                                       const CXXScopeSpec &SS,
2676                                                 TypeSourceInfo *ScopeTypeInfo,
2677                                                       SourceLocation CCLoc,
2678                                                       SourceLocation TildeLoc,
2679                                         PseudoDestructorTypeStorage Destructed,
2680                                                       bool HasTrailingLParen) {
2681  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
2682
2683  // C++ [expr.pseudo]p2:
2684  //   The left-hand side of the dot operator shall be of scalar type. The
2685  //   left-hand side of the arrow operator shall be of pointer to scalar type.
2686  //   This scalar type is the object type.
2687  Expr *BaseE = (Expr *)Base.get();
2688  QualType ObjectType = BaseE->getType();
2689  if (OpKind == tok::arrow) {
2690    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2691      ObjectType = Ptr->getPointeeType();
2692    } else if (!BaseE->isTypeDependent()) {
2693      // The user wrote "p->" when she probably meant "p."; fix it.
2694      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2695        << ObjectType << true
2696        << FixItHint::CreateReplacement(OpLoc, ".");
2697      if (isSFINAEContext())
2698        return ExprError();
2699
2700      OpKind = tok::period;
2701    }
2702  }
2703
2704  if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2705    Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2706      << ObjectType << BaseE->getSourceRange();
2707    return ExprError();
2708  }
2709
2710  // C++ [expr.pseudo]p2:
2711  //   [...] The cv-unqualified versions of the object type and of the type
2712  //   designated by the pseudo-destructor-name shall be the same type.
2713  if (DestructedTypeInfo) {
2714    QualType DestructedType = DestructedTypeInfo->getType();
2715    SourceLocation DestructedTypeStart
2716      = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2717    if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2718        !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2719      Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2720        << ObjectType << DestructedType << BaseE->getSourceRange()
2721        << DestructedTypeInfo->getTypeLoc().getSourceRange();
2722
2723      // Recover by setting the destructed type to the object type.
2724      DestructedType = ObjectType;
2725      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2726                                                           DestructedTypeStart);
2727      Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2728    }
2729  }
2730
2731  // C++ [expr.pseudo]p2:
2732  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2733  //   form
2734  //
2735  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2736  //
2737  //   shall designate the same scalar type.
2738  if (ScopeTypeInfo) {
2739    QualType ScopeType = ScopeTypeInfo->getType();
2740    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2741        !Context.hasSameType(ScopeType, ObjectType)) {
2742
2743      Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2744           diag::err_pseudo_dtor_type_mismatch)
2745        << ObjectType << ScopeType << BaseE->getSourceRange()
2746        << ScopeTypeInfo->getTypeLoc().getSourceRange();
2747
2748      ScopeType = QualType();
2749      ScopeTypeInfo = 0;
2750    }
2751  }
2752
2753  OwningExprResult Result
2754    = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2755                                                  Base.takeAs<Expr>(),
2756                                                  OpKind == tok::arrow,
2757                                                  OpLoc,
2758                                       (NestedNameSpecifier *) SS.getScopeRep(),
2759                                                  SS.getRange(),
2760                                                  ScopeTypeInfo,
2761                                                  CCLoc,
2762                                                  TildeLoc,
2763                                                  Destructed));
2764
2765  if (HasTrailingLParen)
2766    return move(Result);
2767
2768  return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
2769}
2770
2771Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2772                                                       SourceLocation OpLoc,
2773                                                       tok::TokenKind OpKind,
2774                                                       CXXScopeSpec &SS,
2775                                                  UnqualifiedId &FirstTypeName,
2776                                                       SourceLocation CCLoc,
2777                                                       SourceLocation TildeLoc,
2778                                                 UnqualifiedId &SecondTypeName,
2779                                                       bool HasTrailingLParen) {
2780  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2781          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2782         "Invalid first type name in pseudo-destructor");
2783  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2784          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2785         "Invalid second type name in pseudo-destructor");
2786
2787  Expr *BaseE = (Expr *)Base.get();
2788
2789  // C++ [expr.pseudo]p2:
2790  //   The left-hand side of the dot operator shall be of scalar type. The
2791  //   left-hand side of the arrow operator shall be of pointer to scalar type.
2792  //   This scalar type is the object type.
2793  QualType ObjectType = BaseE->getType();
2794  if (OpKind == tok::arrow) {
2795    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2796      ObjectType = Ptr->getPointeeType();
2797    } else if (!ObjectType->isDependentType()) {
2798      // The user wrote "p->" when she probably meant "p."; fix it.
2799      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2800        << ObjectType << true
2801        << FixItHint::CreateReplacement(OpLoc, ".");
2802      if (isSFINAEContext())
2803        return ExprError();
2804
2805      OpKind = tok::period;
2806    }
2807  }
2808
2809  // Compute the object type that we should use for name lookup purposes. Only
2810  // record types and dependent types matter.
2811  void *ObjectTypePtrForLookup = 0;
2812  if (!SS.isSet()) {
2813    ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2814    if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2815      ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2816  }
2817
2818  // Convert the name of the type being destructed (following the ~) into a
2819  // type (with source-location information).
2820  QualType DestructedType;
2821  TypeSourceInfo *DestructedTypeInfo = 0;
2822  PseudoDestructorTypeStorage Destructed;
2823  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2824    TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2825                            SecondTypeName.StartLocation,
2826                            S, &SS, true, ObjectTypePtrForLookup);
2827    if (!T &&
2828        ((SS.isSet() && !computeDeclContext(SS, false)) ||
2829         (!SS.isSet() && ObjectType->isDependentType()))) {
2830      // The name of the type being destroyed is a dependent name, and we
2831      // couldn't find anything useful in scope. Just store the identifier and
2832      // it's location, and we'll perform (qualified) name lookup again at
2833      // template instantiation time.
2834      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2835                                               SecondTypeName.StartLocation);
2836    } else if (!T) {
2837      Diag(SecondTypeName.StartLocation,
2838           diag::err_pseudo_dtor_destructor_non_type)
2839        << SecondTypeName.Identifier << ObjectType;
2840      if (isSFINAEContext())
2841        return ExprError();
2842
2843      // Recover by assuming we had the right type all along.
2844      DestructedType = ObjectType;
2845    } else
2846      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
2847  } else {
2848    // Resolve the template-id to a type.
2849    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
2850    ASTTemplateArgsPtr TemplateArgsPtr(*this,
2851                                       TemplateId->getTemplateArgs(),
2852                                       TemplateId->NumArgs);
2853    TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2854                                       TemplateId->TemplateNameLoc,
2855                                       TemplateId->LAngleLoc,
2856                                       TemplateArgsPtr,
2857                                       TemplateId->RAngleLoc);
2858    if (T.isInvalid() || !T.get()) {
2859      // Recover by assuming we had the right type all along.
2860      DestructedType = ObjectType;
2861    } else
2862      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
2863  }
2864
2865  // If we've performed some kind of recovery, (re-)build the type source
2866  // information.
2867  if (!DestructedType.isNull()) {
2868    if (!DestructedTypeInfo)
2869      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
2870                                                  SecondTypeName.StartLocation);
2871    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2872  }
2873
2874  // Convert the name of the scope type (the type prior to '::') into a type.
2875  TypeSourceInfo *ScopeTypeInfo = 0;
2876  QualType ScopeType;
2877  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2878      FirstTypeName.Identifier) {
2879    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2880      TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2881                              FirstTypeName.StartLocation,
2882                              S, &SS, false, ObjectTypePtrForLookup);
2883      if (!T) {
2884        Diag(FirstTypeName.StartLocation,
2885             diag::err_pseudo_dtor_destructor_non_type)
2886          << FirstTypeName.Identifier << ObjectType;
2887
2888        if (isSFINAEContext())
2889          return ExprError();
2890
2891        // Just drop this type. It's unnecessary anyway.
2892        ScopeType = QualType();
2893      } else
2894        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
2895    } else {
2896      // Resolve the template-id to a type.
2897      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
2898      ASTTemplateArgsPtr TemplateArgsPtr(*this,
2899                                         TemplateId->getTemplateArgs(),
2900                                         TemplateId->NumArgs);
2901      TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2902                                         TemplateId->TemplateNameLoc,
2903                                         TemplateId->LAngleLoc,
2904                                         TemplateArgsPtr,
2905                                         TemplateId->RAngleLoc);
2906      if (T.isInvalid() || !T.get()) {
2907        // Recover by dropping this type.
2908        ScopeType = QualType();
2909      } else
2910        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
2911    }
2912  }
2913
2914  if (!ScopeType.isNull() && !ScopeTypeInfo)
2915    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2916                                                  FirstTypeName.StartLocation);
2917
2918
2919  return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
2920                                   ScopeTypeInfo, CCLoc, TildeLoc,
2921                                   Destructed, HasTrailingLParen);
2922}
2923
2924CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2925                                                NamedDecl *FoundDecl,
2926                                                CXXMethodDecl *Method) {
2927  if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2928                                          FoundDecl, Method))
2929    assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2930
2931  MemberExpr *ME =
2932      new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2933                               SourceLocation(), Method->getType());
2934  QualType ResultType = Method->getResultType().getNonReferenceType();
2935  MarkDeclarationReferenced(Exp->getLocStart(), Method);
2936  CXXMemberCallExpr *CE =
2937    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2938                                    Exp->getLocEnd());
2939  return CE;
2940}
2941
2942Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2943  Expr *FullExpr = Arg.takeAs<Expr>();
2944  if (FullExpr)
2945    FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
2946
2947  return Owned(FullExpr);
2948}
2949