SemaExprCXX.cpp revision 218893
1193326Sed//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed//  This file implements semantic analysis for C++ expressions.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14212904Sdim#include "clang/Sema/SemaInternal.h"
15212904Sdim#include "clang/Sema/DeclSpec.h"
16212904Sdim#include "clang/Sema/Initialization.h"
17212904Sdim#include "clang/Sema/Lookup.h"
18212904Sdim#include "clang/Sema/ParsedTemplate.h"
19218893Sdim#include "clang/Sema/ScopeInfo.h"
20212904Sdim#include "clang/Sema/TemplateDeduction.h"
21198092Srdivacky#include "clang/AST/ASTContext.h"
22198092Srdivacky#include "clang/AST/CXXInheritance.h"
23212904Sdim#include "clang/AST/DeclObjC.h"
24193326Sed#include "clang/AST/ExprCXX.h"
25210299Sed#include "clang/AST/ExprObjC.h"
26204643Srdivacky#include "clang/AST/TypeLoc.h"
27198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
28198092Srdivacky#include "clang/Basic/TargetInfo.h"
29198092Srdivacky#include "clang/Lex/Preprocessor.h"
30193326Sed#include "llvm/ADT/STLExtras.h"
31193326Sedusing namespace clang;
32212904Sdimusing namespace sema;
33193326Sed
34212904SdimParsedType Sema::getDestructorName(SourceLocation TildeLoc,
35218893Sdim                                   IdentifierInfo &II,
36212904Sdim                                   SourceLocation NameLoc,
37212904Sdim                                   Scope *S, CXXScopeSpec &SS,
38212904Sdim                                   ParsedType ObjectTypePtr,
39212904Sdim                                   bool EnteringContext) {
40204643Srdivacky  // Determine where to perform name lookup.
41204643Srdivacky
42204643Srdivacky  // FIXME: This area of the standard is very messy, and the current
43204643Srdivacky  // wording is rather unclear about which scopes we search for the
44204643Srdivacky  // destructor name; see core issues 399 and 555. Issue 399 in
45204643Srdivacky  // particular shows where the current description of destructor name
46204643Srdivacky  // lookup is completely out of line with existing practice, e.g.,
47204643Srdivacky  // this appears to be ill-formed:
48204643Srdivacky  //
49204643Srdivacky  //   namespace N {
50204643Srdivacky  //     template <typename T> struct S {
51204643Srdivacky  //       ~S();
52204643Srdivacky  //     };
53204643Srdivacky  //   }
54204643Srdivacky  //
55204643Srdivacky  //   void f(N::S<int>* s) {
56204643Srdivacky  //     s->N::S<int>::~S();
57204643Srdivacky  //   }
58204643Srdivacky  //
59204643Srdivacky  // See also PR6358 and PR6359.
60210299Sed  // For this reason, we're currently only doing the C++03 version of this
61210299Sed  // code; the C++0x version has to wait until we get a proper spec.
62204643Srdivacky  QualType SearchType;
63204643Srdivacky  DeclContext *LookupCtx = 0;
64204643Srdivacky  bool isDependent = false;
65204643Srdivacky  bool LookInScope = false;
66204643Srdivacky
67204643Srdivacky  // If we have an object type, it's because we are in a
68204643Srdivacky  // pseudo-destructor-expression or a member access expression, and
69204643Srdivacky  // we know what type we're looking for.
70204643Srdivacky  if (ObjectTypePtr)
71204643Srdivacky    SearchType = GetTypeFromParser(ObjectTypePtr);
72204643Srdivacky
73204643Srdivacky  if (SS.isSet()) {
74204643Srdivacky    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
75218893Sdim
76204643Srdivacky    bool AlreadySearched = false;
77204643Srdivacky    bool LookAtPrefix = true;
78210299Sed    // C++ [basic.lookup.qual]p6:
79218893Sdim    //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
80210299Sed    //   the type-names are looked up as types in the scope designated by the
81210299Sed    //   nested-name-specifier. In a qualified-id of the form:
82210299Sed    //
83218893Sdim    //     ::[opt] nested-name-specifier  ~ class-name
84218893Sdim    //
85210299Sed    //   where the nested-name-specifier designates a namespace scope, and in
86204643Srdivacky    //   a qualified-id of the form:
87204643Srdivacky    //
88218893Sdim    //     ::opt nested-name-specifier class-name ::  ~ class-name
89204643Srdivacky    //
90218893Sdim    //   the class-names are looked up as types in the scope designated by
91210299Sed    //   the nested-name-specifier.
92204643Srdivacky    //
93210299Sed    // Here, we check the first case (completely) and determine whether the
94218893Sdim    // code below is permitted to look at the prefix of the
95210299Sed    // nested-name-specifier.
96210299Sed    DeclContext *DC = computeDeclContext(SS, EnteringContext);
97210299Sed    if (DC && DC->isFileContext()) {
98210299Sed      AlreadySearched = true;
99210299Sed      LookupCtx = DC;
100210299Sed      isDependent = false;
101210299Sed    } else if (DC && isa<CXXRecordDecl>(DC))
102210299Sed      LookAtPrefix = false;
103218893Sdim
104210299Sed    // The second case from the C++03 rules quoted further above.
105204643Srdivacky    NestedNameSpecifier *Prefix = 0;
106204643Srdivacky    if (AlreadySearched) {
107204643Srdivacky      // Nothing left to do.
108204643Srdivacky    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
109204643Srdivacky      CXXScopeSpec PrefixSS;
110204643Srdivacky      PrefixSS.setScopeRep(Prefix);
111204643Srdivacky      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
112204643Srdivacky      isDependent = isDependentScopeSpecifier(PrefixSS);
113204643Srdivacky    } else if (ObjectTypePtr) {
114204643Srdivacky      LookupCtx = computeDeclContext(SearchType);
115204643Srdivacky      isDependent = SearchType->isDependentType();
116204643Srdivacky    } else {
117204643Srdivacky      LookupCtx = computeDeclContext(SS, EnteringContext);
118204643Srdivacky      isDependent = LookupCtx && LookupCtx->isDependentContext();
119204643Srdivacky    }
120218893Sdim
121204643Srdivacky    LookInScope = false;
122204643Srdivacky  } else if (ObjectTypePtr) {
123204643Srdivacky    // C++ [basic.lookup.classref]p3:
124204643Srdivacky    //   If the unqualified-id is ~type-name, the type-name is looked up
125204643Srdivacky    //   in the context of the entire postfix-expression. If the type T
126204643Srdivacky    //   of the object expression is of a class type C, the type-name is
127204643Srdivacky    //   also looked up in the scope of class C. At least one of the
128204643Srdivacky    //   lookups shall find a name that refers to (possibly
129204643Srdivacky    //   cv-qualified) T.
130204643Srdivacky    LookupCtx = computeDeclContext(SearchType);
131204643Srdivacky    isDependent = SearchType->isDependentType();
132218893Sdim    assert((isDependent || !SearchType->isIncompleteType()) &&
133204643Srdivacky           "Caller should have completed object type");
134204643Srdivacky
135204643Srdivacky    LookInScope = true;
136204643Srdivacky  } else {
137204643Srdivacky    // Perform lookup into the current scope (only).
138204643Srdivacky    LookInScope = true;
139204643Srdivacky  }
140204643Srdivacky
141204643Srdivacky  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
142204643Srdivacky  for (unsigned Step = 0; Step != 2; ++Step) {
143204643Srdivacky    // Look for the name first in the computed lookup context (if we
144204643Srdivacky    // have one) and, if that fails to find a match, in the sope (if
145204643Srdivacky    // we're allowed to look there).
146204643Srdivacky    Found.clear();
147204643Srdivacky    if (Step == 0 && LookupCtx)
148204643Srdivacky      LookupQualifiedName(Found, LookupCtx);
149204643Srdivacky    else if (Step == 1 && LookInScope && S)
150204643Srdivacky      LookupName(Found, S);
151204643Srdivacky    else
152204643Srdivacky      continue;
153204643Srdivacky
154204643Srdivacky    // FIXME: Should we be suppressing ambiguities here?
155204643Srdivacky    if (Found.isAmbiguous())
156212904Sdim      return ParsedType();
157204643Srdivacky
158204643Srdivacky    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
159204643Srdivacky      QualType T = Context.getTypeDeclType(Type);
160204643Srdivacky
161204643Srdivacky      if (SearchType.isNull() || SearchType->isDependentType() ||
162204643Srdivacky          Context.hasSameUnqualifiedType(T, SearchType)) {
163204643Srdivacky        // We found our type!
164204643Srdivacky
165212904Sdim        return ParsedType::make(T);
166204643Srdivacky      }
167204643Srdivacky    }
168204643Srdivacky
169204643Srdivacky    // If the name that we found is a class template name, and it is
170204643Srdivacky    // the same name as the template name in the last part of the
171204643Srdivacky    // nested-name-specifier (if present) or the object type, then
172204643Srdivacky    // this is the destructor for that class.
173204643Srdivacky    // FIXME: This is a workaround until we get real drafting for core
174218893Sdim    // issue 399, for which there isn't even an obvious direction.
175204643Srdivacky    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
176204643Srdivacky      QualType MemberOfType;
177204643Srdivacky      if (SS.isSet()) {
178204643Srdivacky        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
179204643Srdivacky          // Figure out the type of the context, if it has one.
180204962Srdivacky          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
181204962Srdivacky            MemberOfType = Context.getTypeDeclType(Record);
182204643Srdivacky        }
183204643Srdivacky      }
184204643Srdivacky      if (MemberOfType.isNull())
185204643Srdivacky        MemberOfType = SearchType;
186218893Sdim
187204643Srdivacky      if (MemberOfType.isNull())
188204643Srdivacky        continue;
189204643Srdivacky
190204643Srdivacky      // We're referring into a class template specialization. If the
191204643Srdivacky      // class template we found is the same as the template being
192204643Srdivacky      // specialized, we found what we are looking for.
193204643Srdivacky      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
194204643Srdivacky        if (ClassTemplateSpecializationDecl *Spec
195204643Srdivacky              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
196204643Srdivacky          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
197204643Srdivacky                Template->getCanonicalDecl())
198212904Sdim            return ParsedType::make(MemberOfType);
199204643Srdivacky        }
200204643Srdivacky
201204643Srdivacky        continue;
202204643Srdivacky      }
203218893Sdim
204204643Srdivacky      // We're referring to an unresolved class template
205204643Srdivacky      // specialization. Determine whether we class template we found
206204643Srdivacky      // is the same as the template being specialized or, if we don't
207204643Srdivacky      // know which template is being specialized, that it at least
208204643Srdivacky      // has the same name.
209204643Srdivacky      if (const TemplateSpecializationType *SpecType
210204643Srdivacky            = MemberOfType->getAs<TemplateSpecializationType>()) {
211204643Srdivacky        TemplateName SpecName = SpecType->getTemplateName();
212204643Srdivacky
213204643Srdivacky        // The class template we found is the same template being
214204643Srdivacky        // specialized.
215204643Srdivacky        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
216204643Srdivacky          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
217212904Sdim            return ParsedType::make(MemberOfType);
218204643Srdivacky
219204643Srdivacky          continue;
220204643Srdivacky        }
221204643Srdivacky
222204643Srdivacky        // The class template we found has the same name as the
223204643Srdivacky        // (dependent) template name being specialized.
224218893Sdim        if (DependentTemplateName *DepTemplate
225204643Srdivacky                                    = SpecName.getAsDependentTemplateName()) {
226204643Srdivacky          if (DepTemplate->isIdentifier() &&
227204643Srdivacky              DepTemplate->getIdentifier() == Template->getIdentifier())
228212904Sdim            return ParsedType::make(MemberOfType);
229204643Srdivacky
230204643Srdivacky          continue;
231204643Srdivacky        }
232204643Srdivacky      }
233204643Srdivacky    }
234204643Srdivacky  }
235204643Srdivacky
236204643Srdivacky  if (isDependent) {
237204643Srdivacky    // We didn't find our type, but that's okay: it's dependent
238204643Srdivacky    // anyway.
239204643Srdivacky    NestedNameSpecifier *NNS = 0;
240204643Srdivacky    SourceRange Range;
241204643Srdivacky    if (SS.isSet()) {
242204643Srdivacky      NNS = (NestedNameSpecifier *)SS.getScopeRep();
243204643Srdivacky      Range = SourceRange(SS.getRange().getBegin(), NameLoc);
244204643Srdivacky    } else {
245204643Srdivacky      NNS = NestedNameSpecifier::Create(Context, &II);
246204643Srdivacky      Range = SourceRange(NameLoc);
247204643Srdivacky    }
248204643Srdivacky
249212904Sdim    QualType T = CheckTypenameType(ETK_None, NNS, II,
250212904Sdim                                   SourceLocation(),
251212904Sdim                                   Range, NameLoc);
252212904Sdim    return ParsedType::make(T);
253204643Srdivacky  }
254204643Srdivacky
255204643Srdivacky  if (ObjectTypePtr)
256204643Srdivacky    Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
257218893Sdim      << &II;
258204643Srdivacky  else
259204643Srdivacky    Diag(NameLoc, diag::err_destructor_class_name);
260204643Srdivacky
261212904Sdim  return ParsedType();
262204643Srdivacky}
263204643Srdivacky
264207619Srdivacky/// \brief Build a C++ typeid expression with a type operand.
265212904SdimExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
266218893Sdim                                SourceLocation TypeidLoc,
267218893Sdim                                TypeSourceInfo *Operand,
268218893Sdim                                SourceLocation RParenLoc) {
269207619Srdivacky  // C++ [expr.typeid]p4:
270218893Sdim  //   The top-level cv-qualifiers of the lvalue expression or the type-id
271207619Srdivacky  //   that is the operand of typeid are always ignored.
272218893Sdim  //   If the type of the type-id is a class type or a reference to a class
273207619Srdivacky  //   type, the class shall be completely-defined.
274210299Sed  Qualifiers Quals;
275210299Sed  QualType T
276210299Sed    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
277210299Sed                                      Quals);
278207619Srdivacky  if (T->getAs<RecordType>() &&
279207619Srdivacky      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
280207619Srdivacky    return ExprError();
281218893Sdim
282207619Srdivacky  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
283207619Srdivacky                                           Operand,
284207619Srdivacky                                           SourceRange(TypeidLoc, RParenLoc)));
285207619Srdivacky}
286207619Srdivacky
287207619Srdivacky/// \brief Build a C++ typeid expression with an expression operand.
288212904SdimExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
289218893Sdim                                SourceLocation TypeidLoc,
290218893Sdim                                Expr *E,
291218893Sdim                                SourceLocation RParenLoc) {
292207619Srdivacky  bool isUnevaluatedOperand = true;
293207619Srdivacky  if (E && !E->isTypeDependent()) {
294207619Srdivacky    QualType T = E->getType();
295207619Srdivacky    if (const RecordType *RecordT = T->getAs<RecordType>()) {
296207619Srdivacky      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
297207619Srdivacky      // C++ [expr.typeid]p3:
298207619Srdivacky      //   [...] If the type of the expression is a class type, the class
299207619Srdivacky      //   shall be completely-defined.
300207619Srdivacky      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
301207619Srdivacky        return ExprError();
302218893Sdim
303207619Srdivacky      // C++ [expr.typeid]p3:
304212904Sdim      //   When typeid is applied to an expression other than an glvalue of a
305207619Srdivacky      //   polymorphic class type [...] [the] expression is an unevaluated
306207619Srdivacky      //   operand. [...]
307212904Sdim      if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
308207619Srdivacky        isUnevaluatedOperand = false;
309208600Srdivacky
310208600Srdivacky        // We require a vtable to query the type at run time.
311208600Srdivacky        MarkVTableUsed(TypeidLoc, RecordD);
312208600Srdivacky      }
313207619Srdivacky    }
314218893Sdim
315207619Srdivacky    // C++ [expr.typeid]p4:
316207619Srdivacky    //   [...] If the type of the type-id is a reference to a possibly
317218893Sdim    //   cv-qualified type, the result of the typeid expression refers to a
318218893Sdim    //   std::type_info object representing the cv-unqualified referenced
319207619Srdivacky    //   type.
320210299Sed    Qualifiers Quals;
321210299Sed    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
322210299Sed    if (!Context.hasSameType(T, UnqualT)) {
323210299Sed      T = UnqualT;
324212904Sdim      ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E));
325207619Srdivacky    }
326207619Srdivacky  }
327218893Sdim
328207619Srdivacky  // If this is an unevaluated operand, clear out the set of
329207619Srdivacky  // declaration references we have been computing and eliminate any
330207619Srdivacky  // temporaries introduced in its computation.
331207619Srdivacky  if (isUnevaluatedOperand)
332207619Srdivacky    ExprEvalContexts.back().Context = Unevaluated;
333218893Sdim
334207619Srdivacky  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
335212904Sdim                                           E,
336218893Sdim                                           SourceRange(TypeidLoc, RParenLoc)));
337207619Srdivacky}
338207619Srdivacky
339207619Srdivacky/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
340212904SdimExprResult
341193326SedSema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
342193326Sed                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
343207619Srdivacky  // Find the std::type_info type.
344198092Srdivacky  if (!StdNamespace)
345193326Sed    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
346198092Srdivacky
347218893Sdim  if (!CXXTypeInfoDecl) {
348218893Sdim    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
349218893Sdim    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
350218893Sdim    LookupQualifiedName(R, getStdNamespace());
351218893Sdim    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
352218893Sdim    if (!CXXTypeInfoDecl)
353218893Sdim      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
354218893Sdim  }
355218893Sdim
356218893Sdim  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
357218893Sdim
358207619Srdivacky  if (isType) {
359207619Srdivacky    // The operand is a type; handle it as such.
360207619Srdivacky    TypeSourceInfo *TInfo = 0;
361212904Sdim    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
362212904Sdim                                   &TInfo);
363207619Srdivacky    if (T.isNull())
364207619Srdivacky      return ExprError();
365218893Sdim
366207619Srdivacky    if (!TInfo)
367207619Srdivacky      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
368193326Sed
369207619Srdivacky    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
370194711Sed  }
371198092Srdivacky
372218893Sdim  // The operand is an expression.
373212904Sdim  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
374193326Sed}
375193326Sed
376218893Sdim/// Retrieve the UuidAttr associated with QT.
377218893Sdimstatic UuidAttr *GetUuidAttrOfType(QualType QT) {
378218893Sdim  // Optionally remove one level of pointer, reference or array indirection.
379218893Sdim  const Type *Ty = QT.getTypePtr();;
380218893Sdim  if (QT->isPointerType() || QT->isReferenceType())
381218893Sdim    Ty = QT->getPointeeType().getTypePtr();
382218893Sdim  else if (QT->isArrayType())
383218893Sdim    Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
384218893Sdim
385218893Sdim  // Loop all class definition and declaration looking for an uuid attribute.
386218893Sdim  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
387218893Sdim  while (RD) {
388218893Sdim    if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
389218893Sdim      return Uuid;
390218893Sdim    RD = RD->getPreviousDeclaration();
391218893Sdim  }
392218893Sdim  return 0;
393218893Sdim}
394218893Sdim
395218893Sdim/// \brief Build a Microsoft __uuidof expression with a type operand.
396218893SdimExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
397218893Sdim                                SourceLocation TypeidLoc,
398218893Sdim                                TypeSourceInfo *Operand,
399218893Sdim                                SourceLocation RParenLoc) {
400218893Sdim  if (!Operand->getType()->isDependentType()) {
401218893Sdim    if (!GetUuidAttrOfType(Operand->getType()))
402218893Sdim      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
403218893Sdim  }
404218893Sdim
405218893Sdim  // FIXME: add __uuidof semantic analysis for type operand.
406218893Sdim  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
407218893Sdim                                           Operand,
408218893Sdim                                           SourceRange(TypeidLoc, RParenLoc)));
409218893Sdim}
410218893Sdim
411218893Sdim/// \brief Build a Microsoft __uuidof expression with an expression operand.
412218893SdimExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
413218893Sdim                                SourceLocation TypeidLoc,
414218893Sdim                                Expr *E,
415218893Sdim                                SourceLocation RParenLoc) {
416218893Sdim  if (!E->getType()->isDependentType()) {
417218893Sdim    if (!GetUuidAttrOfType(E->getType()) &&
418218893Sdim        !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
419218893Sdim      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
420218893Sdim  }
421218893Sdim  // FIXME: add __uuidof semantic analysis for type operand.
422218893Sdim  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
423218893Sdim                                           E,
424218893Sdim                                           SourceRange(TypeidLoc, RParenLoc)));
425218893Sdim}
426218893Sdim
427218893Sdim/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
428218893SdimExprResult
429218893SdimSema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
430218893Sdim                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
431218893Sdim  // If MSVCGuidDecl has not been cached, do the lookup.
432218893Sdim  if (!MSVCGuidDecl) {
433218893Sdim    IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
434218893Sdim    LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
435218893Sdim    LookupQualifiedName(R, Context.getTranslationUnitDecl());
436218893Sdim    MSVCGuidDecl = R.getAsSingle<RecordDecl>();
437218893Sdim    if (!MSVCGuidDecl)
438218893Sdim      return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
439218893Sdim  }
440218893Sdim
441218893Sdim  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
442218893Sdim
443218893Sdim  if (isType) {
444218893Sdim    // The operand is a type; handle it as such.
445218893Sdim    TypeSourceInfo *TInfo = 0;
446218893Sdim    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
447218893Sdim                                   &TInfo);
448218893Sdim    if (T.isNull())
449218893Sdim      return ExprError();
450218893Sdim
451218893Sdim    if (!TInfo)
452218893Sdim      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
453218893Sdim
454218893Sdim    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
455218893Sdim  }
456218893Sdim
457218893Sdim  // The operand is an expression.
458218893Sdim  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
459218893Sdim}
460218893Sdim
461193326Sed/// ActOnCXXBoolLiteral - Parse {true,false} literals.
462212904SdimExprResult
463193326SedSema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
464193326Sed  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
465193326Sed         "Unknown C++ Boolean value!");
466193326Sed  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
467193326Sed                                                Context.BoolTy, OpLoc));
468193326Sed}
469193326Sed
470193326Sed/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
471212904SdimExprResult
472193326SedSema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
473193326Sed  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
474193326Sed}
475193326Sed
476193326Sed/// ActOnCXXThrow - Parse throw expressions.
477212904SdimExprResult
478212904SdimSema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
479218893Sdim  if (!getLangOptions().Exceptions)
480218893Sdim    Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
481218893Sdim
482193326Sed  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
483193326Sed    return ExprError();
484193326Sed  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
485193326Sed}
486193326Sed
487193326Sed/// CheckCXXThrowOperand - Validate the operand of a throw.
488193326Sedbool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
489193326Sed  // C++ [except.throw]p3:
490201361Srdivacky  //   A throw-expression initializes a temporary object, called the exception
491201361Srdivacky  //   object, the type of which is determined by removing any top-level
492201361Srdivacky  //   cv-qualifiers from the static type of the operand of throw and adjusting
493218893Sdim  //   the type from "array of T" or "function returning T" to "pointer to T"
494201361Srdivacky  //   or "pointer to function returning T", [...]
495201361Srdivacky  if (E->getType().hasQualifiers())
496212904Sdim    ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
497212904Sdim                      CastCategory(E));
498218893Sdim
499193326Sed  DefaultFunctionArrayConversion(E);
500193326Sed
501193326Sed  //   If the type of the exception would be an incomplete type or a pointer
502193326Sed  //   to an incomplete type other than (cv) void the program is ill-formed.
503193326Sed  QualType Ty = E->getType();
504207619Srdivacky  bool isPointer = false;
505198092Srdivacky  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
506193326Sed    Ty = Ptr->getPointeeType();
507207619Srdivacky    isPointer = true;
508193326Sed  }
509193326Sed  if (!isPointer || !Ty->isVoidType()) {
510193326Sed    if (RequireCompleteType(ThrowLoc, Ty,
511198092Srdivacky                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
512198092Srdivacky                                            : diag::err_throw_incomplete)
513198092Srdivacky                              << E->getSourceRange()))
514193326Sed      return true;
515204643Srdivacky
516207619Srdivacky    if (RequireNonAbstractType(ThrowLoc, E->getType(),
517207619Srdivacky                               PDiag(diag::err_throw_abstract_type)
518207619Srdivacky                                 << E->getSourceRange()))
519207619Srdivacky      return true;
520193326Sed  }
521193326Sed
522207619Srdivacky  // Initialize the exception result.  This implicitly weeds out
523207619Srdivacky  // abstract types or types with inaccessible copy constructors.
524218893Sdim  const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
525218893Sdim
526218893Sdim  // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
527207619Srdivacky  InitializedEntity Entity =
528218893Sdim      InitializedEntity::InitializeException(ThrowLoc, E->getType(),
529218893Sdim                                             /*NRVO=*/false);
530218893Sdim  ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
531218893Sdim                                                   QualType(), E);
532207619Srdivacky  if (Res.isInvalid())
533207619Srdivacky    return true;
534207619Srdivacky  E = Res.takeAs<Expr>();
535208600Srdivacky
536210299Sed  // If the exception has class type, we need additional handling.
537210299Sed  const RecordType *RecordTy = Ty->getAs<RecordType>();
538210299Sed  if (!RecordTy)
539210299Sed    return false;
540210299Sed  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
541210299Sed
542208600Srdivacky  // If we are throwing a polymorphic class type or pointer thereof,
543208600Srdivacky  // exception handling will make use of the vtable.
544210299Sed  MarkVTableUsed(ThrowLoc, RD);
545210299Sed
546218893Sdim  // If a pointer is thrown, the referenced object will not be destroyed.
547218893Sdim  if (isPointer)
548218893Sdim    return false;
549218893Sdim
550210299Sed  // If the class has a non-trivial destructor, we must be able to call it.
551210299Sed  if (RD->hasTrivialDestructor())
552210299Sed    return false;
553210299Sed
554218893Sdim  CXXDestructorDecl *Destructor
555210299Sed    = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
556210299Sed  if (!Destructor)
557210299Sed    return false;
558210299Sed
559210299Sed  MarkDeclarationReferenced(E->getExprLoc(), Destructor);
560210299Sed  CheckDestructorAccess(E->getExprLoc(), Destructor,
561210299Sed                        PDiag(diag::err_access_dtor_exception) << Ty);
562193326Sed  return false;
563193326Sed}
564193326Sed
565218893SdimCXXMethodDecl *Sema::tryCaptureCXXThis() {
566218893Sdim  // Ignore block scopes: we can capture through them.
567218893Sdim  // Ignore nested enum scopes: we'll diagnose non-constant expressions
568218893Sdim  // where they're invalid, and other uses are legitimate.
569218893Sdim  // Don't ignore nested class scopes: you can't use 'this' in a local class.
570218893Sdim  DeclContext *DC = CurContext;
571218893Sdim  while (true) {
572218893Sdim    if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
573218893Sdim    else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
574218893Sdim    else break;
575218893Sdim  }
576218893Sdim
577218893Sdim  // If we're not in an instance method, error out.
578218893Sdim  CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
579218893Sdim  if (!method || !method->isInstance())
580218893Sdim    return 0;
581218893Sdim
582218893Sdim  // Mark that we're closing on 'this' in all the block scopes, if applicable.
583218893Sdim  for (unsigned idx = FunctionScopes.size() - 1;
584218893Sdim       isa<BlockScopeInfo>(FunctionScopes[idx]);
585218893Sdim       --idx)
586218893Sdim    cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
587218893Sdim
588218893Sdim  return method;
589218893Sdim}
590218893Sdim
591218893SdimExprResult Sema::ActOnCXXThis(SourceLocation loc) {
592193326Sed  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
593193326Sed  /// is a non-lvalue expression whose value is the address of the object for
594193326Sed  /// which the function is called.
595193326Sed
596218893Sdim  CXXMethodDecl *method = tryCaptureCXXThis();
597218893Sdim  if (!method) return Diag(loc, diag::err_invalid_this_use);
598193326Sed
599218893Sdim  return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
600218893Sdim                                         /*isImplicit=*/false));
601193326Sed}
602193326Sed
603212904SdimExprResult
604218893SdimSema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
605193326Sed                                SourceLocation LParenLoc,
606193326Sed                                MultiExprArg exprs,
607193326Sed                                SourceLocation RParenLoc) {
608203955Srdivacky  if (!TypeRep)
609203955Srdivacky    return ExprError();
610203955Srdivacky
611202879Srdivacky  TypeSourceInfo *TInfo;
612202879Srdivacky  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
613202879Srdivacky  if (!TInfo)
614202879Srdivacky    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
615218893Sdim
616218893Sdim  return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
617218893Sdim}
618218893Sdim
619218893Sdim/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
620218893Sdim/// Can be interpreted either as function-style casting ("int(x)")
621218893Sdim/// or class type construction ("ClassType(x,y,z)")
622218893Sdim/// or creation of a value-initialized type ("int()").
623218893SdimExprResult
624218893SdimSema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
625218893Sdim                                SourceLocation LParenLoc,
626218893Sdim                                MultiExprArg exprs,
627218893Sdim                                SourceLocation RParenLoc) {
628218893Sdim  QualType Ty = TInfo->getType();
629193326Sed  unsigned NumExprs = exprs.size();
630193326Sed  Expr **Exprs = (Expr**)exprs.get();
631218893Sdim  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
632193326Sed  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
633193326Sed
634193326Sed  if (Ty->isDependentType() ||
635193326Sed      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
636193326Sed    exprs.release();
637198092Srdivacky
638218893Sdim    return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
639193326Sed                                                    LParenLoc,
640193326Sed                                                    Exprs, NumExprs,
641193326Sed                                                    RParenLoc));
642193326Sed  }
643193326Sed
644198092Srdivacky  if (Ty->isArrayType())
645198092Srdivacky    return ExprError(Diag(TyBeginLoc,
646198092Srdivacky                          diag::err_value_init_for_array_type) << FullRange);
647198092Srdivacky  if (!Ty->isVoidType() &&
648198092Srdivacky      RequireCompleteType(TyBeginLoc, Ty,
649198092Srdivacky                          PDiag(diag::err_invalid_incomplete_type_use)
650198092Srdivacky                            << FullRange))
651198092Srdivacky    return ExprError();
652218893Sdim
653198092Srdivacky  if (RequireNonAbstractType(TyBeginLoc, Ty,
654198092Srdivacky                             diag::err_allocation_of_abstract_type))
655198092Srdivacky    return ExprError();
656198092Srdivacky
657198092Srdivacky
658193326Sed  // C++ [expr.type.conv]p1:
659193326Sed  // If the expression list is a single expression, the type conversion
660193326Sed  // expression is equivalent (in definedness, and if defined in meaning) to the
661193326Sed  // corresponding cast expression.
662193326Sed  //
663193326Sed  if (NumExprs == 1) {
664218893Sdim    CastKind Kind = CK_Invalid;
665218893Sdim    ExprValueKind VK = VK_RValue;
666212904Sdim    CXXCastPath BasePath;
667218893Sdim    if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
668218893Sdim                       Kind, VK, BasePath,
669198092Srdivacky                       /*FunctionalStyle=*/true))
670193326Sed      return ExprError();
671198092Srdivacky
672193326Sed    exprs.release();
673198092Srdivacky
674212904Sdim    return Owned(CXXFunctionalCastExpr::Create(Context,
675218893Sdim                                               Ty.getNonLValueExprType(Context),
676218893Sdim                                               VK, TInfo, TyBeginLoc, Kind,
677212904Sdim                                               Exprs[0], &BasePath,
678212904Sdim                                               RParenLoc));
679193326Sed  }
680193326Sed
681218893Sdim  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
682218893Sdim  InitializationKind Kind
683218893Sdim    = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
684218893Sdim                                                  LParenLoc, RParenLoc)
685218893Sdim               : InitializationKind::CreateValue(TyBeginLoc,
686218893Sdim                                                 LParenLoc, RParenLoc);
687218893Sdim  InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
688218893Sdim  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
689193326Sed
690218893Sdim  // FIXME: Improve AST representation?
691218893Sdim  return move(Result);
692218893Sdim}
693218893Sdim
694218893Sdim/// doesUsualArrayDeleteWantSize - Answers whether the usual
695218893Sdim/// operator delete[] for the given type has a size_t parameter.
696218893Sdimstatic bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
697218893Sdim                                         QualType allocType) {
698218893Sdim  const RecordType *record =
699218893Sdim    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
700218893Sdim  if (!record) return false;
701218893Sdim
702218893Sdim  // Try to find an operator delete[] in class scope.
703218893Sdim
704218893Sdim  DeclarationName deleteName =
705218893Sdim    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
706218893Sdim  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
707218893Sdim  S.LookupQualifiedName(ops, record->getDecl());
708218893Sdim
709218893Sdim  // We're just doing this for information.
710218893Sdim  ops.suppressDiagnostics();
711218893Sdim
712218893Sdim  // Very likely: there's no operator delete[].
713218893Sdim  if (ops.empty()) return false;
714218893Sdim
715218893Sdim  // If it's ambiguous, it should be illegal to call operator delete[]
716218893Sdim  // on this thing, so it doesn't matter if we allocate extra space or not.
717218893Sdim  if (ops.isAmbiguous()) return false;
718218893Sdim
719218893Sdim  LookupResult::Filter filter = ops.makeFilter();
720218893Sdim  while (filter.hasNext()) {
721218893Sdim    NamedDecl *del = filter.next()->getUnderlyingDecl();
722218893Sdim
723218893Sdim    // C++0x [basic.stc.dynamic.deallocation]p2:
724218893Sdim    //   A template instance is never a usual deallocation function,
725218893Sdim    //   regardless of its signature.
726218893Sdim    if (isa<FunctionTemplateDecl>(del)) {
727218893Sdim      filter.erase();
728218893Sdim      continue;
729218893Sdim    }
730218893Sdim
731218893Sdim    // C++0x [basic.stc.dynamic.deallocation]p2:
732218893Sdim    //   If class T does not declare [an operator delete[] with one
733218893Sdim    //   parameter] but does declare a member deallocation function
734218893Sdim    //   named operator delete[] with exactly two parameters, the
735218893Sdim    //   second of which has type std::size_t, then this function
736218893Sdim    //   is a usual deallocation function.
737218893Sdim    if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
738218893Sdim      filter.erase();
739218893Sdim      continue;
740218893Sdim    }
741193326Sed  }
742218893Sdim  filter.done();
743193326Sed
744218893Sdim  if (!ops.isSingleResult()) return false;
745193326Sed
746218893Sdim  const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
747218893Sdim  return (del->getNumParams() == 2);
748193326Sed}
749193326Sed
750193326Sed/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
751193326Sed/// @code new (memory) int[size][4] @endcode
752193326Sed/// or
753193326Sed/// @code ::new Foo(23, "hello") @endcode
754193326Sed/// For the interpretation of this heap of arguments, consult the base version.
755212904SdimExprResult
756193326SedSema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
757193326Sed                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
758218893Sdim                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
759193326Sed                  Declarator &D, SourceLocation ConstructorLParen,
760193326Sed                  MultiExprArg ConstructorArgs,
761198092Srdivacky                  SourceLocation ConstructorRParen) {
762218893Sdim  bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
763218893Sdim
764193326Sed  Expr *ArraySize = 0;
765193326Sed  // If the specified type is an array, unwrap it and save the expression.
766193326Sed  if (D.getNumTypeObjects() > 0 &&
767193326Sed      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
768193326Sed    DeclaratorChunk &Chunk = D.getTypeObject(0);
769218893Sdim    if (TypeContainsAuto)
770218893Sdim      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
771218893Sdim        << D.getSourceRange());
772193326Sed    if (Chunk.Arr.hasStatic)
773193326Sed      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
774193326Sed        << D.getSourceRange());
775193326Sed    if (!Chunk.Arr.NumElts)
776193326Sed      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
777193326Sed        << D.getSourceRange());
778198893Srdivacky
779193326Sed    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
780198893Srdivacky    D.DropFirstTypeObject();
781193326Sed  }
782193326Sed
783198092Srdivacky  // Every dimension shall be of constant size.
784198893Srdivacky  if (ArraySize) {
785198893Srdivacky    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
786198092Srdivacky      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
787198092Srdivacky        break;
788193326Sed
789198092Srdivacky      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
790198092Srdivacky      if (Expr *NumElts = (Expr *)Array.NumElts) {
791198092Srdivacky        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
792198092Srdivacky            !NumElts->isIntegerConstantExpr(Context)) {
793198092Srdivacky          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
794198092Srdivacky            << NumElts->getSourceRange();
795198092Srdivacky          return ExprError();
796198092Srdivacky        }
797198092Srdivacky      }
798193326Sed    }
799193326Sed  }
800198893Srdivacky
801218893Sdim  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
802218893Sdim                                               /*AllowAuto=*/true);
803210299Sed  QualType AllocType = TInfo->getType();
804198092Srdivacky  if (D.isInvalidType())
805198092Srdivacky    return ExprError();
806218893Sdim
807198092Srdivacky  return BuildCXXNew(StartLoc, UseGlobal,
808193326Sed                     PlacementLParen,
809198092Srdivacky                     move(PlacementArgs),
810193326Sed                     PlacementRParen,
811210299Sed                     TypeIdParens,
812198092Srdivacky                     AllocType,
813218893Sdim                     TInfo,
814212904Sdim                     ArraySize,
815193326Sed                     ConstructorLParen,
816193326Sed                     move(ConstructorArgs),
817218893Sdim                     ConstructorRParen,
818218893Sdim                     TypeContainsAuto);
819193326Sed}
820193326Sed
821212904SdimExprResult
822193326SedSema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
823193326Sed                  SourceLocation PlacementLParen,
824193326Sed                  MultiExprArg PlacementArgs,
825193326Sed                  SourceLocation PlacementRParen,
826210299Sed                  SourceRange TypeIdParens,
827193326Sed                  QualType AllocType,
828218893Sdim                  TypeSourceInfo *AllocTypeInfo,
829212904Sdim                  Expr *ArraySize,
830193326Sed                  SourceLocation ConstructorLParen,
831193326Sed                  MultiExprArg ConstructorArgs,
832218893Sdim                  SourceLocation ConstructorRParen,
833218893Sdim                  bool TypeMayContainAuto) {
834218893Sdim  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
835193326Sed
836218893Sdim  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
837218893Sdim  if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
838218893Sdim    if (ConstructorArgs.size() == 0)
839218893Sdim      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
840218893Sdim                       << AllocType << TypeRange);
841218893Sdim    if (ConstructorArgs.size() != 1) {
842218893Sdim      Expr *FirstBad = ConstructorArgs.get()[1];
843218893Sdim      return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
844218893Sdim                            diag::err_auto_new_ctor_multiple_expressions)
845218893Sdim                       << AllocType << TypeRange);
846218893Sdim    }
847218893Sdim    QualType DeducedType;
848218893Sdim    if (!DeduceAutoType(AllocType, ConstructorArgs.get()[0], DeducedType))
849218893Sdim      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
850218893Sdim                       << AllocType
851218893Sdim                       << ConstructorArgs.get()[0]->getType()
852218893Sdim                       << TypeRange
853218893Sdim                       << ConstructorArgs.get()[0]->getSourceRange());
854218893Sdim
855218893Sdim    AllocType = DeducedType;
856218893Sdim    AllocTypeInfo = Context.getTrivialTypeSourceInfo(AllocType, StartLoc);
857218893Sdim  }
858218893Sdim
859208600Srdivacky  // Per C++0x [expr.new]p5, the type being constructed may be a
860208600Srdivacky  // typedef of an array type.
861212904Sdim  if (!ArraySize) {
862208600Srdivacky    if (const ConstantArrayType *Array
863208600Srdivacky                              = Context.getAsConstantArrayType(AllocType)) {
864212904Sdim      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
865212904Sdim                                         Context.getSizeType(),
866212904Sdim                                         TypeRange.getEnd());
867208600Srdivacky      AllocType = Array->getElementType();
868208600Srdivacky    }
869208600Srdivacky  }
870208600Srdivacky
871218893Sdim  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
872218893Sdim    return ExprError();
873218893Sdim
874193326Sed  QualType ResultType = Context.getPointerType(AllocType);
875193326Sed
876193326Sed  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
877193326Sed  //   or enumeration type with a non-negative value."
878193326Sed  if (ArraySize && !ArraySize->isTypeDependent()) {
879218893Sdim
880193326Sed    QualType SizeType = ArraySize->getType();
881218893Sdim
882212904Sdim    ExprResult ConvertedSize
883212904Sdim      = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
884210299Sed                                       PDiag(diag::err_array_size_not_integral),
885210299Sed                                     PDiag(diag::err_array_size_incomplete_type)
886210299Sed                                       << ArraySize->getSourceRange(),
887210299Sed                               PDiag(diag::err_array_size_explicit_conversion),
888210299Sed                                       PDiag(diag::note_array_size_conversion),
889210299Sed                               PDiag(diag::err_array_size_ambiguous_conversion),
890210299Sed                                       PDiag(diag::note_array_size_conversion),
891218893Sdim                          PDiag(getLangOptions().CPlusPlus0x? 0
892210299Sed                                            : diag::ext_array_size_conversion));
893210299Sed    if (ConvertedSize.isInvalid())
894210299Sed      return ExprError();
895218893Sdim
896212904Sdim    ArraySize = ConvertedSize.take();
897210299Sed    SizeType = ArraySize->getType();
898218893Sdim    if (!SizeType->isIntegralOrUnscopedEnumerationType())
899210299Sed      return ExprError();
900218893Sdim
901193326Sed    // Let's see if this is a constant < 0. If so, we reject it out of hand.
902193326Sed    // We don't care about special rules, so we tell the machinery it's not
903193326Sed    // evaluated - it gives us a result in more cases.
904193326Sed    if (!ArraySize->isValueDependent()) {
905193326Sed      llvm::APSInt Value;
906193326Sed      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
907193326Sed        if (Value < llvm::APSInt(
908218893Sdim                        llvm::APInt::getNullValue(Value.getBitWidth()),
909198092Srdivacky                                 Value.isUnsigned()))
910193326Sed          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
911212904Sdim                                diag::err_typecheck_negative_array_size)
912193326Sed            << ArraySize->getSourceRange());
913218893Sdim
914212904Sdim        if (!AllocType->isDependentType()) {
915212904Sdim          unsigned ActiveSizeBits
916212904Sdim            = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
917212904Sdim          if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
918218893Sdim            Diag(ArraySize->getSourceRange().getBegin(),
919212904Sdim                 diag::err_array_too_large)
920212904Sdim              << Value.toString(10)
921212904Sdim              << ArraySize->getSourceRange();
922212904Sdim            return ExprError();
923212904Sdim          }
924212904Sdim        }
925210299Sed      } else if (TypeIdParens.isValid()) {
926210299Sed        // Can't have dynamic array size when the type-id is in parentheses.
927210299Sed        Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
928210299Sed          << ArraySize->getSourceRange()
929210299Sed          << FixItHint::CreateRemoval(TypeIdParens.getBegin())
930210299Sed          << FixItHint::CreateRemoval(TypeIdParens.getEnd());
931218893Sdim
932210299Sed        TypeIdParens = SourceRange();
933193326Sed      }
934193326Sed    }
935218893Sdim
936198398Srdivacky    ImpCastExprToType(ArraySize, Context.getSizeType(),
937212904Sdim                      CK_IntegralCast);
938193326Sed  }
939193326Sed
940193326Sed  FunctionDecl *OperatorNew = 0;
941193326Sed  FunctionDecl *OperatorDelete = 0;
942193326Sed  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
943193326Sed  unsigned NumPlaceArgs = PlacementArgs.size();
944218893Sdim
945193326Sed  if (!AllocType->isDependentType() &&
946193326Sed      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
947193326Sed      FindAllocationFunctions(StartLoc,
948193326Sed                              SourceRange(PlacementLParen, PlacementRParen),
949193326Sed                              UseGlobal, AllocType, ArraySize, PlaceArgs,
950193326Sed                              NumPlaceArgs, OperatorNew, OperatorDelete))
951193326Sed    return ExprError();
952218893Sdim
953218893Sdim  // If this is an array allocation, compute whether the usual array
954218893Sdim  // deallocation function for the type has a size_t parameter.
955218893Sdim  bool UsualArrayDeleteWantsSize = false;
956218893Sdim  if (ArraySize && !AllocType->isDependentType())
957218893Sdim    UsualArrayDeleteWantsSize
958218893Sdim      = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
959218893Sdim
960199990Srdivacky  llvm::SmallVector<Expr *, 8> AllPlaceArgs;
961199990Srdivacky  if (OperatorNew) {
962199990Srdivacky    // Add default arguments, if any.
963218893Sdim    const FunctionProtoType *Proto =
964199990Srdivacky      OperatorNew->getType()->getAs<FunctionProtoType>();
965218893Sdim    VariadicCallType CallType =
966199990Srdivacky      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
967218893Sdim
968207619Srdivacky    if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
969218893Sdim                               Proto, 1, PlaceArgs, NumPlaceArgs,
970207619Srdivacky                               AllPlaceArgs, CallType))
971199990Srdivacky      return ExprError();
972218893Sdim
973199990Srdivacky    NumPlaceArgs = AllPlaceArgs.size();
974199990Srdivacky    if (NumPlaceArgs > 0)
975199990Srdivacky      PlaceArgs = &AllPlaceArgs[0];
976199990Srdivacky  }
977218893Sdim
978193326Sed  bool Init = ConstructorLParen.isValid();
979193326Sed  // --- Choosing a constructor ---
980193326Sed  CXXConstructorDecl *Constructor = 0;
981193326Sed  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
982193326Sed  unsigned NumConsArgs = ConstructorArgs.size();
983212904Sdim  ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
984199482Srdivacky
985207619Srdivacky  // Array 'new' can't have any initializers.
986208600Srdivacky  if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
987207619Srdivacky    SourceRange InitRange(ConsArgs[0]->getLocStart(),
988207619Srdivacky                          ConsArgs[NumConsArgs - 1]->getLocEnd());
989218893Sdim
990207619Srdivacky    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
991207619Srdivacky    return ExprError();
992207619Srdivacky  }
993207619Srdivacky
994201361Srdivacky  if (!AllocType->isDependentType() &&
995201361Srdivacky      !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
996201361Srdivacky    // C++0x [expr.new]p15:
997201361Srdivacky    //   A new-expression that creates an object of type T initializes that
998201361Srdivacky    //   object as follows:
999201361Srdivacky    InitializationKind Kind
1000201361Srdivacky    //     - If the new-initializer is omitted, the object is default-
1001201361Srdivacky    //       initialized (8.5); if no initialization is performed,
1002201361Srdivacky    //       the object has indeterminate value
1003218893Sdim      = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
1004218893Sdim    //     - Otherwise, the new-initializer is interpreted according to the
1005201361Srdivacky    //       initialization rules of 8.5 for direct-initialization.
1006218893Sdim             : InitializationKind::CreateDirect(TypeRange.getBegin(),
1007218893Sdim                                                ConstructorLParen,
1008201361Srdivacky                                                ConstructorRParen);
1009218893Sdim
1010201361Srdivacky    InitializedEntity Entity
1011201361Srdivacky      = InitializedEntity::InitializeNew(StartLoc, AllocType);
1012201361Srdivacky    InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
1013218893Sdim    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1014201361Srdivacky                                                move(ConstructorArgs));
1015201361Srdivacky    if (FullInit.isInvalid())
1016193326Sed      return ExprError();
1017218893Sdim
1018218893Sdim    // FullInit is our initializer; walk through it to determine if it's a
1019201361Srdivacky    // constructor call, which CXXNewExpr handles directly.
1020201361Srdivacky    if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1021201361Srdivacky      if (CXXBindTemporaryExpr *Binder
1022201361Srdivacky            = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1023201361Srdivacky        FullInitExpr = Binder->getSubExpr();
1024201361Srdivacky      if (CXXConstructExpr *Construct
1025201361Srdivacky                    = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1026201361Srdivacky        Constructor = Construct->getConstructor();
1027201361Srdivacky        for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1028201361Srdivacky                                         AEnd = Construct->arg_end();
1029201361Srdivacky             A != AEnd; ++A)
1030218893Sdim          ConvertedConstructorArgs.push_back(*A);
1031201361Srdivacky      } else {
1032201361Srdivacky        // Take the converted initializer.
1033201361Srdivacky        ConvertedConstructorArgs.push_back(FullInit.release());
1034201361Srdivacky      }
1035201361Srdivacky    } else {
1036201361Srdivacky      // No initialization required.
1037201361Srdivacky    }
1038218893Sdim
1039201361Srdivacky    // Take the converted arguments and use them for the new expression.
1040198092Srdivacky    NumConsArgs = ConvertedConstructorArgs.size();
1041198092Srdivacky    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
1042193326Sed  }
1043218893Sdim
1044204643Srdivacky  // Mark the new and delete operators as referenced.
1045204643Srdivacky  if (OperatorNew)
1046204643Srdivacky    MarkDeclarationReferenced(StartLoc, OperatorNew);
1047204643Srdivacky  if (OperatorDelete)
1048204643Srdivacky    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1049204643Srdivacky
1050193326Sed  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
1051218893Sdim
1052193326Sed  PlacementArgs.release();
1053193326Sed  ConstructorArgs.release();
1054218893Sdim
1055203955Srdivacky  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1056210299Sed                                        PlaceArgs, NumPlaceArgs, TypeIdParens,
1057203955Srdivacky                                        ArraySize, Constructor, Init,
1058203955Srdivacky                                        ConsArgs, NumConsArgs, OperatorDelete,
1059218893Sdim                                        UsualArrayDeleteWantsSize,
1060218893Sdim                                        ResultType, AllocTypeInfo,
1061218893Sdim                                        StartLoc,
1062203955Srdivacky                                        Init ? ConstructorRParen :
1063218893Sdim                                               TypeRange.getEnd(),
1064218893Sdim                                        ConstructorLParen, ConstructorRParen));
1065193326Sed}
1066193326Sed
1067193326Sed/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1068193326Sed/// in a new-expression.
1069193326Sed/// dimension off and stores the size expression in ArraySize.
1070193326Sedbool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1071198092Srdivacky                              SourceRange R) {
1072193326Sed  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1073193326Sed  //   abstract class type or array thereof.
1074193326Sed  if (AllocType->isFunctionType())
1075193326Sed    return Diag(Loc, diag::err_bad_new_type)
1076193326Sed      << AllocType << 0 << R;
1077193326Sed  else if (AllocType->isReferenceType())
1078193326Sed    return Diag(Loc, diag::err_bad_new_type)
1079193326Sed      << AllocType << 1 << R;
1080193326Sed  else if (!AllocType->isDependentType() &&
1081193326Sed           RequireCompleteType(Loc, AllocType,
1082198092Srdivacky                               PDiag(diag::err_new_incomplete_type)
1083198092Srdivacky                                 << R))
1084193326Sed    return true;
1085193326Sed  else if (RequireNonAbstractType(Loc, AllocType,
1086193326Sed                                  diag::err_allocation_of_abstract_type))
1087193326Sed    return true;
1088218893Sdim  else if (AllocType->isVariablyModifiedType())
1089218893Sdim    return Diag(Loc, diag::err_variably_modified_new_type)
1090218893Sdim             << AllocType;
1091193326Sed
1092193326Sed  return false;
1093193326Sed}
1094193326Sed
1095204643Srdivacky/// \brief Determine whether the given function is a non-placement
1096204643Srdivacky/// deallocation function.
1097204643Srdivackystatic bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1098204643Srdivacky  if (FD->isInvalidDecl())
1099204643Srdivacky    return false;
1100204643Srdivacky
1101204643Srdivacky  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1102204643Srdivacky    return Method->isUsualDeallocationFunction();
1103204643Srdivacky
1104204643Srdivacky  return ((FD->getOverloadedOperator() == OO_Delete ||
1105204643Srdivacky           FD->getOverloadedOperator() == OO_Array_Delete) &&
1106204643Srdivacky          FD->getNumParams() == 1);
1107204643Srdivacky}
1108204643Srdivacky
1109193326Sed/// FindAllocationFunctions - Finds the overloads of operator new and delete
1110193326Sed/// that are appropriate for the allocation.
1111193326Sedbool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1112193326Sed                                   bool UseGlobal, QualType AllocType,
1113193326Sed                                   bool IsArray, Expr **PlaceArgs,
1114193326Sed                                   unsigned NumPlaceArgs,
1115193326Sed                                   FunctionDecl *&OperatorNew,
1116198092Srdivacky                                   FunctionDecl *&OperatorDelete) {
1117193326Sed  // --- Choosing an allocation function ---
1118193326Sed  // C++ 5.3.4p8 - 14 & 18
1119193326Sed  // 1) If UseGlobal is true, only look in the global scope. Else, also look
1120193326Sed  //   in the scope of the allocated class.
1121193326Sed  // 2) If an array size is given, look for operator new[], else look for
1122193326Sed  //   operator new.
1123193326Sed  // 3) The first argument is always size_t. Append the arguments from the
1124193326Sed  //   placement form.
1125193326Sed
1126193326Sed  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1127193326Sed  // We don't care about the actual value of this argument.
1128193326Sed  // FIXME: Should the Sema create the expression and embed it in the syntax
1129193326Sed  // tree? Or should the consumer just recalculate the value?
1130212904Sdim  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1131198092Srdivacky                      Context.Target.getPointerWidth(0)),
1132198092Srdivacky                      Context.getSizeType(),
1133198092Srdivacky                      SourceLocation());
1134198092Srdivacky  AllocArgs[0] = &Size;
1135193326Sed  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1136193326Sed
1137204643Srdivacky  // C++ [expr.new]p8:
1138204643Srdivacky  //   If the allocated type is a non-array type, the allocation
1139218893Sdim  //   function's name is operator new and the deallocation function's
1140204643Srdivacky  //   name is operator delete. If the allocated type is an array
1141218893Sdim  //   type, the allocation function's name is operator new[] and the
1142218893Sdim  //   deallocation function's name is operator delete[].
1143193326Sed  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1144193326Sed                                        IsArray ? OO_Array_New : OO_New);
1145204643Srdivacky  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1146204643Srdivacky                                        IsArray ? OO_Array_Delete : OO_Delete);
1147204643Srdivacky
1148212904Sdim  QualType AllocElemType = Context.getBaseElementType(AllocType);
1149212904Sdim
1150212904Sdim  if (AllocElemType->isRecordType() && !UseGlobal) {
1151198092Srdivacky    CXXRecordDecl *Record
1152212904Sdim      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1153193326Sed    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1154193326Sed                          AllocArgs.size(), Record, /*AllowMissing=*/true,
1155193326Sed                          OperatorNew))
1156193326Sed      return true;
1157193326Sed  }
1158193326Sed  if (!OperatorNew) {
1159193326Sed    // Didn't find a member overload. Look for a global one.
1160193326Sed    DeclareGlobalNewDelete();
1161193326Sed    DeclContext *TUDecl = Context.getTranslationUnitDecl();
1162193326Sed    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1163193326Sed                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1164193326Sed                          OperatorNew))
1165193326Sed      return true;
1166193326Sed  }
1167193326Sed
1168207619Srdivacky  // We don't need an operator delete if we're running under
1169207619Srdivacky  // -fno-exceptions.
1170207619Srdivacky  if (!getLangOptions().Exceptions) {
1171207619Srdivacky    OperatorDelete = 0;
1172207619Srdivacky    return false;
1173207619Srdivacky  }
1174207619Srdivacky
1175193326Sed  // FindAllocationOverload can change the passed in arguments, so we need to
1176193326Sed  // copy them back.
1177193326Sed  if (NumPlaceArgs > 0)
1178193326Sed    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
1179198092Srdivacky
1180204643Srdivacky  // C++ [expr.new]p19:
1181204643Srdivacky  //
1182204643Srdivacky  //   If the new-expression begins with a unary :: operator, the
1183218893Sdim  //   deallocation function's name is looked up in the global
1184204643Srdivacky  //   scope. Otherwise, if the allocated type is a class type T or an
1185218893Sdim  //   array thereof, the deallocation function's name is looked up in
1186204643Srdivacky  //   the scope of T. If this lookup fails to find the name, or if
1187204643Srdivacky  //   the allocated type is not a class type or array thereof, the
1188218893Sdim  //   deallocation function's name is looked up in the global scope.
1189204643Srdivacky  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1190212904Sdim  if (AllocElemType->isRecordType() && !UseGlobal) {
1191204643Srdivacky    CXXRecordDecl *RD
1192212904Sdim      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1193204643Srdivacky    LookupQualifiedName(FoundDelete, RD);
1194204643Srdivacky  }
1195205408Srdivacky  if (FoundDelete.isAmbiguous())
1196205408Srdivacky    return true; // FIXME: clean up expressions?
1197204643Srdivacky
1198204643Srdivacky  if (FoundDelete.empty()) {
1199204643Srdivacky    DeclareGlobalNewDelete();
1200204643Srdivacky    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1201204643Srdivacky  }
1202204643Srdivacky
1203204643Srdivacky  FoundDelete.suppressDiagnostics();
1204205408Srdivacky
1205205408Srdivacky  llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1206205408Srdivacky
1207218893Sdim  // Whether we're looking for a placement operator delete is dictated
1208218893Sdim  // by whether we selected a placement operator new, not by whether
1209218893Sdim  // we had explicit placement arguments.  This matters for things like
1210218893Sdim  //   struct A { void *operator new(size_t, int = 0); ... };
1211218893Sdim  //   A *a = new A()
1212218893Sdim  bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1213218893Sdim
1214218893Sdim  if (isPlacementNew) {
1215204643Srdivacky    // C++ [expr.new]p20:
1216204643Srdivacky    //   A declaration of a placement deallocation function matches the
1217204643Srdivacky    //   declaration of a placement allocation function if it has the
1218204643Srdivacky    //   same number of parameters and, after parameter transformations
1219204643Srdivacky    //   (8.3.5), all parameter types except the first are
1220204643Srdivacky    //   identical. [...]
1221218893Sdim    //
1222204643Srdivacky    // To perform this comparison, we compute the function type that
1223204643Srdivacky    // the deallocation function should have, and use that type both
1224204643Srdivacky    // for template argument deduction and for comparison purposes.
1225218893Sdim    //
1226218893Sdim    // FIXME: this comparison should ignore CC and the like.
1227204643Srdivacky    QualType ExpectedFunctionType;
1228204643Srdivacky    {
1229204643Srdivacky      const FunctionProtoType *Proto
1230204643Srdivacky        = OperatorNew->getType()->getAs<FunctionProtoType>();
1231218893Sdim
1232204643Srdivacky      llvm::SmallVector<QualType, 4> ArgTypes;
1233218893Sdim      ArgTypes.push_back(Context.VoidPtrTy);
1234204643Srdivacky      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1235204643Srdivacky        ArgTypes.push_back(Proto->getArgType(I));
1236204643Srdivacky
1237218893Sdim      FunctionProtoType::ExtProtoInfo EPI;
1238218893Sdim      EPI.Variadic = Proto->isVariadic();
1239218893Sdim
1240204643Srdivacky      ExpectedFunctionType
1241204643Srdivacky        = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1242218893Sdim                                  ArgTypes.size(), EPI);
1243204643Srdivacky    }
1244204643Srdivacky
1245218893Sdim    for (LookupResult::iterator D = FoundDelete.begin(),
1246204643Srdivacky                             DEnd = FoundDelete.end();
1247204643Srdivacky         D != DEnd; ++D) {
1248204643Srdivacky      FunctionDecl *Fn = 0;
1249218893Sdim      if (FunctionTemplateDecl *FnTmpl
1250204643Srdivacky            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1251204643Srdivacky        // Perform template argument deduction to try to match the
1252204643Srdivacky        // expected function type.
1253204643Srdivacky        TemplateDeductionInfo Info(Context, StartLoc);
1254204643Srdivacky        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1255204643Srdivacky          continue;
1256204643Srdivacky      } else
1257204643Srdivacky        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1258204643Srdivacky
1259204643Srdivacky      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1260205408Srdivacky        Matches.push_back(std::make_pair(D.getPair(), Fn));
1261204643Srdivacky    }
1262204643Srdivacky  } else {
1263204643Srdivacky    // C++ [expr.new]p20:
1264204643Srdivacky    //   [...] Any non-placement deallocation function matches a
1265204643Srdivacky    //   non-placement allocation function. [...]
1266218893Sdim    for (LookupResult::iterator D = FoundDelete.begin(),
1267204643Srdivacky                             DEnd = FoundDelete.end();
1268204643Srdivacky         D != DEnd; ++D) {
1269204643Srdivacky      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1270204643Srdivacky        if (isNonPlacementDeallocationFunction(Fn))
1271205408Srdivacky          Matches.push_back(std::make_pair(D.getPair(), Fn));
1272204643Srdivacky    }
1273204643Srdivacky  }
1274204643Srdivacky
1275204643Srdivacky  // C++ [expr.new]p20:
1276204643Srdivacky  //   [...] If the lookup finds a single matching deallocation
1277204643Srdivacky  //   function, that function will be called; otherwise, no
1278204643Srdivacky  //   deallocation function will be called.
1279204643Srdivacky  if (Matches.size() == 1) {
1280205408Srdivacky    OperatorDelete = Matches[0].second;
1281204643Srdivacky
1282204643Srdivacky    // C++0x [expr.new]p20:
1283204643Srdivacky    //   If the lookup finds the two-parameter form of a usual
1284204643Srdivacky    //   deallocation function (3.7.4.2) and that function, considered
1285204643Srdivacky    //   as a placement deallocation function, would have been
1286204643Srdivacky    //   selected as a match for the allocation function, the program
1287204643Srdivacky    //   is ill-formed.
1288204643Srdivacky    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1289204643Srdivacky        isNonPlacementDeallocationFunction(OperatorDelete)) {
1290204643Srdivacky      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1291218893Sdim        << SourceRange(PlaceArgs[0]->getLocStart(),
1292204643Srdivacky                       PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1293204643Srdivacky      Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1294204643Srdivacky        << DeleteName;
1295205408Srdivacky    } else {
1296205408Srdivacky      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1297205408Srdivacky                            Matches[0].first);
1298204643Srdivacky    }
1299204643Srdivacky  }
1300204643Srdivacky
1301193326Sed  return false;
1302193326Sed}
1303193326Sed
1304193326Sed/// FindAllocationOverload - Find an fitting overload for the allocation
1305193326Sed/// function in the specified scope.
1306193326Sedbool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1307193326Sed                                  DeclarationName Name, Expr** Args,
1308193326Sed                                  unsigned NumArgs, DeclContext *Ctx,
1309198092Srdivacky                                  bool AllowMissing, FunctionDecl *&Operator) {
1310199482Srdivacky  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1311199482Srdivacky  LookupQualifiedName(R, Ctx);
1312198092Srdivacky  if (R.empty()) {
1313193326Sed    if (AllowMissing)
1314193326Sed      return false;
1315193326Sed    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1316193326Sed      << Name << Range;
1317193326Sed  }
1318193326Sed
1319205408Srdivacky  if (R.isAmbiguous())
1320205408Srdivacky    return true;
1321198092Srdivacky
1322205408Srdivacky  R.suppressDiagnostics();
1323205408Srdivacky
1324203955Srdivacky  OverloadCandidateSet Candidates(StartLoc);
1325218893Sdim  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1326198092Srdivacky       Alloc != AllocEnd; ++Alloc) {
1327193326Sed    // Even member operator new/delete are implicitly treated as
1328193326Sed    // static, so don't use AddMemberCandidate.
1329205408Srdivacky    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1330203955Srdivacky
1331205408Srdivacky    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1332205408Srdivacky      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1333203955Srdivacky                                   /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1334203955Srdivacky                                   Candidates,
1335203955Srdivacky                                   /*SuppressUserConversions=*/false);
1336198092Srdivacky      continue;
1337203955Srdivacky    }
1338203955Srdivacky
1339205408Srdivacky    FunctionDecl *Fn = cast<FunctionDecl>(D);
1340205408Srdivacky    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1341203955Srdivacky                         /*SuppressUserConversions=*/false);
1342193326Sed  }
1343193326Sed
1344193326Sed  // Do the resolution.
1345193326Sed  OverloadCandidateSet::iterator Best;
1346212904Sdim  switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1347193326Sed  case OR_Success: {
1348193326Sed    // Got one!
1349193326Sed    FunctionDecl *FnDecl = Best->Function;
1350193326Sed    // The first argument is size_t, and the first parameter must be size_t,
1351193326Sed    // too. This is checked on declaration and can be assumed. (It can't be
1352193326Sed    // asserted on, though, since invalid decls are left in there.)
1353205408Srdivacky    // Watch out for variadic allocator function.
1354199990Srdivacky    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1355199990Srdivacky    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1356212904Sdim      ExprResult Result
1357206084Srdivacky        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1358218893Sdim                                                       Context,
1359206084Srdivacky                                                       FnDecl->getParamDecl(i)),
1360206084Srdivacky                                    SourceLocation(),
1361218893Sdim                                    Owned(Args[i]));
1362206084Srdivacky      if (Result.isInvalid())
1363193326Sed        return true;
1364218893Sdim
1365206084Srdivacky      Args[i] = Result.takeAs<Expr>();
1366193326Sed    }
1367193326Sed    Operator = FnDecl;
1368205408Srdivacky    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1369193326Sed    return false;
1370193326Sed  }
1371193326Sed
1372193326Sed  case OR_No_Viable_Function:
1373193326Sed    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1374193326Sed      << Name << Range;
1375212904Sdim    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1376193326Sed    return true;
1377193326Sed
1378193326Sed  case OR_Ambiguous:
1379193326Sed    Diag(StartLoc, diag::err_ovl_ambiguous_call)
1380193326Sed      << Name << Range;
1381212904Sdim    Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1382193326Sed    return true;
1383193326Sed
1384193326Sed  case OR_Deleted:
1385193326Sed    Diag(StartLoc, diag::err_ovl_deleted_call)
1386193326Sed      << Best->Function->isDeleted()
1387193326Sed      << Name << Range;
1388212904Sdim    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1389193326Sed    return true;
1390193326Sed  }
1391193326Sed  assert(false && "Unreachable, bad result from BestViableFunction");
1392193326Sed  return true;
1393193326Sed}
1394193326Sed
1395193326Sed
1396193326Sed/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1397193326Sed/// delete. These are:
1398193326Sed/// @code
1399193326Sed///   void* operator new(std::size_t) throw(std::bad_alloc);
1400193326Sed///   void* operator new[](std::size_t) throw(std::bad_alloc);
1401193326Sed///   void operator delete(void *) throw();
1402193326Sed///   void operator delete[](void *) throw();
1403193326Sed/// @endcode
1404193326Sed/// Note that the placement and nothrow forms of new are *not* implicitly
1405193326Sed/// declared. Their use requires including \<new\>.
1406198092Srdivackyvoid Sema::DeclareGlobalNewDelete() {
1407193326Sed  if (GlobalNewDeleteDeclared)
1408193326Sed    return;
1409218893Sdim
1410198092Srdivacky  // C++ [basic.std.dynamic]p2:
1411218893Sdim  //   [...] The following allocation and deallocation functions (18.4) are
1412218893Sdim  //   implicitly declared in global scope in each translation unit of a
1413198092Srdivacky  //   program
1414218893Sdim  //
1415198092Srdivacky  //     void* operator new(std::size_t) throw(std::bad_alloc);
1416218893Sdim  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1417218893Sdim  //     void  operator delete(void*) throw();
1418198092Srdivacky  //     void  operator delete[](void*) throw();
1419198092Srdivacky  //
1420218893Sdim  //   These implicit declarations introduce only the function names operator
1421198092Srdivacky  //   new, operator new[], operator delete, operator delete[].
1422198092Srdivacky  //
1423198092Srdivacky  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1424198092Srdivacky  // "std" or "bad_alloc" as necessary to form the exception specification.
1425198092Srdivacky  // However, we do not make these implicit declarations visible to name
1426198092Srdivacky  // lookup.
1427198092Srdivacky  if (!StdBadAlloc) {
1428198092Srdivacky    // The "std::bad_alloc" class has not yet been declared, so build it
1429198092Srdivacky    // implicitly.
1430218893Sdim    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1431218893Sdim                                        getOrCreateStdNamespace(),
1432218893Sdim                                        SourceLocation(),
1433218893Sdim                                      &PP.getIdentifierTable().get("bad_alloc"),
1434198092Srdivacky                                        SourceLocation(), 0);
1435212904Sdim    getStdBadAlloc()->setImplicit(true);
1436198092Srdivacky  }
1437218893Sdim
1438193326Sed  GlobalNewDeleteDeclared = true;
1439193326Sed
1440193326Sed  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1441193326Sed  QualType SizeT = Context.getSizeType();
1442201361Srdivacky  bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1443193326Sed
1444193326Sed  DeclareGlobalAllocationFunction(
1445193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_New),
1446201361Srdivacky      VoidPtr, SizeT, AssumeSaneOperatorNew);
1447193326Sed  DeclareGlobalAllocationFunction(
1448193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1449201361Srdivacky      VoidPtr, SizeT, AssumeSaneOperatorNew);
1450193326Sed  DeclareGlobalAllocationFunction(
1451193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1452193326Sed      Context.VoidTy, VoidPtr);
1453193326Sed  DeclareGlobalAllocationFunction(
1454193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1455193326Sed      Context.VoidTy, VoidPtr);
1456193326Sed}
1457193326Sed
1458193326Sed/// DeclareGlobalAllocationFunction - Declares a single implicit global
1459193326Sed/// allocation function if it doesn't already exist.
1460193326Sedvoid Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1461201361Srdivacky                                           QualType Return, QualType Argument,
1462201361Srdivacky                                           bool AddMallocAttr) {
1463193326Sed  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1464193326Sed
1465193326Sed  // Check if this function is already declared.
1466193326Sed  {
1467193326Sed    DeclContext::lookup_iterator Alloc, AllocEnd;
1468195341Sed    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1469193326Sed         Alloc != AllocEnd; ++Alloc) {
1470203955Srdivacky      // Only look at non-template functions, as it is the predefined,
1471203955Srdivacky      // non-templated allocation function we are trying to declare here.
1472203955Srdivacky      if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1473203955Srdivacky        QualType InitialParamType =
1474201361Srdivacky          Context.getCanonicalType(
1475203955Srdivacky            Func->getParamDecl(0)->getType().getUnqualifiedType());
1476203955Srdivacky        // FIXME: Do we need to check for default arguments here?
1477212904Sdim        if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1478212904Sdim          if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1479212904Sdim            Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1480203955Srdivacky          return;
1481212904Sdim        }
1482203955Srdivacky      }
1483193326Sed    }
1484193326Sed  }
1485193326Sed
1486198092Srdivacky  QualType BadAllocType;
1487218893Sdim  bool HasBadAllocExceptionSpec
1488198092Srdivacky    = (Name.getCXXOverloadedOperator() == OO_New ||
1489198092Srdivacky       Name.getCXXOverloadedOperator() == OO_Array_New);
1490198092Srdivacky  if (HasBadAllocExceptionSpec) {
1491198092Srdivacky    assert(StdBadAlloc && "Must have std::bad_alloc declared");
1492212904Sdim    BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1493198092Srdivacky  }
1494218893Sdim
1495218893Sdim  FunctionProtoType::ExtProtoInfo EPI;
1496218893Sdim  EPI.HasExceptionSpec = true;
1497218893Sdim  if (HasBadAllocExceptionSpec) {
1498218893Sdim    EPI.NumExceptions = 1;
1499218893Sdim    EPI.Exceptions = &BadAllocType;
1500218893Sdim  }
1501218893Sdim
1502218893Sdim  QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
1503193326Sed  FunctionDecl *Alloc =
1504193326Sed    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
1505212904Sdim                         FnType, /*TInfo=*/0, SC_None,
1506212904Sdim                         SC_None, false, true);
1507193326Sed  Alloc->setImplicit();
1508218893Sdim
1509201361Srdivacky  if (AddMallocAttr)
1510212904Sdim    Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1511218893Sdim
1512193326Sed  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1513200583Srdivacky                                           0, Argument, /*TInfo=*/0,
1514212904Sdim                                           SC_None,
1515212904Sdim                                           SC_None, 0);
1516203955Srdivacky  Alloc->setParams(&Param, 1);
1517193326Sed
1518193326Sed  // FIXME: Also add this declaration to the IdentifierResolver, but
1519193326Sed  // make sure it is at the end of the chain to coincide with the
1520193326Sed  // global scope.
1521212904Sdim  Context.getTranslationUnitDecl()->addDecl(Alloc);
1522193326Sed}
1523193326Sed
1524199482Srdivackybool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1525199482Srdivacky                                    DeclarationName Name,
1526199482Srdivacky                                    FunctionDecl* &Operator) {
1527199482Srdivacky  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1528199482Srdivacky  // Try to find operator delete/operator delete[] in class scope.
1529199482Srdivacky  LookupQualifiedName(Found, RD);
1530218893Sdim
1531199482Srdivacky  if (Found.isAmbiguous())
1532199482Srdivacky    return true;
1533199482Srdivacky
1534210299Sed  Found.suppressDiagnostics();
1535210299Sed
1536212904Sdim  llvm::SmallVector<DeclAccessPair,4> Matches;
1537199482Srdivacky  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1538199482Srdivacky       F != FEnd; ++F) {
1539212904Sdim    NamedDecl *ND = (*F)->getUnderlyingDecl();
1540212904Sdim
1541212904Sdim    // Ignore template operator delete members from the check for a usual
1542212904Sdim    // deallocation function.
1543212904Sdim    if (isa<FunctionTemplateDecl>(ND))
1544212904Sdim      continue;
1545212904Sdim
1546212904Sdim    if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1547212904Sdim      Matches.push_back(F.getPair());
1548199482Srdivacky  }
1549199482Srdivacky
1550212904Sdim  // There's exactly one suitable operator;  pick it.
1551212904Sdim  if (Matches.size() == 1) {
1552212904Sdim    Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1553212904Sdim    CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1554212904Sdim                          Matches[0]);
1555212904Sdim    return false;
1556212904Sdim
1557212904Sdim  // We found multiple suitable operators;  complain about the ambiguity.
1558212904Sdim  } else if (!Matches.empty()) {
1559212904Sdim    Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1560212904Sdim      << Name << RD;
1561212904Sdim
1562212904Sdim    for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1563212904Sdim           F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1564212904Sdim      Diag((*F)->getUnderlyingDecl()->getLocation(),
1565212904Sdim           diag::note_member_declared_here) << Name;
1566212904Sdim    return true;
1567212904Sdim  }
1568212904Sdim
1569199482Srdivacky  // We did find operator delete/operator delete[] declarations, but
1570199482Srdivacky  // none of them were suitable.
1571199482Srdivacky  if (!Found.empty()) {
1572199482Srdivacky    Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1573199482Srdivacky      << Name << RD;
1574218893Sdim
1575199482Srdivacky    for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1576212904Sdim         F != FEnd; ++F)
1577212904Sdim      Diag((*F)->getUnderlyingDecl()->getLocation(),
1578212904Sdim           diag::note_member_declared_here) << Name;
1579199482Srdivacky
1580199482Srdivacky    return true;
1581199482Srdivacky  }
1582199482Srdivacky
1583199482Srdivacky  // Look for a global declaration.
1584199482Srdivacky  DeclareGlobalNewDelete();
1585199482Srdivacky  DeclContext *TUDecl = Context.getTranslationUnitDecl();
1586218893Sdim
1587199482Srdivacky  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1588199482Srdivacky  Expr* DeallocArgs[1];
1589199482Srdivacky  DeallocArgs[0] = &Null;
1590199482Srdivacky  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1591199482Srdivacky                             DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1592199482Srdivacky                             Operator))
1593199482Srdivacky    return true;
1594199482Srdivacky
1595199482Srdivacky  assert(Operator && "Did not find a deallocation function!");
1596199482Srdivacky  return false;
1597199482Srdivacky}
1598199482Srdivacky
1599193326Sed/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1600193326Sed/// @code ::delete ptr; @endcode
1601193326Sed/// or
1602193326Sed/// @code delete [] ptr; @endcode
1603212904SdimExprResult
1604193326SedSema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1605212904Sdim                     bool ArrayForm, Expr *Ex) {
1606198092Srdivacky  // C++ [expr.delete]p1:
1607198092Srdivacky  //   The operand shall have a pointer type, or a class type having a single
1608198092Srdivacky  //   conversion function to a pointer type. The result has type void.
1609198092Srdivacky  //
1610193326Sed  // DR599 amends "pointer type" to "pointer to object type" in both cases.
1611193326Sed
1612198092Srdivacky  FunctionDecl *OperatorDelete = 0;
1613218893Sdim  bool ArrayFormAsWritten = ArrayForm;
1614218893Sdim  bool UsualArrayDeleteWantsSize = false;
1615198092Srdivacky
1616193326Sed  if (!Ex->isTypeDependent()) {
1617193326Sed    QualType Type = Ex->getType();
1618193326Sed
1619198092Srdivacky    if (const RecordType *Record = Type->getAs<RecordType>()) {
1620218893Sdim      if (RequireCompleteType(StartLoc, Type,
1621212904Sdim                              PDiag(diag::err_delete_incomplete_class_type)))
1622212904Sdim        return ExprError();
1623218893Sdim
1624206084Srdivacky      llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1625206084Srdivacky
1626198092Srdivacky      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1627218893Sdim      const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1628202879Srdivacky      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1629199990Srdivacky             E = Conversions->end(); I != E; ++I) {
1630206084Srdivacky        NamedDecl *D = I.getDecl();
1631206084Srdivacky        if (isa<UsingShadowDecl>(D))
1632206084Srdivacky          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1633206084Srdivacky
1634198092Srdivacky        // Skip over templated conversion functions; they aren't considered.
1635206084Srdivacky        if (isa<FunctionTemplateDecl>(D))
1636198092Srdivacky          continue;
1637218893Sdim
1638206084Srdivacky        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1639218893Sdim
1640198092Srdivacky        QualType ConvType = Conv->getConversionType().getNonReferenceType();
1641198092Srdivacky        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1642212904Sdim          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
1643198092Srdivacky            ObjectPtrConversions.push_back(Conv);
1644198092Srdivacky      }
1645198092Srdivacky      if (ObjectPtrConversions.size() == 1) {
1646198092Srdivacky        // We have a single conversion to a pointer-to-object type. Perform
1647198092Srdivacky        // that conversion.
1648206084Srdivacky        // TODO: don't redo the conversion calculation.
1649206084Srdivacky        if (!PerformImplicitConversion(Ex,
1650206084Srdivacky                            ObjectPtrConversions.front()->getConversionType(),
1651201361Srdivacky                                      AA_Converting)) {
1652198092Srdivacky          Type = Ex->getType();
1653198092Srdivacky        }
1654198092Srdivacky      }
1655198092Srdivacky      else if (ObjectPtrConversions.size() > 1) {
1656198092Srdivacky        Diag(StartLoc, diag::err_ambiguous_delete_operand)
1657198092Srdivacky              << Type << Ex->getSourceRange();
1658206084Srdivacky        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1659206084Srdivacky          NoteOverloadCandidate(ObjectPtrConversions[i]);
1660198092Srdivacky        return ExprError();
1661198092Srdivacky      }
1662193326Sed    }
1663193326Sed
1664193326Sed    if (!Type->isPointerType())
1665193326Sed      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1666193326Sed        << Type << Ex->getSourceRange());
1667193326Sed
1668198092Srdivacky    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1669208600Srdivacky    if (Pointee->isVoidType() && !isSFINAEContext()) {
1670218893Sdim      // The C++ standard bans deleting a pointer to a non-object type, which
1671208600Srdivacky      // effectively bans deletion of "void*". However, most compilers support
1672208600Srdivacky      // this, so we treat it as a warning unless we're in a SFINAE context.
1673208600Srdivacky      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1674208600Srdivacky        << Type << Ex->getSourceRange();
1675208600Srdivacky    } else if (Pointee->isFunctionType() || Pointee->isVoidType())
1676193326Sed      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1677193326Sed        << Type << Ex->getSourceRange());
1678193326Sed    else if (!Pointee->isDependentType() &&
1679198092Srdivacky             RequireCompleteType(StartLoc, Pointee,
1680198092Srdivacky                                 PDiag(diag::warn_delete_incomplete)
1681198092Srdivacky                                   << Ex->getSourceRange()))
1682193326Sed      return ExprError();
1683193326Sed
1684198092Srdivacky    // C++ [expr.delete]p2:
1685218893Sdim    //   [Note: a pointer to a const type can be the operand of a
1686218893Sdim    //   delete-expression; it is not necessary to cast away the constness
1687218893Sdim    //   (5.2.11) of the pointer expression before it is used as the operand
1688198092Srdivacky    //   of the delete-expression. ]
1689218893Sdim    ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1690212904Sdim                      CK_NoOp);
1691218893Sdim
1692218893Sdim    if (Pointee->isArrayType() && !ArrayForm) {
1693218893Sdim      Diag(StartLoc, diag::warn_delete_array_type)
1694218893Sdim          << Type << Ex->getSourceRange()
1695218893Sdim          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1696218893Sdim      ArrayForm = true;
1697218893Sdim    }
1698218893Sdim
1699198092Srdivacky    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1700198092Srdivacky                                      ArrayForm ? OO_Array_Delete : OO_Delete);
1701198092Srdivacky
1702212904Sdim    QualType PointeeElem = Context.getBaseElementType(Pointee);
1703212904Sdim    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1704199482Srdivacky      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1705199482Srdivacky
1706218893Sdim      if (!UseGlobal &&
1707199482Srdivacky          FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1708199482Srdivacky        return ExprError();
1709218893Sdim
1710218893Sdim      // If we're allocating an array of records, check whether the
1711218893Sdim      // usual operator delete[] has a size_t parameter.
1712218893Sdim      if (ArrayForm) {
1713218893Sdim        // If the user specifically asked to use the global allocator,
1714218893Sdim        // we'll need to do the lookup into the class.
1715218893Sdim        if (UseGlobal)
1716218893Sdim          UsualArrayDeleteWantsSize =
1717218893Sdim            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1718218893Sdim
1719218893Sdim        // Otherwise, the usual operator delete[] should be the
1720218893Sdim        // function we just found.
1721218893Sdim        else if (isa<CXXMethodDecl>(OperatorDelete))
1722218893Sdim          UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1723218893Sdim      }
1724218893Sdim
1725199482Srdivacky      if (!RD->hasTrivialDestructor())
1726218893Sdim        if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1727198092Srdivacky          MarkDeclarationReferenced(StartLoc,
1728198092Srdivacky                                    const_cast<CXXDestructorDecl*>(Dtor));
1729218893Sdim          DiagnoseUseOfDecl(Dtor, StartLoc);
1730218893Sdim        }
1731198092Srdivacky    }
1732218893Sdim
1733198092Srdivacky    if (!OperatorDelete) {
1734199482Srdivacky      // Look for a global declaration.
1735198092Srdivacky      DeclareGlobalNewDelete();
1736198092Srdivacky      DeclContext *TUDecl = Context.getTranslationUnitDecl();
1737198092Srdivacky      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1738198092Srdivacky                                 &Ex, 1, TUDecl, /*AllowMissing=*/false,
1739198092Srdivacky                                 OperatorDelete))
1740198092Srdivacky        return ExprError();
1741198092Srdivacky    }
1742198092Srdivacky
1743207619Srdivacky    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1744218893Sdim
1745218893Sdim    // Check access and ambiguity of operator delete and destructor.
1746218893Sdim    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1747218893Sdim      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1748218893Sdim      if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1749218893Sdim          CheckDestructorAccess(Ex->getExprLoc(), Dtor,
1750218893Sdim                      PDiag(diag::err_access_dtor) << PointeeElem);
1751218893Sdim      }
1752218893Sdim    }
1753207619Srdivacky
1754193326Sed  }
1755193326Sed
1756193326Sed  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1757218893Sdim                                           ArrayFormAsWritten,
1758218893Sdim                                           UsualArrayDeleteWantsSize,
1759198092Srdivacky                                           OperatorDelete, Ex, StartLoc));
1760193326Sed}
1761193326Sed
1762199990Srdivacky/// \brief Check the use of the given variable as a C++ condition in an if,
1763199990Srdivacky/// while, do-while, or switch statement.
1764212904SdimExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1765218893Sdim                                        SourceLocation StmtLoc,
1766218893Sdim                                        bool ConvertToBoolean) {
1767199990Srdivacky  QualType T = ConditionVar->getType();
1768218893Sdim
1769199990Srdivacky  // C++ [stmt.select]p2:
1770199990Srdivacky  //   The declarator shall not specify a function or an array.
1771199990Srdivacky  if (T->isFunctionType())
1772218893Sdim    return ExprError(Diag(ConditionVar->getLocation(),
1773199990Srdivacky                          diag::err_invalid_use_of_function_type)
1774199990Srdivacky                       << ConditionVar->getSourceRange());
1775199990Srdivacky  else if (T->isArrayType())
1776218893Sdim    return ExprError(Diag(ConditionVar->getLocation(),
1777199990Srdivacky                          diag::err_invalid_use_of_array_type)
1778199990Srdivacky                     << ConditionVar->getSourceRange());
1779193326Sed
1780208600Srdivacky  Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1781218893Sdim                                        ConditionVar->getLocation(),
1782218893Sdim                            ConditionVar->getType().getNonReferenceType(),
1783218893Sdim                                        VK_LValue);
1784212904Sdim  if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc))
1785208600Srdivacky    return ExprError();
1786218893Sdim
1787208600Srdivacky  return Owned(Condition);
1788193326Sed}
1789193326Sed
1790193326Sed/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1791193326Sedbool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1792193326Sed  // C++ 6.4p4:
1793193326Sed  // The value of a condition that is an initialized declaration in a statement
1794193326Sed  // other than a switch statement is the value of the declared variable
1795193326Sed  // implicitly converted to type bool. If that conversion is ill-formed, the
1796193326Sed  // program is ill-formed.
1797193326Sed  // The value of a condition that is an expression is the value of the
1798193326Sed  // expression, implicitly converted to bool.
1799193326Sed  //
1800193326Sed  return PerformContextuallyConvertToBool(CondExpr);
1801193326Sed}
1802193326Sed
1803193326Sed/// Helper function to determine whether this is the (deprecated) C++
1804193326Sed/// conversion from a string literal to a pointer to non-const char or
1805193326Sed/// non-const wchar_t (for narrow and wide string literals,
1806193326Sed/// respectively).
1807198092Srdivackybool
1808193326SedSema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1809193326Sed  // Look inside the implicit cast, if it exists.
1810193326Sed  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1811193326Sed    From = Cast->getSubExpr();
1812193326Sed
1813193326Sed  // A string literal (2.13.4) that is not a wide string literal can
1814193326Sed  // be converted to an rvalue of type "pointer to char"; a wide
1815193326Sed  // string literal can be converted to an rvalue of type "pointer
1816193326Sed  // to wchar_t" (C++ 4.2p2).
1817210299Sed  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
1818198092Srdivacky    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1819198092Srdivacky      if (const BuiltinType *ToPointeeType
1820198092Srdivacky          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1821193326Sed        // This conversion is considered only when there is an
1822193326Sed        // explicit appropriate pointer target type (C++ 4.2p2).
1823198092Srdivacky        if (!ToPtrType->getPointeeType().hasQualifiers() &&
1824193326Sed            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1825193326Sed             (!StrLit->isWide() &&
1826193326Sed              (ToPointeeType->getKind() == BuiltinType::Char_U ||
1827193326Sed               ToPointeeType->getKind() == BuiltinType::Char_S))))
1828193326Sed          return true;
1829193326Sed      }
1830193326Sed
1831193326Sed  return false;
1832193326Sed}
1833193326Sed
1834218893Sdimstatic ExprResult BuildCXXCastArgument(Sema &S,
1835212904Sdim                                       SourceLocation CastLoc,
1836212904Sdim                                       QualType Ty,
1837212904Sdim                                       CastKind Kind,
1838212904Sdim                                       CXXMethodDecl *Method,
1839218893Sdim                                       NamedDecl *FoundDecl,
1840212904Sdim                                       Expr *From) {
1841207619Srdivacky  switch (Kind) {
1842207619Srdivacky  default: assert(0 && "Unhandled cast kind!");
1843212904Sdim  case CK_ConstructorConversion: {
1844212904Sdim    ASTOwningVector<Expr*> ConstructorArgs(S);
1845218893Sdim
1846207619Srdivacky    if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1847212904Sdim                                  MultiExprArg(&From, 1),
1848207619Srdivacky                                  CastLoc, ConstructorArgs))
1849212904Sdim      return ExprError();
1850218893Sdim
1851218893Sdim    ExprResult Result =
1852218893Sdim    S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1853212904Sdim                            move_arg(ConstructorArgs),
1854218893Sdim                            /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1855218893Sdim                            SourceRange());
1856207619Srdivacky    if (Result.isInvalid())
1857212904Sdim      return ExprError();
1858218893Sdim
1859207619Srdivacky    return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1860193326Sed  }
1861218893Sdim
1862212904Sdim  case CK_UserDefinedConversion: {
1863207619Srdivacky    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1864218893Sdim
1865207619Srdivacky    // Create an implicit call expr that calls it.
1866218893Sdim    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
1867218893Sdim    if (Result.isInvalid())
1868218893Sdim      return ExprError();
1869218893Sdim
1870218893Sdim    return S.MaybeBindToTemporary(Result.get());
1871193326Sed  }
1872207619Srdivacky  }
1873218893Sdim}
1874193326Sed
1875193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
1876193326Sed/// expression From to the type ToType using the pre-computed implicit
1877193326Sed/// conversion sequence ICS. Returns true if there was an error, false
1878193326Sed/// otherwise. The expression From is replaced with the converted
1879201361Srdivacky/// expression. Action is the kind of conversion we're performing,
1880193326Sed/// used in the error message.
1881193326Sedbool
1882193326SedSema::PerformImplicitConversion(Expr *&From, QualType ToType,
1883193326Sed                                const ImplicitConversionSequence &ICS,
1884218893Sdim                                AssignmentAction Action, bool CStyle) {
1885202379Srdivacky  switch (ICS.getKind()) {
1886193326Sed  case ImplicitConversionSequence::StandardConversion:
1887201361Srdivacky    if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
1888218893Sdim                                  CStyle))
1889193326Sed      return true;
1890193326Sed    break;
1891193326Sed
1892198092Srdivacky  case ImplicitConversionSequence::UserDefinedConversion: {
1893218893Sdim
1894198092Srdivacky      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1895218893Sdim      CastKind CastKind;
1896198092Srdivacky      QualType BeforeToType;
1897198092Srdivacky      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1898212904Sdim        CastKind = CK_UserDefinedConversion;
1899218893Sdim
1900198092Srdivacky        // If the user-defined conversion is specified by a conversion function,
1901198092Srdivacky        // the initial standard conversion sequence converts the source type to
1902198092Srdivacky        // the implicit object parameter of the conversion function.
1903198092Srdivacky        BeforeToType = Context.getTagDeclType(Conv->getParent());
1904218893Sdim      } else {
1905218893Sdim        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
1906212904Sdim        CastKind = CK_ConstructorConversion;
1907199482Srdivacky        // Do no conversion if dealing with ... for the first conversion.
1908199990Srdivacky        if (!ICS.UserDefined.EllipsisConversion) {
1909218893Sdim          // If the user-defined conversion is specified by a constructor, the
1910199482Srdivacky          // initial standard conversion sequence converts the source type to the
1911199482Srdivacky          // type required by the argument of the constructor
1912199990Srdivacky          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1913199990Srdivacky        }
1914218893Sdim      }
1915218893Sdim      // Watch out for elipsis conversion.
1916199482Srdivacky      if (!ICS.UserDefined.EllipsisConversion) {
1917218893Sdim        if (PerformImplicitConversion(From, BeforeToType,
1918201361Srdivacky                                      ICS.UserDefined.Before, AA_Converting,
1919218893Sdim                                      CStyle))
1920199482Srdivacky          return true;
1921199482Srdivacky      }
1922218893Sdim
1923218893Sdim      ExprResult CastArg
1924207619Srdivacky        = BuildCXXCastArgument(*this,
1925207619Srdivacky                               From->getLocStart(),
1926198092Srdivacky                               ToType.getNonReferenceType(),
1927218893Sdim                               CastKind, cast<CXXMethodDecl>(FD),
1928218893Sdim                               ICS.UserDefined.FoundConversionFunction,
1929212904Sdim                               From);
1930198092Srdivacky
1931198092Srdivacky      if (CastArg.isInvalid())
1932198092Srdivacky        return true;
1933199990Srdivacky
1934199990Srdivacky      From = CastArg.takeAs<Expr>();
1935199990Srdivacky
1936199990Srdivacky      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
1937218893Sdim                                       AA_Converting, CStyle);
1938198398Srdivacky  }
1939202379Srdivacky
1940202379Srdivacky  case ImplicitConversionSequence::AmbiguousConversion:
1941212904Sdim    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
1942202379Srdivacky                          PDiag(diag::err_typecheck_ambiguous_condition)
1943202379Srdivacky                            << From->getSourceRange());
1944202379Srdivacky     return true;
1945218893Sdim
1946193326Sed  case ImplicitConversionSequence::EllipsisConversion:
1947193326Sed    assert(false && "Cannot perform an ellipsis conversion");
1948193326Sed    return false;
1949193326Sed
1950193326Sed  case ImplicitConversionSequence::BadConversion:
1951193326Sed    return true;
1952193326Sed  }
1953193326Sed
1954193326Sed  // Everything went well.
1955193326Sed  return false;
1956193326Sed}
1957193326Sed
1958193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
1959193326Sed/// expression From to the type ToType by following the standard
1960193326Sed/// conversion sequence SCS. Returns true if there was an error, false
1961193326Sed/// otherwise. The expression From is replaced with the converted
1962193326Sed/// expression. Flavor is the context in which we're performing this
1963193326Sed/// conversion, for use in error messages.
1964198092Srdivackybool
1965193326SedSema::PerformImplicitConversion(Expr *&From, QualType ToType,
1966193326Sed                                const StandardConversionSequence& SCS,
1967218893Sdim                                AssignmentAction Action, bool CStyle) {
1968193326Sed  // Overall FIXME: we are recomputing too many types here and doing far too
1969193326Sed  // much extra work. What this means is that we need to keep track of more
1970193326Sed  // information that is computed when we try the implicit conversion initially,
1971193326Sed  // so that we don't need to recompute anything here.
1972193326Sed  QualType FromType = From->getType();
1973193326Sed
1974193326Sed  if (SCS.CopyConstructor) {
1975193326Sed    // FIXME: When can ToType be a reference type?
1976193326Sed    assert(!ToType->isReferenceType());
1977198092Srdivacky    if (SCS.Second == ICK_Derived_To_Base) {
1978212904Sdim      ASTOwningVector<Expr*> ConstructorArgs(*this);
1979198092Srdivacky      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1980212904Sdim                                  MultiExprArg(*this, &From, 1),
1981218893Sdim                                  /*FIXME:ConstructLoc*/SourceLocation(),
1982198092Srdivacky                                  ConstructorArgs))
1983198092Srdivacky        return true;
1984212904Sdim      ExprResult FromResult =
1985198092Srdivacky        BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1986198092Srdivacky                              ToType, SCS.CopyConstructor,
1987212904Sdim                              move_arg(ConstructorArgs),
1988212904Sdim                              /*ZeroInit*/ false,
1989218893Sdim                              CXXConstructExpr::CK_Complete,
1990218893Sdim                              SourceRange());
1991198092Srdivacky      if (FromResult.isInvalid())
1992198092Srdivacky        return true;
1993198092Srdivacky      From = FromResult.takeAs<Expr>();
1994198092Srdivacky      return false;
1995198092Srdivacky    }
1996212904Sdim    ExprResult FromResult =
1997198092Srdivacky      BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1998198092Srdivacky                            ToType, SCS.CopyConstructor,
1999212904Sdim                            MultiExprArg(*this, &From, 1),
2000212904Sdim                            /*ZeroInit*/ false,
2001218893Sdim                            CXXConstructExpr::CK_Complete,
2002218893Sdim                            SourceRange());
2003198092Srdivacky
2004198092Srdivacky    if (FromResult.isInvalid())
2005198092Srdivacky      return true;
2006198092Srdivacky
2007198092Srdivacky    From = FromResult.takeAs<Expr>();
2008193326Sed    return false;
2009193326Sed  }
2010193326Sed
2011207619Srdivacky  // Resolve overloaded function references.
2012207619Srdivacky  if (Context.hasSameType(FromType, Context.OverloadTy)) {
2013207619Srdivacky    DeclAccessPair Found;
2014207619Srdivacky    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2015207619Srdivacky                                                          true, Found);
2016207619Srdivacky    if (!Fn)
2017207619Srdivacky      return true;
2018207619Srdivacky
2019207619Srdivacky    if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2020207619Srdivacky      return true;
2021207619Srdivacky
2022207619Srdivacky    From = FixOverloadedFunctionReference(From, Found, Fn);
2023207619Srdivacky    FromType = From->getType();
2024207619Srdivacky  }
2025207619Srdivacky
2026193326Sed  // Perform the first implicit conversion.
2027193326Sed  switch (SCS.First) {
2028193326Sed  case ICK_Identity:
2029193326Sed    // Nothing to do.
2030193326Sed    break;
2031193326Sed
2032218893Sdim  case ICK_Lvalue_To_Rvalue:
2033218893Sdim    // Should this get its own ICK?
2034218893Sdim    if (From->getObjectKind() == OK_ObjCProperty) {
2035218893Sdim      ConvertPropertyForRValue(From);
2036218893Sdim      if (!From->isGLValue()) break;
2037218893Sdim    }
2038218893Sdim
2039218893Sdim    // Check for trivial buffer overflows.
2040218893Sdim    if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(From))
2041218893Sdim      CheckArrayAccess(AE);
2042218893Sdim
2043218893Sdim    FromType = FromType.getUnqualifiedType();
2044218893Sdim    From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2045218893Sdim                                    From, 0, VK_RValue);
2046218893Sdim    break;
2047218893Sdim
2048193326Sed  case ICK_Array_To_Pointer:
2049193326Sed    FromType = Context.getArrayDecayedType(FromType);
2050212904Sdim    ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay);
2051193326Sed    break;
2052193326Sed
2053193326Sed  case ICK_Function_To_Pointer:
2054193326Sed    FromType = Context.getPointerType(FromType);
2055212904Sdim    ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay);
2056193326Sed    break;
2057193326Sed
2058193326Sed  default:
2059193326Sed    assert(false && "Improper first standard conversion");
2060193326Sed    break;
2061193326Sed  }
2062193326Sed
2063193326Sed  // Perform the second implicit conversion
2064193326Sed  switch (SCS.Second) {
2065193326Sed  case ICK_Identity:
2066198092Srdivacky    // If both sides are functions (or pointers/references to them), there could
2067198092Srdivacky    // be incompatible exception declarations.
2068198092Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
2069198092Srdivacky      return true;
2070198092Srdivacky    // Nothing else to do.
2071193326Sed    break;
2072193326Sed
2073200583Srdivacky  case ICK_NoReturn_Adjustment:
2074200583Srdivacky    // If both sides are functions (or pointers/references to them), there could
2075200583Srdivacky    // be incompatible exception declarations.
2076200583Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
2077218893Sdim      return true;
2078218893Sdim
2079218893Sdim    ImpCastExprToType(From, ToType, CK_NoOp);
2080200583Srdivacky    break;
2081218893Sdim
2082193326Sed  case ICK_Integral_Promotion:
2083198398Srdivacky  case ICK_Integral_Conversion:
2084212904Sdim    ImpCastExprToType(From, ToType, CK_IntegralCast);
2085198398Srdivacky    break;
2086198398Srdivacky
2087193326Sed  case ICK_Floating_Promotion:
2088198398Srdivacky  case ICK_Floating_Conversion:
2089212904Sdim    ImpCastExprToType(From, ToType, CK_FloatingCast);
2090198398Srdivacky    break;
2091198398Srdivacky
2092193326Sed  case ICK_Complex_Promotion:
2093218893Sdim  case ICK_Complex_Conversion: {
2094218893Sdim    QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2095218893Sdim    QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2096218893Sdim    CastKind CK;
2097218893Sdim    if (FromEl->isRealFloatingType()) {
2098218893Sdim      if (ToEl->isRealFloatingType())
2099218893Sdim        CK = CK_FloatingComplexCast;
2100218893Sdim      else
2101218893Sdim        CK = CK_FloatingComplexToIntegralComplex;
2102218893Sdim    } else if (ToEl->isRealFloatingType()) {
2103218893Sdim      CK = CK_IntegralComplexToFloatingComplex;
2104218893Sdim    } else {
2105218893Sdim      CK = CK_IntegralComplexCast;
2106218893Sdim    }
2107218893Sdim    ImpCastExprToType(From, ToType, CK);
2108198398Srdivacky    break;
2109218893Sdim  }
2110198398Srdivacky
2111193326Sed  case ICK_Floating_Integral:
2112210299Sed    if (ToType->isRealFloatingType())
2113212904Sdim      ImpCastExprToType(From, ToType, CK_IntegralToFloating);
2114198398Srdivacky    else
2115212904Sdim      ImpCastExprToType(From, ToType, CK_FloatingToIntegral);
2116198398Srdivacky    break;
2117198398Srdivacky
2118193326Sed  case ICK_Compatible_Conversion:
2119212904Sdim    ImpCastExprToType(From, ToType, CK_NoOp);
2120193326Sed    break;
2121193326Sed
2122198092Srdivacky  case ICK_Pointer_Conversion: {
2123218893Sdim    if (SCS.IncompatibleObjC && Action != AA_Casting) {
2124193326Sed      // Diagnose incompatible Objective-C conversions
2125198092Srdivacky      Diag(From->getSourceRange().getBegin(),
2126193326Sed           diag::ext_typecheck_convert_incompatible_pointer)
2127201361Srdivacky        << From->getType() << ToType << Action
2128193326Sed        << From->getSourceRange();
2129193326Sed    }
2130193326Sed
2131218893Sdim    CastKind Kind = CK_Invalid;
2132212904Sdim    CXXCastPath BasePath;
2133218893Sdim    if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2134193326Sed      return true;
2135212904Sdim    ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
2136193326Sed    break;
2137198092Srdivacky  }
2138218893Sdim
2139198092Srdivacky  case ICK_Pointer_Member: {
2140218893Sdim    CastKind Kind = CK_Invalid;
2141212904Sdim    CXXCastPath BasePath;
2142218893Sdim    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2143193326Sed      return true;
2144198092Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
2145198092Srdivacky      return true;
2146212904Sdim    ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath);
2147193326Sed    break;
2148198092Srdivacky  }
2149199990Srdivacky  case ICK_Boolean_Conversion: {
2150218893Sdim    CastKind Kind = CK_Invalid;
2151218893Sdim    switch (FromType->getScalarTypeKind()) {
2152218893Sdim    case Type::STK_Pointer: Kind = CK_PointerToBoolean; break;
2153218893Sdim    case Type::STK_MemberPointer: Kind = CK_MemberPointerToBoolean; break;
2154218893Sdim    case Type::STK_Bool: llvm_unreachable("bool -> bool conversion?");
2155218893Sdim    case Type::STK_Integral: Kind = CK_IntegralToBoolean; break;
2156218893Sdim    case Type::STK_Floating: Kind = CK_FloatingToBoolean; break;
2157218893Sdim    case Type::STK_IntegralComplex: Kind = CK_IntegralComplexToBoolean; break;
2158218893Sdim    case Type::STK_FloatingComplex: Kind = CK_FloatingComplexToBoolean; break;
2159218893Sdim    }
2160218893Sdim
2161199990Srdivacky    ImpCastExprToType(From, Context.BoolTy, Kind);
2162193326Sed    break;
2163199990Srdivacky  }
2164193326Sed
2165208600Srdivacky  case ICK_Derived_To_Base: {
2166212904Sdim    CXXCastPath BasePath;
2167218893Sdim    if (CheckDerivedToBaseConversion(From->getType(),
2168199482Srdivacky                                     ToType.getNonReferenceType(),
2169199482Srdivacky                                     From->getLocStart(),
2170218893Sdim                                     From->getSourceRange(),
2171208600Srdivacky                                     &BasePath,
2172218893Sdim                                     CStyle))
2173199482Srdivacky      return true;
2174208600Srdivacky
2175212904Sdim    ImpCastExprToType(From, ToType.getNonReferenceType(),
2176212904Sdim                      CK_DerivedToBase, CastCategory(From),
2177212904Sdim                      &BasePath);
2178199482Srdivacky    break;
2179208600Srdivacky  }
2180208600Srdivacky
2181208600Srdivacky  case ICK_Vector_Conversion:
2182212904Sdim    ImpCastExprToType(From, ToType, CK_BitCast);
2183208600Srdivacky    break;
2184208600Srdivacky
2185208600Srdivacky  case ICK_Vector_Splat:
2186212904Sdim    ImpCastExprToType(From, ToType, CK_VectorSplat);
2187208600Srdivacky    break;
2188218893Sdim
2189208600Srdivacky  case ICK_Complex_Real:
2190218893Sdim    // Case 1.  x -> _Complex y
2191218893Sdim    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2192218893Sdim      QualType ElType = ToComplex->getElementType();
2193218893Sdim      bool isFloatingComplex = ElType->isRealFloatingType();
2194218893Sdim
2195218893Sdim      // x -> y
2196218893Sdim      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2197218893Sdim        // do nothing
2198218893Sdim      } else if (From->getType()->isRealFloatingType()) {
2199218893Sdim        ImpCastExprToType(From, ElType,
2200218893Sdim                isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral);
2201218893Sdim      } else {
2202218893Sdim        assert(From->getType()->isIntegerType());
2203218893Sdim        ImpCastExprToType(From, ElType,
2204218893Sdim                isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast);
2205218893Sdim      }
2206218893Sdim      // y -> _Complex y
2207218893Sdim      ImpCastExprToType(From, ToType,
2208218893Sdim                   isFloatingComplex ? CK_FloatingRealToComplex
2209218893Sdim                                     : CK_IntegralRealToComplex);
2210218893Sdim
2211218893Sdim    // Case 2.  _Complex x -> y
2212218893Sdim    } else {
2213218893Sdim      const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2214218893Sdim      assert(FromComplex);
2215218893Sdim
2216218893Sdim      QualType ElType = FromComplex->getElementType();
2217218893Sdim      bool isFloatingComplex = ElType->isRealFloatingType();
2218218893Sdim
2219218893Sdim      // _Complex x -> x
2220218893Sdim      ImpCastExprToType(From, ElType,
2221218893Sdim                   isFloatingComplex ? CK_FloatingComplexToReal
2222218893Sdim                                     : CK_IntegralComplexToReal);
2223218893Sdim
2224218893Sdim      // x -> y
2225218893Sdim      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2226218893Sdim        // do nothing
2227218893Sdim      } else if (ToType->isRealFloatingType()) {
2228218893Sdim        ImpCastExprToType(From, ToType,
2229218893Sdim                isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating);
2230218893Sdim      } else {
2231218893Sdim        assert(ToType->isIntegerType());
2232218893Sdim        ImpCastExprToType(From, ToType,
2233218893Sdim                isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast);
2234218893Sdim      }
2235218893Sdim    }
2236208600Srdivacky    break;
2237218893Sdim
2238218893Sdim  case ICK_Block_Pointer_Conversion: {
2239218893Sdim      ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, VK_RValue);
2240218893Sdim      break;
2241218893Sdim    }
2242208600Srdivacky
2243208600Srdivacky  case ICK_Lvalue_To_Rvalue:
2244208600Srdivacky  case ICK_Array_To_Pointer:
2245208600Srdivacky  case ICK_Function_To_Pointer:
2246208600Srdivacky  case ICK_Qualification:
2247208600Srdivacky  case ICK_Num_Conversion_Kinds:
2248193326Sed    assert(false && "Improper second standard conversion");
2249193326Sed    break;
2250193326Sed  }
2251193326Sed
2252193326Sed  switch (SCS.Third) {
2253193326Sed  case ICK_Identity:
2254193326Sed    // Nothing to do.
2255193326Sed    break;
2256193326Sed
2257212904Sdim  case ICK_Qualification: {
2258212904Sdim    // The qualification keeps the category of the inner expression, unless the
2259212904Sdim    // target type isn't a reference.
2260212904Sdim    ExprValueKind VK = ToType->isReferenceType() ?
2261212904Sdim                                  CastCategory(From) : VK_RValue;
2262210299Sed    ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2263212904Sdim                      CK_NoOp, VK);
2264204643Srdivacky
2265204643Srdivacky    if (SCS.DeprecatedStringLiteralToCharPtr)
2266204643Srdivacky      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2267204643Srdivacky        << ToType.getNonReferenceType();
2268204643Srdivacky
2269193326Sed    break;
2270212904Sdim    }
2271212904Sdim
2272193326Sed  default:
2273208600Srdivacky    assert(false && "Improper third standard conversion");
2274193326Sed    break;
2275193326Sed  }
2276193326Sed
2277193326Sed  return false;
2278193326Sed}
2279193326Sed
2280218893SdimExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
2281218893Sdim                                     SourceLocation KWLoc,
2282218893Sdim                                     ParsedType Ty,
2283218893Sdim                                     SourceLocation RParen) {
2284218893Sdim  TypeSourceInfo *TSInfo;
2285218893Sdim  QualType T = GetTypeFromParser(Ty, &TSInfo);
2286193326Sed
2287218893Sdim  if (!TSInfo)
2288218893Sdim    TSInfo = Context.getTrivialTypeSourceInfo(T);
2289218893Sdim  return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
2290218893Sdim}
2291218893Sdim
2292218893Sdimstatic bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T,
2293218893Sdim                                   SourceLocation KeyLoc) {
2294218893Sdim  // FIXME: For many of these traits, we need a complete type before we can
2295218893Sdim  // check these properties.
2296218893Sdim  assert(!T->isDependentType() &&
2297218893Sdim         "Cannot evaluate traits for dependent types.");
2298218893Sdim  ASTContext &C = Self.Context;
2299218893Sdim  switch(UTT) {
2300218893Sdim  default: assert(false && "Unknown type trait or not implemented");
2301218893Sdim  case UTT_IsPOD: return T->isPODType();
2302218893Sdim  case UTT_IsLiteral: return T->isLiteralType();
2303218893Sdim  case UTT_IsClass: // Fallthrough
2304218893Sdim  case UTT_IsUnion:
2305218893Sdim    if (const RecordType *Record = T->getAs<RecordType>()) {
2306218893Sdim      bool Union = Record->getDecl()->isUnion();
2307218893Sdim      return UTT == UTT_IsUnion ? Union : !Union;
2308218893Sdim    }
2309218893Sdim    return false;
2310218893Sdim  case UTT_IsEnum: return T->isEnumeralType();
2311218893Sdim  case UTT_IsPolymorphic:
2312218893Sdim    if (const RecordType *Record = T->getAs<RecordType>()) {
2313218893Sdim      // Type traits are only parsed in C++, so we've got CXXRecords.
2314218893Sdim      return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic();
2315218893Sdim    }
2316218893Sdim    return false;
2317218893Sdim  case UTT_IsAbstract:
2318218893Sdim    if (const RecordType *RT = T->getAs<RecordType>())
2319218893Sdim      return cast<CXXRecordDecl>(RT->getDecl())->isAbstract();
2320218893Sdim    return false;
2321218893Sdim  case UTT_IsEmpty:
2322218893Sdim    if (const RecordType *Record = T->getAs<RecordType>()) {
2323218893Sdim      return !Record->getDecl()->isUnion()
2324218893Sdim          && cast<CXXRecordDecl>(Record->getDecl())->isEmpty();
2325218893Sdim    }
2326218893Sdim    return false;
2327218893Sdim  case UTT_HasTrivialConstructor:
2328218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2329218893Sdim    //   If __is_pod (type) is true then the trait is true, else if type is
2330218893Sdim    //   a cv class or union type (or array thereof) with a trivial default
2331218893Sdim    //   constructor ([class.ctor]) then the trait is true, else it is false.
2332218893Sdim    if (T->isPODType())
2333218893Sdim      return true;
2334218893Sdim    if (const RecordType *RT =
2335218893Sdim          C.getBaseElementType(T)->getAs<RecordType>())
2336218893Sdim      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2337218893Sdim    return false;
2338218893Sdim  case UTT_HasTrivialCopy:
2339218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2340218893Sdim    //   If __is_pod (type) is true or type is a reference type then
2341218893Sdim    //   the trait is true, else if type is a cv class or union type
2342218893Sdim    //   with a trivial copy constructor ([class.copy]) then the trait
2343218893Sdim    //   is true, else it is false.
2344218893Sdim    if (T->isPODType() || T->isReferenceType())
2345218893Sdim      return true;
2346218893Sdim    if (const RecordType *RT = T->getAs<RecordType>())
2347218893Sdim      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2348218893Sdim    return false;
2349218893Sdim  case UTT_HasTrivialAssign:
2350218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2351218893Sdim    //   If type is const qualified or is a reference type then the
2352218893Sdim    //   trait is false. Otherwise if __is_pod (type) is true then the
2353218893Sdim    //   trait is true, else if type is a cv class or union type with
2354218893Sdim    //   a trivial copy assignment ([class.copy]) then the trait is
2355218893Sdim    //   true, else it is false.
2356218893Sdim    // Note: the const and reference restrictions are interesting,
2357218893Sdim    // given that const and reference members don't prevent a class
2358218893Sdim    // from having a trivial copy assignment operator (but do cause
2359218893Sdim    // errors if the copy assignment operator is actually used, q.v.
2360218893Sdim    // [class.copy]p12).
2361218893Sdim
2362218893Sdim    if (C.getBaseElementType(T).isConstQualified())
2363218893Sdim      return false;
2364218893Sdim    if (T->isPODType())
2365218893Sdim      return true;
2366218893Sdim    if (const RecordType *RT = T->getAs<RecordType>())
2367218893Sdim      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2368218893Sdim    return false;
2369218893Sdim  case UTT_HasTrivialDestructor:
2370218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2371218893Sdim    //   If __is_pod (type) is true or type is a reference type
2372218893Sdim    //   then the trait is true, else if type is a cv class or union
2373218893Sdim    //   type (or array thereof) with a trivial destructor
2374218893Sdim    //   ([class.dtor]) then the trait is true, else it is
2375218893Sdim    //   false.
2376218893Sdim    if (T->isPODType() || T->isReferenceType())
2377218893Sdim      return true;
2378218893Sdim    if (const RecordType *RT =
2379218893Sdim          C.getBaseElementType(T)->getAs<RecordType>())
2380218893Sdim      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2381218893Sdim    return false;
2382218893Sdim  // TODO: Propagate nothrowness for implicitly declared special members.
2383218893Sdim  case UTT_HasNothrowAssign:
2384218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2385218893Sdim    //   If type is const qualified or is a reference type then the
2386218893Sdim    //   trait is false. Otherwise if __has_trivial_assign (type)
2387218893Sdim    //   is true then the trait is true, else if type is a cv class
2388218893Sdim    //   or union type with copy assignment operators that are known
2389218893Sdim    //   not to throw an exception then the trait is true, else it is
2390218893Sdim    //   false.
2391218893Sdim    if (C.getBaseElementType(T).isConstQualified())
2392218893Sdim      return false;
2393218893Sdim    if (T->isReferenceType())
2394218893Sdim      return false;
2395218893Sdim    if (T->isPODType())
2396218893Sdim      return true;
2397218893Sdim    if (const RecordType *RT = T->getAs<RecordType>()) {
2398218893Sdim      CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2399218893Sdim      if (RD->hasTrivialCopyAssignment())
2400218893Sdim        return true;
2401218893Sdim
2402218893Sdim      bool FoundAssign = false;
2403218893Sdim      bool AllNoThrow = true;
2404218893Sdim      DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
2405218893Sdim      LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2406218893Sdim                       Sema::LookupOrdinaryName);
2407218893Sdim      if (Self.LookupQualifiedName(Res, RD)) {
2408218893Sdim        for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2409218893Sdim             Op != OpEnd; ++Op) {
2410218893Sdim          CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2411218893Sdim          if (Operator->isCopyAssignmentOperator()) {
2412218893Sdim            FoundAssign = true;
2413218893Sdim            const FunctionProtoType *CPT
2414218893Sdim                = Operator->getType()->getAs<FunctionProtoType>();
2415218893Sdim            if (!CPT->hasEmptyExceptionSpec()) {
2416218893Sdim              AllNoThrow = false;
2417218893Sdim              break;
2418218893Sdim            }
2419218893Sdim          }
2420218893Sdim        }
2421218893Sdim      }
2422218893Sdim
2423218893Sdim      return FoundAssign && AllNoThrow;
2424218893Sdim    }
2425218893Sdim    return false;
2426218893Sdim  case UTT_HasNothrowCopy:
2427218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2428218893Sdim    //   If __has_trivial_copy (type) is true then the trait is true, else
2429218893Sdim    //   if type is a cv class or union type with copy constructors that are
2430218893Sdim    //   known not to throw an exception then the trait is true, else it is
2431218893Sdim    //   false.
2432218893Sdim    if (T->isPODType() || T->isReferenceType())
2433218893Sdim      return true;
2434218893Sdim    if (const RecordType *RT = T->getAs<RecordType>()) {
2435218893Sdim      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2436218893Sdim      if (RD->hasTrivialCopyConstructor())
2437218893Sdim        return true;
2438218893Sdim
2439218893Sdim      bool FoundConstructor = false;
2440218893Sdim      bool AllNoThrow = true;
2441218893Sdim      unsigned FoundTQs;
2442218893Sdim      DeclContext::lookup_const_iterator Con, ConEnd;
2443218893Sdim      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2444218893Sdim           Con != ConEnd; ++Con) {
2445218893Sdim        // A template constructor is never a copy constructor.
2446218893Sdim        // FIXME: However, it may actually be selected at the actual overload
2447218893Sdim        // resolution point.
2448218893Sdim        if (isa<FunctionTemplateDecl>(*Con))
2449218893Sdim          continue;
2450218893Sdim        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2451218893Sdim        if (Constructor->isCopyConstructor(FoundTQs)) {
2452218893Sdim          FoundConstructor = true;
2453218893Sdim          const FunctionProtoType *CPT
2454218893Sdim              = Constructor->getType()->getAs<FunctionProtoType>();
2455218893Sdim          // TODO: check whether evaluating default arguments can throw.
2456218893Sdim          // For now, we'll be conservative and assume that they can throw.
2457218893Sdim          if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) {
2458218893Sdim            AllNoThrow = false;
2459218893Sdim            break;
2460218893Sdim          }
2461218893Sdim        }
2462218893Sdim      }
2463218893Sdim
2464218893Sdim      return FoundConstructor && AllNoThrow;
2465218893Sdim    }
2466218893Sdim    return false;
2467218893Sdim  case UTT_HasNothrowConstructor:
2468218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2469218893Sdim    //   If __has_trivial_constructor (type) is true then the trait is
2470218893Sdim    //   true, else if type is a cv class or union type (or array
2471218893Sdim    //   thereof) with a default constructor that is known not to
2472218893Sdim    //   throw an exception then the trait is true, else it is false.
2473218893Sdim    if (T->isPODType())
2474218893Sdim      return true;
2475218893Sdim    if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2476218893Sdim      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2477218893Sdim      if (RD->hasTrivialConstructor())
2478218893Sdim        return true;
2479218893Sdim
2480218893Sdim      DeclContext::lookup_const_iterator Con, ConEnd;
2481218893Sdim      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2482218893Sdim           Con != ConEnd; ++Con) {
2483218893Sdim        // FIXME: In C++0x, a constructor template can be a default constructor.
2484218893Sdim        if (isa<FunctionTemplateDecl>(*Con))
2485218893Sdim          continue;
2486218893Sdim        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2487218893Sdim        if (Constructor->isDefaultConstructor()) {
2488218893Sdim          const FunctionProtoType *CPT
2489218893Sdim              = Constructor->getType()->getAs<FunctionProtoType>();
2490218893Sdim          // TODO: check whether evaluating default arguments can throw.
2491218893Sdim          // For now, we'll be conservative and assume that they can throw.
2492218893Sdim          return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0;
2493218893Sdim        }
2494218893Sdim      }
2495218893Sdim    }
2496218893Sdim    return false;
2497218893Sdim  case UTT_HasVirtualDestructor:
2498218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2499218893Sdim    //   If type is a class type with a virtual destructor ([class.dtor])
2500218893Sdim    //   then the trait is true, else it is false.
2501218893Sdim    if (const RecordType *Record = T->getAs<RecordType>()) {
2502218893Sdim      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2503218893Sdim      if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
2504218893Sdim        return Destructor->isVirtual();
2505218893Sdim    }
2506218893Sdim    return false;
2507218893Sdim  }
2508218893Sdim}
2509218893Sdim
2510218893SdimExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
2511218893Sdim                                     SourceLocation KWLoc,
2512218893Sdim                                     TypeSourceInfo *TSInfo,
2513218893Sdim                                     SourceLocation RParen) {
2514218893Sdim  QualType T = TSInfo->getType();
2515218893Sdim
2516198092Srdivacky  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
2517198092Srdivacky  // all traits except __is_class, __is_enum and __is_union require a the type
2518218893Sdim  // to be complete, an array of unknown bound, or void.
2519218893Sdim  if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) {
2520218893Sdim    QualType E = T;
2521218893Sdim    if (T->isIncompleteArrayType())
2522218893Sdim      E = Context.getAsArrayType(T)->getElementType();
2523218893Sdim    if (!T->isVoidType() &&
2524218893Sdim        RequireCompleteType(KWLoc, E,
2525198092Srdivacky                            diag::err_incomplete_type_used_in_type_trait_expr))
2526198092Srdivacky      return ExprError();
2527198092Srdivacky  }
2528198092Srdivacky
2529218893Sdim  bool Value = false;
2530218893Sdim  if (!T->isDependentType())
2531218893Sdim    Value = EvaluateUnaryTypeTrait(*this, UTT, T, KWLoc);
2532218893Sdim
2533218893Sdim  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
2534198092Srdivacky                                                RParen, Context.BoolTy));
2535193326Sed}
2536193326Sed
2537218893SdimExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2538218893Sdim                                      SourceLocation KWLoc,
2539218893Sdim                                      ParsedType LhsTy,
2540218893Sdim                                      ParsedType RhsTy,
2541218893Sdim                                      SourceLocation RParen) {
2542218893Sdim  TypeSourceInfo *LhsTSInfo;
2543218893Sdim  QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2544218893Sdim  if (!LhsTSInfo)
2545218893Sdim    LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2546218893Sdim
2547218893Sdim  TypeSourceInfo *RhsTSInfo;
2548218893Sdim  QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2549218893Sdim  if (!RhsTSInfo)
2550218893Sdim    RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2551218893Sdim
2552218893Sdim  return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2553218893Sdim}
2554218893Sdim
2555218893Sdimstatic bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2556218893Sdim                                    QualType LhsT, QualType RhsT,
2557218893Sdim                                    SourceLocation KeyLoc) {
2558218893Sdim  assert((!LhsT->isDependentType() || RhsT->isDependentType()) &&
2559218893Sdim         "Cannot evaluate traits for dependent types.");
2560218893Sdim
2561218893Sdim  switch(BTT) {
2562218893Sdim  case BTT_IsBaseOf: {
2563218893Sdim    // C++0x [meta.rel]p2
2564218893Sdim    // Base is a base class of Derived without regard to cv-qualifiers or
2565218893Sdim    // Base and Derived are not unions and name the same class type without
2566218893Sdim    // regard to cv-qualifiers.
2567218893Sdim
2568218893Sdim    const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2569218893Sdim    if (!lhsRecord) return false;
2570218893Sdim
2571218893Sdim    const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2572218893Sdim    if (!rhsRecord) return false;
2573218893Sdim
2574218893Sdim    assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2575218893Sdim             == (lhsRecord == rhsRecord));
2576218893Sdim
2577218893Sdim    if (lhsRecord == rhsRecord)
2578218893Sdim      return !lhsRecord->getDecl()->isUnion();
2579218893Sdim
2580218893Sdim    // C++0x [meta.rel]p2:
2581218893Sdim    //   If Base and Derived are class types and are different types
2582218893Sdim    //   (ignoring possible cv-qualifiers) then Derived shall be a
2583218893Sdim    //   complete type.
2584218893Sdim    if (Self.RequireCompleteType(KeyLoc, RhsT,
2585218893Sdim                          diag::err_incomplete_type_used_in_type_trait_expr))
2586218893Sdim      return false;
2587218893Sdim
2588218893Sdim    return cast<CXXRecordDecl>(rhsRecord->getDecl())
2589218893Sdim      ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2590218893Sdim  }
2591218893Sdim
2592218893Sdim  case BTT_TypeCompatible:
2593218893Sdim    return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2594218893Sdim                                           RhsT.getUnqualifiedType());
2595218893Sdim
2596218893Sdim  case BTT_IsConvertibleTo: {
2597218893Sdim    // C++0x [meta.rel]p4:
2598218893Sdim    //   Given the following function prototype:
2599218893Sdim    //
2600218893Sdim    //     template <class T>
2601218893Sdim    //       typename add_rvalue_reference<T>::type create();
2602218893Sdim    //
2603218893Sdim    //   the predicate condition for a template specialization
2604218893Sdim    //   is_convertible<From, To> shall be satisfied if and only if
2605218893Sdim    //   the return expression in the following code would be
2606218893Sdim    //   well-formed, including any implicit conversions to the return
2607218893Sdim    //   type of the function:
2608218893Sdim    //
2609218893Sdim    //     To test() {
2610218893Sdim    //       return create<From>();
2611218893Sdim    //     }
2612218893Sdim    //
2613218893Sdim    //   Access checking is performed as if in a context unrelated to To and
2614218893Sdim    //   From. Only the validity of the immediate context of the expression
2615218893Sdim    //   of the return-statement (including conversions to the return type)
2616218893Sdim    //   is considered.
2617218893Sdim    //
2618218893Sdim    // We model the initialization as a copy-initialization of a temporary
2619218893Sdim    // of the appropriate type, which for this expression is identical to the
2620218893Sdim    // return statement (since NRVO doesn't apply).
2621218893Sdim    if (LhsT->isObjectType() || LhsT->isFunctionType())
2622218893Sdim      LhsT = Self.Context.getRValueReferenceType(LhsT);
2623218893Sdim
2624218893Sdim    InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
2625218893Sdim    OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
2626218893Sdim                         Expr::getValueKindForType(LhsT));
2627218893Sdim    Expr *FromPtr = &From;
2628218893Sdim    InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2629218893Sdim                                                           SourceLocation()));
2630218893Sdim
2631218893Sdim    // Perform the initialization within a SFINAE trap at translation unit
2632218893Sdim    // scope.
2633218893Sdim    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2634218893Sdim    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
2635218893Sdim    InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2636218893Sdim    if (Init.getKind() == InitializationSequence::FailedSequence)
2637218893Sdim      return false;
2638218893Sdim
2639218893Sdim    ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2640218893Sdim    return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2641218893Sdim  }
2642218893Sdim  }
2643218893Sdim  llvm_unreachable("Unknown type trait or not implemented");
2644218893Sdim}
2645218893Sdim
2646218893SdimExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2647218893Sdim                                      SourceLocation KWLoc,
2648218893Sdim                                      TypeSourceInfo *LhsTSInfo,
2649218893Sdim                                      TypeSourceInfo *RhsTSInfo,
2650218893Sdim                                      SourceLocation RParen) {
2651218893Sdim  QualType LhsT = LhsTSInfo->getType();
2652218893Sdim  QualType RhsT = RhsTSInfo->getType();
2653218893Sdim
2654218893Sdim  if (BTT == BTT_TypeCompatible) {
2655218893Sdim    if (getLangOptions().CPlusPlus) {
2656218893Sdim      Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2657218893Sdim        << SourceRange(KWLoc, RParen);
2658218893Sdim      return ExprError();
2659218893Sdim    }
2660218893Sdim  }
2661218893Sdim
2662218893Sdim  bool Value = false;
2663218893Sdim  if (!LhsT->isDependentType() && !RhsT->isDependentType())
2664218893Sdim    Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2665218893Sdim
2666218893Sdim  // Select trait result type.
2667218893Sdim  QualType ResultType;
2668218893Sdim  switch (BTT) {
2669218893Sdim  case BTT_IsBaseOf:       ResultType = Context.BoolTy; break;
2670218893Sdim  case BTT_TypeCompatible: ResultType = Context.IntTy; break;
2671218893Sdim  case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
2672218893Sdim  }
2673218893Sdim
2674218893Sdim  return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2675218893Sdim                                                 RhsTSInfo, Value, RParen,
2676218893Sdim                                                 ResultType));
2677218893Sdim}
2678218893Sdim
2679218893SdimQualType Sema::CheckPointerToMemberOperands(Expr *&lex, Expr *&rex,
2680218893Sdim                                            ExprValueKind &VK,
2681218893Sdim                                            SourceLocation Loc,
2682218893Sdim                                            bool isIndirect) {
2683193326Sed  const char *OpSpelling = isIndirect ? "->*" : ".*";
2684193326Sed  // C++ 5.5p2
2685193326Sed  //   The binary operator .* [p3: ->*] binds its second operand, which shall
2686193326Sed  //   be of type "pointer to member of T" (where T is a completely-defined
2687193326Sed  //   class type) [...]
2688193326Sed  QualType RType = rex->getType();
2689198092Srdivacky  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
2690193326Sed  if (!MemPtr) {
2691193326Sed    Diag(Loc, diag::err_bad_memptr_rhs)
2692193326Sed      << OpSpelling << RType << rex->getSourceRange();
2693193326Sed    return QualType();
2694198092Srdivacky  }
2695193326Sed
2696193326Sed  QualType Class(MemPtr->getClass(), 0);
2697193326Sed
2698218893Sdim  // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
2699218893Sdim  // member pointer points must be completely-defined. However, there is no
2700218893Sdim  // reason for this semantic distinction, and the rule is not enforced by
2701218893Sdim  // other compilers. Therefore, we do not check this property, as it is
2702218893Sdim  // likely to be considered a defect.
2703207619Srdivacky
2704193326Sed  // C++ 5.5p2
2705193326Sed  //   [...] to its first operand, which shall be of class T or of a class of
2706193326Sed  //   which T is an unambiguous and accessible base class. [p3: a pointer to
2707193326Sed  //   such a class]
2708193326Sed  QualType LType = lex->getType();
2709193326Sed  if (isIndirect) {
2710198092Srdivacky    if (const PointerType *Ptr = LType->getAs<PointerType>())
2711218893Sdim      LType = Ptr->getPointeeType();
2712193326Sed    else {
2713193326Sed      Diag(Loc, diag::err_bad_memptr_lhs)
2714198893Srdivacky        << OpSpelling << 1 << LType
2715206084Srdivacky        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
2716193326Sed      return QualType();
2717193326Sed    }
2718193326Sed  }
2719193326Sed
2720199482Srdivacky  if (!Context.hasSameUnqualifiedType(Class, LType)) {
2721207619Srdivacky    // If we want to check the hierarchy, we need a complete type.
2722207619Srdivacky    if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
2723207619Srdivacky        << OpSpelling << (int)isIndirect)) {
2724207619Srdivacky      return QualType();
2725207619Srdivacky    }
2726207619Srdivacky    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2727198092Srdivacky                       /*DetectVirtual=*/false);
2728193326Sed    // FIXME: Would it be useful to print full ambiguity paths, or is that
2729193326Sed    // overkill?
2730193326Sed    if (!IsDerivedFrom(LType, Class, Paths) ||
2731193326Sed        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
2732193326Sed      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
2733202879Srdivacky        << (int)isIndirect << lex->getType();
2734193326Sed      return QualType();
2735193326Sed    }
2736202879Srdivacky    // Cast LHS to type of use.
2737202879Srdivacky    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
2738212904Sdim    ExprValueKind VK =
2739212904Sdim        isIndirect ? VK_RValue : CastCategory(lex);
2740212904Sdim
2741212904Sdim    CXXCastPath BasePath;
2742207619Srdivacky    BuildBasePathArray(Paths, BasePath);
2743212904Sdim    ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath);
2744193326Sed  }
2745193326Sed
2746210299Sed  if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) {
2747199512Srdivacky    // Diagnose use of pointer-to-member type which when used as
2748199512Srdivacky    // the functional cast in a pointer-to-member expression.
2749199512Srdivacky    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
2750199512Srdivacky     return QualType();
2751199512Srdivacky  }
2752218893Sdim
2753193326Sed  // C++ 5.5p2
2754193326Sed  //   The result is an object or a function of the type specified by the
2755193326Sed  //   second operand.
2756193326Sed  // The cv qualifiers are the union of those in the pointer and the left side,
2757193326Sed  // in accordance with 5.5p5 and 5.2.5.
2758193326Sed  // FIXME: This returns a dereferenced member function pointer as a normal
2759193326Sed  // function type. However, the only operation valid on such functions is
2760193326Sed  // calling them. There's also a GCC extension to get a function pointer to the
2761193326Sed  // thing, which is another complication, because this type - unlike the type
2762193326Sed  // that is the result of this expression - takes the class as the first
2763193326Sed  // argument.
2764193326Sed  // We probably need a "MemberFunctionClosureType" or something like that.
2765193326Sed  QualType Result = MemPtr->getPointeeType();
2766198092Srdivacky  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
2767218893Sdim
2768218893Sdim  // C++0x [expr.mptr.oper]p6:
2769218893Sdim  //   In a .* expression whose object expression is an rvalue, the program is
2770218893Sdim  //   ill-formed if the second operand is a pointer to member function with
2771218893Sdim  //   ref-qualifier &. In a ->* expression or in a .* expression whose object
2772218893Sdim  //   expression is an lvalue, the program is ill-formed if the second operand
2773218893Sdim  //   is a pointer to member function with ref-qualifier &&.
2774218893Sdim  if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
2775218893Sdim    switch (Proto->getRefQualifier()) {
2776218893Sdim    case RQ_None:
2777218893Sdim      // Do nothing
2778218893Sdim      break;
2779218893Sdim
2780218893Sdim    case RQ_LValue:
2781218893Sdim      if (!isIndirect && !lex->Classify(Context).isLValue())
2782218893Sdim        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2783218893Sdim          << RType << 1 << lex->getSourceRange();
2784218893Sdim      break;
2785218893Sdim
2786218893Sdim    case RQ_RValue:
2787218893Sdim      if (isIndirect || !lex->Classify(Context).isRValue())
2788218893Sdim        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
2789218893Sdim          << RType << 0 << lex->getSourceRange();
2790218893Sdim      break;
2791218893Sdim    }
2792218893Sdim  }
2793218893Sdim
2794218893Sdim  // C++ [expr.mptr.oper]p6:
2795218893Sdim  //   The result of a .* expression whose second operand is a pointer
2796218893Sdim  //   to a data member is of the same value category as its
2797218893Sdim  //   first operand. The result of a .* expression whose second
2798218893Sdim  //   operand is a pointer to a member function is a prvalue. The
2799218893Sdim  //   result of an ->* expression is an lvalue if its second operand
2800218893Sdim  //   is a pointer to data member and a prvalue otherwise.
2801218893Sdim  if (Result->isFunctionType())
2802218893Sdim    VK = VK_RValue;
2803218893Sdim  else if (isIndirect)
2804218893Sdim    VK = VK_LValue;
2805218893Sdim  else
2806218893Sdim    VK = lex->getValueKind();
2807218893Sdim
2808193326Sed  return Result;
2809193326Sed}
2810193326Sed
2811193326Sed/// \brief Try to convert a type to another according to C++0x 5.16p3.
2812193326Sed///
2813193326Sed/// This is part of the parameter validation for the ? operator. If either
2814193326Sed/// value operand is a class type, the two operands are attempted to be
2815193326Sed/// converted to each other. This function does the conversion in one direction.
2816206084Srdivacky/// It returns true if the program is ill-formed and has already been diagnosed
2817206084Srdivacky/// as such.
2818193326Sedstatic bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
2819193326Sed                                SourceLocation QuestionLoc,
2820206084Srdivacky                                bool &HaveConversion,
2821206084Srdivacky                                QualType &ToType) {
2822206084Srdivacky  HaveConversion = false;
2823206084Srdivacky  ToType = To->getType();
2824218893Sdim
2825218893Sdim  InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
2826206084Srdivacky                                                           SourceLocation());
2827193326Sed  // C++0x 5.16p3
2828193326Sed  //   The process for determining whether an operand expression E1 of type T1
2829193326Sed  //   can be converted to match an operand expression E2 of type T2 is defined
2830193326Sed  //   as follows:
2831193326Sed  //   -- If E2 is an lvalue:
2832218893Sdim  bool ToIsLvalue = To->isLValue();
2833206084Srdivacky  if (ToIsLvalue) {
2834193326Sed    //   E1 can be converted to match E2 if E1 can be implicitly converted to
2835193326Sed    //   type "lvalue reference to T2", subject to the constraint that in the
2836193326Sed    //   conversion the reference must bind directly to E1.
2837206084Srdivacky    QualType T = Self.Context.getLValueReferenceType(ToType);
2838206084Srdivacky    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2839218893Sdim
2840206084Srdivacky    InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2841206084Srdivacky    if (InitSeq.isDirectReferenceBinding()) {
2842206084Srdivacky      ToType = T;
2843206084Srdivacky      HaveConversion = true;
2844206084Srdivacky      return false;
2845193326Sed    }
2846218893Sdim
2847206084Srdivacky    if (InitSeq.isAmbiguous())
2848206084Srdivacky      return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2849193326Sed  }
2850204643Srdivacky
2851193326Sed  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
2852193326Sed  //      -- if E1 and E2 have class type, and the underlying class types are
2853193326Sed  //         the same or one is a base class of the other:
2854193326Sed  QualType FTy = From->getType();
2855193326Sed  QualType TTy = To->getType();
2856198092Srdivacky  const RecordType *FRec = FTy->getAs<RecordType>();
2857198092Srdivacky  const RecordType *TRec = TTy->getAs<RecordType>();
2858218893Sdim  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2859206084Srdivacky                       Self.IsDerivedFrom(FTy, TTy);
2860218893Sdim  if (FRec && TRec &&
2861206084Srdivacky      (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
2862193326Sed    //         E1 can be converted to match E2 if the class of T2 is the
2863193326Sed    //         same type as, or a base class of, the class of T1, and
2864193326Sed    //         [cv2 > cv1].
2865204643Srdivacky    if (FRec == TRec || FDerivedFromT) {
2866204643Srdivacky      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
2867206084Srdivacky        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2868206084Srdivacky        InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2869206084Srdivacky        if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2870206084Srdivacky          HaveConversion = true;
2871206084Srdivacky          return false;
2872206084Srdivacky        }
2873218893Sdim
2874206084Srdivacky        if (InitSeq.isAmbiguous())
2875206084Srdivacky          return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2876218893Sdim      }
2877193326Sed    }
2878218893Sdim
2879206084Srdivacky    return false;
2880206084Srdivacky  }
2881218893Sdim
2882206084Srdivacky  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
2883206084Srdivacky  //        implicitly converted to the type that expression E2 would have
2884218893Sdim  //        if E2 were converted to an rvalue (or the type it has, if E2 is
2885206084Srdivacky  //        an rvalue).
2886206084Srdivacky  //
2887206084Srdivacky  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2888206084Srdivacky  // to the array-to-pointer or function-to-pointer conversions.
2889206084Srdivacky  if (!TTy->getAs<TagType>())
2890206084Srdivacky    TTy = TTy.getUnqualifiedType();
2891218893Sdim
2892206084Srdivacky  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2893206084Srdivacky  InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2894218893Sdim  HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2895206084Srdivacky  ToType = TTy;
2896206084Srdivacky  if (InitSeq.isAmbiguous())
2897206084Srdivacky    return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2898193326Sed
2899193326Sed  return false;
2900193326Sed}
2901193326Sed
2902193326Sed/// \brief Try to find a common type for two according to C++0x 5.16p5.
2903193326Sed///
2904193326Sed/// This is part of the parameter validation for the ? operator. If either
2905193326Sed/// value operand is a class type, overload resolution is used to find a
2906193326Sed/// conversion to a common type.
2907193326Sedstatic bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2908218893Sdim                                    SourceLocation QuestionLoc) {
2909193326Sed  Expr *Args[2] = { LHS, RHS };
2910218893Sdim  OverloadCandidateSet CandidateSet(QuestionLoc);
2911218893Sdim  Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
2912218893Sdim                                    CandidateSet);
2913193326Sed
2914193326Sed  OverloadCandidateSet::iterator Best;
2915218893Sdim  switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
2916200583Srdivacky    case OR_Success:
2917193326Sed      // We found a match. Perform the conversions on the arguments and move on.
2918193326Sed      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
2919201361Srdivacky                                         Best->Conversions[0], Sema::AA_Converting) ||
2920193326Sed          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
2921201361Srdivacky                                         Best->Conversions[1], Sema::AA_Converting))
2922193326Sed        break;
2923193326Sed      return false;
2924193326Sed
2925200583Srdivacky    case OR_No_Viable_Function:
2926218893Sdim
2927218893Sdim      // Emit a better diagnostic if one of the expressions is a null pointer
2928218893Sdim      // constant and the other is a pointer type. In this case, the user most
2929218893Sdim      // likely forgot to take the address of the other expression.
2930218893Sdim      if (Self.DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
2931218893Sdim        return true;
2932218893Sdim
2933218893Sdim      Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2934193326Sed        << LHS->getType() << RHS->getType()
2935193326Sed        << LHS->getSourceRange() << RHS->getSourceRange();
2936193326Sed      return true;
2937193326Sed
2938200583Srdivacky    case OR_Ambiguous:
2939218893Sdim      Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
2940193326Sed        << LHS->getType() << RHS->getType()
2941193326Sed        << LHS->getSourceRange() << RHS->getSourceRange();
2942193326Sed      // FIXME: Print the possible common types by printing the return types of
2943193326Sed      // the viable candidates.
2944193326Sed      break;
2945193326Sed
2946200583Srdivacky    case OR_Deleted:
2947193326Sed      assert(false && "Conditional operator has only built-in overloads");
2948193326Sed      break;
2949193326Sed  }
2950193326Sed  return true;
2951193326Sed}
2952193326Sed
2953193326Sed/// \brief Perform an "extended" implicit conversion as returned by
2954193326Sed/// TryClassUnification.
2955206084Srdivackystatic bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2956206084Srdivacky  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2957206084Srdivacky  InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2958206084Srdivacky                                                           SourceLocation());
2959206084Srdivacky  InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2960212904Sdim  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1));
2961206084Srdivacky  if (Result.isInvalid())
2962193326Sed    return true;
2963218893Sdim
2964206084Srdivacky  E = Result.takeAs<Expr>();
2965193326Sed  return false;
2966193326Sed}
2967193326Sed
2968193326Sed/// \brief Check the operands of ?: under C++ semantics.
2969193326Sed///
2970193326Sed/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2971193326Sed/// extension. In this case, LHS == Cond. (But they're not aliases.)
2972193326SedQualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2973218893Sdim                                           ExprValueKind &VK, ExprObjectKind &OK,
2974193326Sed                                           SourceLocation QuestionLoc) {
2975193326Sed  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2976193326Sed  // interface pointers.
2977193326Sed
2978193326Sed  // C++0x 5.16p1
2979193326Sed  //   The first expression is contextually converted to bool.
2980193326Sed  if (!Cond->isTypeDependent()) {
2981193326Sed    if (CheckCXXBooleanCondition(Cond))
2982193326Sed      return QualType();
2983193326Sed  }
2984193326Sed
2985218893Sdim  // Assume r-value.
2986218893Sdim  VK = VK_RValue;
2987218893Sdim  OK = OK_Ordinary;
2988218893Sdim
2989193326Sed  // Either of the arguments dependent?
2990193326Sed  if (LHS->isTypeDependent() || RHS->isTypeDependent())
2991193326Sed    return Context.DependentTy;
2992193326Sed
2993193326Sed  // C++0x 5.16p2
2994193326Sed  //   If either the second or the third operand has type (cv) void, ...
2995193326Sed  QualType LTy = LHS->getType();
2996193326Sed  QualType RTy = RHS->getType();
2997193326Sed  bool LVoid = LTy->isVoidType();
2998193326Sed  bool RVoid = RTy->isVoidType();
2999193326Sed  if (LVoid || RVoid) {
3000193326Sed    //   ... then the [l2r] conversions are performed on the second and third
3001193326Sed    //   operands ...
3002203955Srdivacky    DefaultFunctionArrayLvalueConversion(LHS);
3003203955Srdivacky    DefaultFunctionArrayLvalueConversion(RHS);
3004193326Sed    LTy = LHS->getType();
3005193326Sed    RTy = RHS->getType();
3006193326Sed
3007193326Sed    //   ... and one of the following shall hold:
3008193326Sed    //   -- The second or the third operand (but not both) is a throw-
3009193326Sed    //      expression; the result is of the type of the other and is an rvalue.
3010193326Sed    bool LThrow = isa<CXXThrowExpr>(LHS);
3011193326Sed    bool RThrow = isa<CXXThrowExpr>(RHS);
3012193326Sed    if (LThrow && !RThrow)
3013193326Sed      return RTy;
3014193326Sed    if (RThrow && !LThrow)
3015193326Sed      return LTy;
3016193326Sed
3017193326Sed    //   -- Both the second and third operands have type void; the result is of
3018193326Sed    //      type void and is an rvalue.
3019193326Sed    if (LVoid && RVoid)
3020193326Sed      return Context.VoidTy;
3021193326Sed
3022193326Sed    // Neither holds, error.
3023193326Sed    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3024193326Sed      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3025193326Sed      << LHS->getSourceRange() << RHS->getSourceRange();
3026193326Sed    return QualType();
3027193326Sed  }
3028193326Sed
3029193326Sed  // Neither is void.
3030193326Sed
3031193326Sed  // C++0x 5.16p3
3032193326Sed  //   Otherwise, if the second and third operand have different types, and
3033193326Sed  //   either has (cv) class type, and attempt is made to convert each of those
3034193326Sed  //   operands to the other.
3035218893Sdim  if (!Context.hasSameType(LTy, RTy) &&
3036193326Sed      (LTy->isRecordType() || RTy->isRecordType())) {
3037193326Sed    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3038193326Sed    // These return true if a single direction is already ambiguous.
3039206084Srdivacky    QualType L2RType, R2LType;
3040206084Srdivacky    bool HaveL2R, HaveR2L;
3041206084Srdivacky    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
3042193326Sed      return QualType();
3043206084Srdivacky    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
3044193326Sed      return QualType();
3045218893Sdim
3046193326Sed    //   If both can be converted, [...] the program is ill-formed.
3047193326Sed    if (HaveL2R && HaveR2L) {
3048193326Sed      Diag(QuestionLoc, diag::err_conditional_ambiguous)
3049193326Sed        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
3050193326Sed      return QualType();
3051193326Sed    }
3052193326Sed
3053193326Sed    //   If exactly one conversion is possible, that conversion is applied to
3054193326Sed    //   the chosen operand and the converted operands are used in place of the
3055193326Sed    //   original operands for the remainder of this section.
3056193326Sed    if (HaveL2R) {
3057206084Srdivacky      if (ConvertForConditional(*this, LHS, L2RType))
3058193326Sed        return QualType();
3059193326Sed      LTy = LHS->getType();
3060193326Sed    } else if (HaveR2L) {
3061206084Srdivacky      if (ConvertForConditional(*this, RHS, R2LType))
3062193326Sed        return QualType();
3063193326Sed      RTy = RHS->getType();
3064193326Sed    }
3065193326Sed  }
3066193326Sed
3067193326Sed  // C++0x 5.16p4
3068218893Sdim  //   If the second and third operands are glvalues of the same value
3069218893Sdim  //   category and have the same type, the result is of that type and
3070218893Sdim  //   value category and it is a bit-field if the second or the third
3071218893Sdim  //   operand is a bit-field, or if both are bit-fields.
3072218893Sdim  // We only extend this to bitfields, not to the crazy other kinds of
3073218893Sdim  // l-values.
3074206084Srdivacky  bool Same = Context.hasSameType(LTy, RTy);
3075218893Sdim  if (Same &&
3076218893Sdim      LHS->isGLValue() &&
3077218893Sdim      LHS->getValueKind() == RHS->getValueKind() &&
3078218893Sdim      LHS->isOrdinaryOrBitFieldObject() &&
3079218893Sdim      RHS->isOrdinaryOrBitFieldObject()) {
3080218893Sdim    VK = LHS->getValueKind();
3081218893Sdim    if (LHS->getObjectKind() == OK_BitField ||
3082218893Sdim        RHS->getObjectKind() == OK_BitField)
3083218893Sdim      OK = OK_BitField;
3084193326Sed    return LTy;
3085218893Sdim  }
3086193326Sed
3087193326Sed  // C++0x 5.16p5
3088193326Sed  //   Otherwise, the result is an rvalue. If the second and third operands
3089193326Sed  //   do not have the same type, and either has (cv) class type, ...
3090193326Sed  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3091193326Sed    //   ... overload resolution is used to determine the conversions (if any)
3092193326Sed    //   to be applied to the operands. If the overload resolution fails, the
3093193326Sed    //   program is ill-formed.
3094193326Sed    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3095193326Sed      return QualType();
3096193326Sed  }
3097193326Sed
3098193326Sed  // C++0x 5.16p6
3099193326Sed  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3100193326Sed  //   conversions are performed on the second and third operands.
3101203955Srdivacky  DefaultFunctionArrayLvalueConversion(LHS);
3102203955Srdivacky  DefaultFunctionArrayLvalueConversion(RHS);
3103193326Sed  LTy = LHS->getType();
3104193326Sed  RTy = RHS->getType();
3105193326Sed
3106193326Sed  //   After those conversions, one of the following shall hold:
3107193326Sed  //   -- The second and third operands have the same type; the result
3108208600Srdivacky  //      is of that type. If the operands have class type, the result
3109208600Srdivacky  //      is a prvalue temporary of the result type, which is
3110208600Srdivacky  //      copy-initialized from either the second operand or the third
3111208600Srdivacky  //      operand depending on the value of the first operand.
3112208600Srdivacky  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3113208600Srdivacky    if (LTy->isRecordType()) {
3114208600Srdivacky      // The operands have class type. Make a temporary copy.
3115208600Srdivacky      InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
3116218893Sdim      ExprResult LHSCopy = PerformCopyInitialization(Entity,
3117218893Sdim                                                     SourceLocation(),
3118218893Sdim                                                     Owned(LHS));
3119208600Srdivacky      if (LHSCopy.isInvalid())
3120208600Srdivacky        return QualType();
3121218893Sdim
3122218893Sdim      ExprResult RHSCopy = PerformCopyInitialization(Entity,
3123218893Sdim                                                     SourceLocation(),
3124218893Sdim                                                     Owned(RHS));
3125208600Srdivacky      if (RHSCopy.isInvalid())
3126208600Srdivacky        return QualType();
3127218893Sdim
3128208600Srdivacky      LHS = LHSCopy.takeAs<Expr>();
3129208600Srdivacky      RHS = RHSCopy.takeAs<Expr>();
3130208600Srdivacky    }
3131208600Srdivacky
3132193326Sed    return LTy;
3133208600Srdivacky  }
3134193326Sed
3135208600Srdivacky  // Extension: conditional operator involving vector types.
3136218893Sdim  if (LTy->isVectorType() || RTy->isVectorType())
3137208600Srdivacky    return CheckVectorOperands(QuestionLoc, LHS, RHS);
3138208600Srdivacky
3139193326Sed  //   -- The second and third operands have arithmetic or enumeration type;
3140193326Sed  //      the usual arithmetic conversions are performed to bring them to a
3141193326Sed  //      common type, and the result is of that type.
3142193326Sed  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3143193326Sed    UsualArithmeticConversions(LHS, RHS);
3144193326Sed    return LHS->getType();
3145193326Sed  }
3146193326Sed
3147193326Sed  //   -- The second and third operands have pointer type, or one has pointer
3148193326Sed  //      type and the other is a null pointer constant; pointer conversions
3149193326Sed  //      and qualification conversions are performed to bring them to their
3150193326Sed  //      composite pointer type. The result is of the composite pointer type.
3151202379Srdivacky  //   -- The second and third operands have pointer to member type, or one has
3152202379Srdivacky  //      pointer to member type and the other is a null pointer constant;
3153202379Srdivacky  //      pointer to member conversions and qualification conversions are
3154202379Srdivacky  //      performed to bring them to a common type, whose cv-qualification
3155202379Srdivacky  //      shall match the cv-qualification of either the second or the third
3156202379Srdivacky  //      operand. The result is of the common type.
3157204643Srdivacky  bool NonStandardCompositeType = false;
3158207619Srdivacky  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
3159204643Srdivacky                              isSFINAEContext()? 0 : &NonStandardCompositeType);
3160204643Srdivacky  if (!Composite.isNull()) {
3161204643Srdivacky    if (NonStandardCompositeType)
3162218893Sdim      Diag(QuestionLoc,
3163204643Srdivacky           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3164204643Srdivacky        << LTy << RTy << Composite
3165204643Srdivacky        << LHS->getSourceRange() << RHS->getSourceRange();
3166218893Sdim
3167193326Sed    return Composite;
3168204643Srdivacky  }
3169218893Sdim
3170206084Srdivacky  // Similarly, attempt to find composite type of two objective-c pointers.
3171200583Srdivacky  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3172200583Srdivacky  if (!Composite.isNull())
3173200583Srdivacky    return Composite;
3174193326Sed
3175218893Sdim  // Check if we are using a null with a non-pointer type.
3176218893Sdim  if (DiagnoseConditionalForNull(LHS, RHS, QuestionLoc))
3177218893Sdim    return QualType();
3178218893Sdim
3179193326Sed  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3180193326Sed    << LHS->getType() << RHS->getType()
3181193326Sed    << LHS->getSourceRange() << RHS->getSourceRange();
3182193326Sed  return QualType();
3183193326Sed}
3184193326Sed
3185193326Sed/// \brief Find a merged pointer type and convert the two expressions to it.
3186193326Sed///
3187198092Srdivacky/// This finds the composite pointer type (or member pointer type) for @p E1
3188198092Srdivacky/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3189198092Srdivacky/// type and returns it.
3190193326Sed/// It does not emit diagnostics.
3191204643Srdivacky///
3192207619Srdivacky/// \param Loc The location of the operator requiring these two expressions to
3193207619Srdivacky/// be converted to the composite pointer type.
3194207619Srdivacky///
3195204643Srdivacky/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3196204643Srdivacky/// a non-standard (but still sane) composite type to which both expressions
3197204643Srdivacky/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3198204643Srdivacky/// will be set true.
3199218893SdimQualType Sema::FindCompositePointerType(SourceLocation Loc,
3200207619Srdivacky                                        Expr *&E1, Expr *&E2,
3201204643Srdivacky                                        bool *NonStandardCompositeType) {
3202204643Srdivacky  if (NonStandardCompositeType)
3203204643Srdivacky    *NonStandardCompositeType = false;
3204218893Sdim
3205193326Sed  assert(getLangOptions().CPlusPlus && "This function assumes C++");
3206193326Sed  QualType T1 = E1->getType(), T2 = E2->getType();
3207193326Sed
3208200583Srdivacky  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3209200583Srdivacky      !T2->isAnyPointerType() && !T2->isMemberPointerType())
3210198092Srdivacky   return QualType();
3211198092Srdivacky
3212193326Sed  // C++0x 5.9p2
3213193326Sed  //   Pointer conversions and qualification conversions are performed on
3214193326Sed  //   pointer operands to bring them to their composite pointer type. If
3215193326Sed  //   one operand is a null pointer constant, the composite pointer type is
3216193326Sed  //   the type of the other operand.
3217198092Srdivacky  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3218198398Srdivacky    if (T2->isMemberPointerType())
3219212904Sdim      ImpCastExprToType(E1, T2, CK_NullToMemberPointer);
3220198398Srdivacky    else
3221218893Sdim      ImpCastExprToType(E1, T2, CK_NullToPointer);
3222193326Sed    return T2;
3223193326Sed  }
3224198092Srdivacky  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3225198398Srdivacky    if (T1->isMemberPointerType())
3226212904Sdim      ImpCastExprToType(E2, T1, CK_NullToMemberPointer);
3227198398Srdivacky    else
3228218893Sdim      ImpCastExprToType(E2, T1, CK_NullToPointer);
3229193326Sed    return T1;
3230193326Sed  }
3231198092Srdivacky
3232198092Srdivacky  // Now both have to be pointers or member pointers.
3233199482Srdivacky  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3234199482Srdivacky      (!T2->isPointerType() && !T2->isMemberPointerType()))
3235193326Sed    return QualType();
3236193326Sed
3237193326Sed  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
3238193326Sed  //   the other has type "pointer to cv2 T" and the composite pointer type is
3239193326Sed  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3240193326Sed  //   Otherwise, the composite pointer type is a pointer type similar to the
3241193326Sed  //   type of one of the operands, with a cv-qualification signature that is
3242193326Sed  //   the union of the cv-qualification signatures of the operand types.
3243193326Sed  // In practice, the first part here is redundant; it's subsumed by the second.
3244193326Sed  // What we do here is, we build the two possible composite types, and try the
3245193326Sed  // conversions in both directions. If only one works, or if the two composite
3246193326Sed  // types are the same, we have succeeded.
3247198092Srdivacky  // FIXME: extended qualifiers?
3248199482Srdivacky  typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3249199482Srdivacky  QualifierVector QualifierUnion;
3250199482Srdivacky  typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3251199482Srdivacky      ContainingClassVector;
3252199482Srdivacky  ContainingClassVector MemberOfClass;
3253199482Srdivacky  QualType Composite1 = Context.getCanonicalType(T1),
3254199482Srdivacky           Composite2 = Context.getCanonicalType(T2);
3255218893Sdim  unsigned NeedConstBefore = 0;
3256198092Srdivacky  do {
3257198092Srdivacky    const PointerType *Ptr1, *Ptr2;
3258198092Srdivacky    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3259198092Srdivacky        (Ptr2 = Composite2->getAs<PointerType>())) {
3260198092Srdivacky      Composite1 = Ptr1->getPointeeType();
3261198092Srdivacky      Composite2 = Ptr2->getPointeeType();
3262218893Sdim
3263204643Srdivacky      // If we're allowed to create a non-standard composite type, keep track
3264218893Sdim      // of where we need to fill in additional 'const' qualifiers.
3265204643Srdivacky      if (NonStandardCompositeType &&
3266204643Srdivacky          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3267204643Srdivacky        NeedConstBefore = QualifierUnion.size();
3268218893Sdim
3269198092Srdivacky      QualifierUnion.push_back(
3270198092Srdivacky                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3271198092Srdivacky      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3272198092Srdivacky      continue;
3273198092Srdivacky    }
3274198092Srdivacky
3275198092Srdivacky    const MemberPointerType *MemPtr1, *MemPtr2;
3276198092Srdivacky    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3277198092Srdivacky        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3278198092Srdivacky      Composite1 = MemPtr1->getPointeeType();
3279198092Srdivacky      Composite2 = MemPtr2->getPointeeType();
3280218893Sdim
3281204643Srdivacky      // If we're allowed to create a non-standard composite type, keep track
3282218893Sdim      // of where we need to fill in additional 'const' qualifiers.
3283204643Srdivacky      if (NonStandardCompositeType &&
3284204643Srdivacky          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3285204643Srdivacky        NeedConstBefore = QualifierUnion.size();
3286218893Sdim
3287198092Srdivacky      QualifierUnion.push_back(
3288198092Srdivacky                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3289198092Srdivacky      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3290198092Srdivacky                                             MemPtr2->getClass()));
3291198092Srdivacky      continue;
3292198092Srdivacky    }
3293198092Srdivacky
3294198092Srdivacky    // FIXME: block pointer types?
3295198092Srdivacky
3296198092Srdivacky    // Cannot unwrap any more types.
3297198092Srdivacky    break;
3298198092Srdivacky  } while (true);
3299198092Srdivacky
3300204643Srdivacky  if (NeedConstBefore && NonStandardCompositeType) {
3301204643Srdivacky    // Extension: Add 'const' to qualifiers that come before the first qualifier
3302218893Sdim    // mismatch, so that our (non-standard!) composite type meets the
3303204643Srdivacky    // requirements of C++ [conv.qual]p4 bullet 3.
3304204643Srdivacky    for (unsigned I = 0; I != NeedConstBefore; ++I) {
3305204643Srdivacky      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3306204643Srdivacky        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3307204643Srdivacky        *NonStandardCompositeType = true;
3308204643Srdivacky      }
3309204643Srdivacky    }
3310204643Srdivacky  }
3311218893Sdim
3312198092Srdivacky  // Rewrap the composites as pointers or member pointers with the union CVRs.
3313199482Srdivacky  ContainingClassVector::reverse_iterator MOC
3314199482Srdivacky    = MemberOfClass.rbegin();
3315199482Srdivacky  for (QualifierVector::reverse_iterator
3316199482Srdivacky         I = QualifierUnion.rbegin(),
3317199482Srdivacky         E = QualifierUnion.rend();
3318198092Srdivacky       I != E; (void)++I, ++MOC) {
3319198092Srdivacky    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
3320198092Srdivacky    if (MOC->first && MOC->second) {
3321198092Srdivacky      // Rebuild member pointer type
3322198092Srdivacky      Composite1 = Context.getMemberPointerType(
3323198092Srdivacky                                    Context.getQualifiedType(Composite1, Quals),
3324198092Srdivacky                                    MOC->first);
3325198092Srdivacky      Composite2 = Context.getMemberPointerType(
3326198092Srdivacky                                    Context.getQualifiedType(Composite2, Quals),
3327198092Srdivacky                                    MOC->second);
3328198092Srdivacky    } else {
3329198092Srdivacky      // Rebuild pointer type
3330198092Srdivacky      Composite1
3331198092Srdivacky        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3332198092Srdivacky      Composite2
3333198092Srdivacky        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
3334198092Srdivacky    }
3335193326Sed  }
3336193326Sed
3337207619Srdivacky  // Try to convert to the first composite pointer type.
3338207619Srdivacky  InitializedEntity Entity1
3339207619Srdivacky    = InitializedEntity::InitializeTemporary(Composite1);
3340207619Srdivacky  InitializationKind Kind
3341207619Srdivacky    = InitializationKind::CreateCopy(Loc, SourceLocation());
3342207619Srdivacky  InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3343207619Srdivacky  InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
3344198092Srdivacky
3345207619Srdivacky  if (E1ToC1 && E2ToC1) {
3346207619Srdivacky    // Conversion to Composite1 is viable.
3347207619Srdivacky    if (!Context.hasSameType(Composite1, Composite2)) {
3348207619Srdivacky      // Composite2 is a different type from Composite1. Check whether
3349207619Srdivacky      // Composite2 is also viable.
3350207619Srdivacky      InitializedEntity Entity2
3351207619Srdivacky        = InitializedEntity::InitializeTemporary(Composite2);
3352207619Srdivacky      InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3353207619Srdivacky      InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3354207619Srdivacky      if (E1ToC2 && E2ToC2) {
3355207619Srdivacky        // Both Composite1 and Composite2 are viable and are different;
3356207619Srdivacky        // this is an ambiguity.
3357207619Srdivacky        return QualType();
3358207619Srdivacky      }
3359207619Srdivacky    }
3360207619Srdivacky
3361207619Srdivacky    // Convert E1 to Composite1
3362212904Sdim    ExprResult E1Result
3363212904Sdim      = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
3364207619Srdivacky    if (E1Result.isInvalid())
3365207619Srdivacky      return QualType();
3366207619Srdivacky    E1 = E1Result.takeAs<Expr>();
3367207619Srdivacky
3368207619Srdivacky    // Convert E2 to Composite1
3369212904Sdim    ExprResult E2Result
3370212904Sdim      = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
3371207619Srdivacky    if (E2Result.isInvalid())
3372207619Srdivacky      return QualType();
3373207619Srdivacky    E2 = E2Result.takeAs<Expr>();
3374218893Sdim
3375207619Srdivacky    return Composite1;
3376193326Sed  }
3377193326Sed
3378207619Srdivacky  // Check whether Composite2 is viable.
3379207619Srdivacky  InitializedEntity Entity2
3380207619Srdivacky    = InitializedEntity::InitializeTemporary(Composite2);
3381207619Srdivacky  InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3382207619Srdivacky  InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3383207619Srdivacky  if (!E1ToC2 || !E2ToC2)
3384207619Srdivacky    return QualType();
3385218893Sdim
3386207619Srdivacky  // Convert E1 to Composite2
3387212904Sdim  ExprResult E1Result
3388212904Sdim    = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
3389207619Srdivacky  if (E1Result.isInvalid())
3390207619Srdivacky    return QualType();
3391207619Srdivacky  E1 = E1Result.takeAs<Expr>();
3392218893Sdim
3393207619Srdivacky  // Convert E2 to Composite2
3394212904Sdim  ExprResult E2Result
3395212904Sdim    = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
3396207619Srdivacky  if (E2Result.isInvalid())
3397207619Srdivacky    return QualType();
3398207619Srdivacky  E2 = E2Result.takeAs<Expr>();
3399218893Sdim
3400207619Srdivacky  return Composite2;
3401193326Sed}
3402193326Sed
3403212904SdimExprResult Sema::MaybeBindToTemporary(Expr *E) {
3404218893Sdim  if (!E)
3405218893Sdim    return ExprError();
3406218893Sdim
3407198092Srdivacky  if (!Context.getLangOptions().CPlusPlus)
3408198092Srdivacky    return Owned(E);
3409198092Srdivacky
3410201361Srdivacky  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3411201361Srdivacky
3412198092Srdivacky  const RecordType *RT = E->getType()->getAs<RecordType>();
3413193326Sed  if (!RT)
3414193326Sed    return Owned(E);
3415198092Srdivacky
3416218893Sdim  // If the result is a glvalue, we shouldn't bind it.
3417218893Sdim  if (E->Classify(Context).isGLValue())
3418218893Sdim    return Owned(E);
3419203955Srdivacky
3420203955Srdivacky  // That should be enough to guarantee that this type is complete.
3421203955Srdivacky  // If it has a trivial destructor, we can avoid the extra copy.
3422203955Srdivacky  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3423212904Sdim  if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
3424203955Srdivacky    return Owned(E);
3425203955Srdivacky
3426210299Sed  CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
3427193326Sed  ExprTemporaries.push_back(Temp);
3428210299Sed  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
3429198092Srdivacky    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
3430207619Srdivacky    CheckDestructorAccess(E->getExprLoc(), Destructor,
3431207619Srdivacky                          PDiag(diag::err_access_dtor_temp)
3432207619Srdivacky                            << E->getType());
3433207619Srdivacky  }
3434193326Sed  // FIXME: Add the temporary to the temporaries vector.
3435193326Sed  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3436193326Sed}
3437193326Sed
3438218893SdimExpr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
3439193576Sed  assert(SubExpr && "sub expression can't be null!");
3440198092Srdivacky
3441200583Srdivacky  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3442200583Srdivacky  assert(ExprTemporaries.size() >= FirstTemporary);
3443200583Srdivacky  if (ExprTemporaries.size() == FirstTemporary)
3444193576Sed    return SubExpr;
3445198092Srdivacky
3446218893Sdim  Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3447218893Sdim                                     &ExprTemporaries[FirstTemporary],
3448218893Sdim                                     ExprTemporaries.size() - FirstTemporary);
3449200583Srdivacky  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3450200583Srdivacky                        ExprTemporaries.end());
3451198092Srdivacky
3452193576Sed  return E;
3453193576Sed}
3454193576Sed
3455218893SdimExprResult
3456218893SdimSema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
3457201361Srdivacky  if (SubExpr.isInvalid())
3458201361Srdivacky    return ExprError();
3459218893Sdim
3460218893Sdim  return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
3461201361Srdivacky}
3462201361Srdivacky
3463218893SdimStmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
3464218893Sdim  assert(SubStmt && "sub statement can't be null!");
3465218893Sdim
3466201361Srdivacky  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3467201361Srdivacky  assert(ExprTemporaries.size() >= FirstTemporary);
3468218893Sdim  if (ExprTemporaries.size() == FirstTemporary)
3469218893Sdim    return SubStmt;
3470201361Srdivacky
3471218893Sdim  // FIXME: In order to attach the temporaries, wrap the statement into
3472218893Sdim  // a StmtExpr; currently this is only used for asm statements.
3473218893Sdim  // This is hacky, either create a new CXXStmtWithTemporaries statement or
3474218893Sdim  // a new AsmStmtWithTemporaries.
3475218893Sdim  CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3476218893Sdim                                                      SourceLocation(),
3477218893Sdim                                                      SourceLocation());
3478218893Sdim  Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3479218893Sdim                                   SourceLocation());
3480218893Sdim  return MaybeCreateExprWithCleanups(E);
3481201361Srdivacky}
3482201361Srdivacky
3483212904SdimExprResult
3484212904SdimSema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
3485212904Sdim                                   tok::TokenKind OpKind, ParsedType &ObjectType,
3486204643Srdivacky                                   bool &MayBePseudoDestructor) {
3487198092Srdivacky  // Since this might be a postfix expression, get rid of ParenListExprs.
3488212904Sdim  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3489212904Sdim  if (Result.isInvalid()) return ExprError();
3490212904Sdim  Base = Result.get();
3491198092Srdivacky
3492212904Sdim  QualType BaseType = Base->getType();
3493204643Srdivacky  MayBePseudoDestructor = false;
3494198092Srdivacky  if (BaseType->isDependentType()) {
3495198954Srdivacky    // If we have a pointer to a dependent type and are using the -> operator,
3496198954Srdivacky    // the object type is the type that the pointer points to. We might still
3497198954Srdivacky    // have enough information about that type to do something useful.
3498198954Srdivacky    if (OpKind == tok::arrow)
3499198954Srdivacky      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3500198954Srdivacky        BaseType = Ptr->getPointeeType();
3501218893Sdim
3502212904Sdim    ObjectType = ParsedType::make(BaseType);
3503204643Srdivacky    MayBePseudoDestructor = true;
3504212904Sdim    return Owned(Base);
3505198092Srdivacky  }
3506198092Srdivacky
3507198092Srdivacky  // C++ [over.match.oper]p8:
3508198092Srdivacky  //   [...] When operator->returns, the operator-> is applied  to the value
3509198092Srdivacky  //   returned, with the original second operand.
3510198092Srdivacky  if (OpKind == tok::arrow) {
3511198092Srdivacky    // The set of types we've considered so far.
3512198092Srdivacky    llvm::SmallPtrSet<CanQualType,8> CTypes;
3513198092Srdivacky    llvm::SmallVector<SourceLocation, 8> Locations;
3514198092Srdivacky    CTypes.insert(Context.getCanonicalType(BaseType));
3515218893Sdim
3516198092Srdivacky    while (BaseType->isRecordType()) {
3517212904Sdim      Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3518212904Sdim      if (Result.isInvalid())
3519198092Srdivacky        return ExprError();
3520212904Sdim      Base = Result.get();
3521212904Sdim      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
3522198092Srdivacky        Locations.push_back(OpCall->getDirectCallee()->getLocation());
3523212904Sdim      BaseType = Base->getType();
3524198092Srdivacky      CanQualType CBaseType = Context.getCanonicalType(BaseType);
3525198092Srdivacky      if (!CTypes.insert(CBaseType)) {
3526198092Srdivacky        Diag(OpLoc, diag::err_operator_arrow_circular);
3527198092Srdivacky        for (unsigned i = 0; i < Locations.size(); i++)
3528198092Srdivacky          Diag(Locations[i], diag::note_declared_at);
3529198092Srdivacky        return ExprError();
3530198092Srdivacky      }
3531198092Srdivacky    }
3532199990Srdivacky
3533199990Srdivacky    if (BaseType->isPointerType())
3534199990Srdivacky      BaseType = BaseType->getPointeeType();
3535198092Srdivacky  }
3536198092Srdivacky
3537198092Srdivacky  // We could end up with various non-record types here, such as extended
3538198092Srdivacky  // vector types or Objective-C interfaces. Just return early and let
3539198092Srdivacky  // ActOnMemberReferenceExpr do the work.
3540198092Srdivacky  if (!BaseType->isRecordType()) {
3541198092Srdivacky    // C++ [basic.lookup.classref]p2:
3542198092Srdivacky    //   [...] If the type of the object expression is of pointer to scalar
3543198092Srdivacky    //   type, the unqualified-id is looked up in the context of the complete
3544198092Srdivacky    //   postfix-expression.
3545204643Srdivacky    //
3546204643Srdivacky    // This also indicates that we should be parsing a
3547204643Srdivacky    // pseudo-destructor-name.
3548212904Sdim    ObjectType = ParsedType();
3549204643Srdivacky    MayBePseudoDestructor = true;
3550212904Sdim    return Owned(Base);
3551198092Srdivacky  }
3552198092Srdivacky
3553199482Srdivacky  // The object type must be complete (or dependent).
3554199482Srdivacky  if (!BaseType->isDependentType() &&
3555218893Sdim      RequireCompleteType(OpLoc, BaseType,
3556199482Srdivacky                          PDiag(diag::err_incomplete_member_access)))
3557199482Srdivacky    return ExprError();
3558218893Sdim
3559198092Srdivacky  // C++ [basic.lookup.classref]p2:
3560198092Srdivacky  //   If the id-expression in a class member access (5.2.5) is an
3561199482Srdivacky  //   unqualified-id, and the type of the object expression is of a class
3562198092Srdivacky  //   type C (or of pointer to a class type C), the unqualified-id is looked
3563198092Srdivacky  //   up in the scope of class C. [...]
3564212904Sdim  ObjectType = ParsedType::make(BaseType);
3565198092Srdivacky  return move(Base);
3566198092Srdivacky}
3567198092Srdivacky
3568212904SdimExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
3569212904Sdim                                                   Expr *MemExpr) {
3570204643Srdivacky  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
3571212904Sdim  Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3572212904Sdim    << isa<CXXPseudoDestructorExpr>(MemExpr)
3573206084Srdivacky    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
3574218893Sdim
3575204643Srdivacky  return ActOnCallExpr(/*Scope*/ 0,
3576212904Sdim                       MemExpr,
3577204643Srdivacky                       /*LPLoc*/ ExpectedLParenLoc,
3578212904Sdim                       MultiExprArg(),
3579204643Srdivacky                       /*RPLoc*/ ExpectedLParenLoc);
3580204643Srdivacky}
3581204643Srdivacky
3582212904SdimExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
3583204643Srdivacky                                                       SourceLocation OpLoc,
3584204643Srdivacky                                                       tok::TokenKind OpKind,
3585204643Srdivacky                                                       const CXXScopeSpec &SS,
3586204643Srdivacky                                                 TypeSourceInfo *ScopeTypeInfo,
3587204643Srdivacky                                                       SourceLocation CCLoc,
3588204643Srdivacky                                                       SourceLocation TildeLoc,
3589204643Srdivacky                                         PseudoDestructorTypeStorage Destructed,
3590204643Srdivacky                                                       bool HasTrailingLParen) {
3591204643Srdivacky  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
3592218893Sdim
3593204643Srdivacky  // C++ [expr.pseudo]p2:
3594218893Sdim  //   The left-hand side of the dot operator shall be of scalar type. The
3595204643Srdivacky  //   left-hand side of the arrow operator shall be of pointer to scalar type.
3596218893Sdim  //   This scalar type is the object type.
3597212904Sdim  QualType ObjectType = Base->getType();
3598204643Srdivacky  if (OpKind == tok::arrow) {
3599204643Srdivacky    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3600204643Srdivacky      ObjectType = Ptr->getPointeeType();
3601212904Sdim    } else if (!Base->isTypeDependent()) {
3602204643Srdivacky      // The user wrote "p->" when she probably meant "p."; fix it.
3603204643Srdivacky      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3604204643Srdivacky        << ObjectType << true
3605206084Srdivacky        << FixItHint::CreateReplacement(OpLoc, ".");
3606204643Srdivacky      if (isSFINAEContext())
3607204643Srdivacky        return ExprError();
3608218893Sdim
3609204643Srdivacky      OpKind = tok::period;
3610204643Srdivacky    }
3611204643Srdivacky  }
3612218893Sdim
3613204643Srdivacky  if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3614204643Srdivacky    Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
3615212904Sdim      << ObjectType << Base->getSourceRange();
3616204643Srdivacky    return ExprError();
3617204643Srdivacky  }
3618204643Srdivacky
3619204643Srdivacky  // C++ [expr.pseudo]p2:
3620218893Sdim  //   [...] The cv-unqualified versions of the object type and of the type
3621204643Srdivacky  //   designated by the pseudo-destructor-name shall be the same type.
3622204643Srdivacky  if (DestructedTypeInfo) {
3623204643Srdivacky    QualType DestructedType = DestructedTypeInfo->getType();
3624204643Srdivacky    SourceLocation DestructedTypeStart
3625208600Srdivacky      = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
3626204643Srdivacky    if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3627204643Srdivacky        !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3628204643Srdivacky      Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
3629212904Sdim        << ObjectType << DestructedType << Base->getSourceRange()
3630208600Srdivacky        << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
3631218893Sdim
3632204643Srdivacky      // Recover by setting the destructed type to the object type.
3633204643Srdivacky      DestructedType = ObjectType;
3634204643Srdivacky      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
3635204643Srdivacky                                                           DestructedTypeStart);
3636204643Srdivacky      Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3637204643Srdivacky    }
3638204643Srdivacky  }
3639218893Sdim
3640204643Srdivacky  // C++ [expr.pseudo]p2:
3641204643Srdivacky  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
3642204643Srdivacky  //   form
3643204643Srdivacky  //
3644218893Sdim  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
3645204643Srdivacky  //
3646204643Srdivacky  //   shall designate the same scalar type.
3647204643Srdivacky  if (ScopeTypeInfo) {
3648204643Srdivacky    QualType ScopeType = ScopeTypeInfo->getType();
3649204643Srdivacky    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
3650210299Sed        !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
3651218893Sdim
3652208600Srdivacky      Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
3653204643Srdivacky           diag::err_pseudo_dtor_type_mismatch)
3654212904Sdim        << ObjectType << ScopeType << Base->getSourceRange()
3655208600Srdivacky        << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
3656218893Sdim
3657204643Srdivacky      ScopeType = QualType();
3658204643Srdivacky      ScopeTypeInfo = 0;
3659204643Srdivacky    }
3660204643Srdivacky  }
3661218893Sdim
3662212904Sdim  Expr *Result
3663212904Sdim    = new (Context) CXXPseudoDestructorExpr(Context, Base,
3664212904Sdim                                            OpKind == tok::arrow, OpLoc,
3665212904Sdim                                            SS.getScopeRep(), SS.getRange(),
3666212904Sdim                                            ScopeTypeInfo,
3667212904Sdim                                            CCLoc,
3668212904Sdim                                            TildeLoc,
3669212904Sdim                                            Destructed);
3670218893Sdim
3671204643Srdivacky  if (HasTrailingLParen)
3672212904Sdim    return Owned(Result);
3673218893Sdim
3674212904Sdim  return DiagnoseDtorReference(Destructed.getLocation(), Result);
3675204643Srdivacky}
3676204643Srdivacky
3677212904SdimExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
3678204643Srdivacky                                                       SourceLocation OpLoc,
3679204643Srdivacky                                                       tok::TokenKind OpKind,
3680207619Srdivacky                                                       CXXScopeSpec &SS,
3681204643Srdivacky                                                  UnqualifiedId &FirstTypeName,
3682204643Srdivacky                                                       SourceLocation CCLoc,
3683204643Srdivacky                                                       SourceLocation TildeLoc,
3684204643Srdivacky                                                 UnqualifiedId &SecondTypeName,
3685204643Srdivacky                                                       bool HasTrailingLParen) {
3686204643Srdivacky  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3687204643Srdivacky          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3688204643Srdivacky         "Invalid first type name in pseudo-destructor");
3689204643Srdivacky  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3690204643Srdivacky          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
3691204643Srdivacky         "Invalid second type name in pseudo-destructor");
3692204643Srdivacky
3693204643Srdivacky  // C++ [expr.pseudo]p2:
3694218893Sdim  //   The left-hand side of the dot operator shall be of scalar type. The
3695204643Srdivacky  //   left-hand side of the arrow operator shall be of pointer to scalar type.
3696218893Sdim  //   This scalar type is the object type.
3697212904Sdim  QualType ObjectType = Base->getType();
3698204643Srdivacky  if (OpKind == tok::arrow) {
3699204643Srdivacky    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3700204643Srdivacky      ObjectType = Ptr->getPointeeType();
3701204643Srdivacky    } else if (!ObjectType->isDependentType()) {
3702204643Srdivacky      // The user wrote "p->" when she probably meant "p."; fix it.
3703204643Srdivacky      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3704204643Srdivacky        << ObjectType << true
3705206084Srdivacky        << FixItHint::CreateReplacement(OpLoc, ".");
3706204643Srdivacky      if (isSFINAEContext())
3707204643Srdivacky        return ExprError();
3708218893Sdim
3709204643Srdivacky      OpKind = tok::period;
3710204643Srdivacky    }
3711204643Srdivacky  }
3712204643Srdivacky
3713204643Srdivacky  // Compute the object type that we should use for name lookup purposes. Only
3714204643Srdivacky  // record types and dependent types matter.
3715212904Sdim  ParsedType ObjectTypePtrForLookup;
3716204643Srdivacky  if (!SS.isSet()) {
3717212904Sdim    if (const Type *T = ObjectType->getAs<RecordType>())
3718212904Sdim      ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0));
3719212904Sdim    else if (ObjectType->isDependentType())
3720212904Sdim      ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
3721204643Srdivacky  }
3722218893Sdim
3723218893Sdim  // Convert the name of the type being destructed (following the ~) into a
3724204643Srdivacky  // type (with source-location information).
3725204643Srdivacky  QualType DestructedType;
3726204643Srdivacky  TypeSourceInfo *DestructedTypeInfo = 0;
3727204643Srdivacky  PseudoDestructorTypeStorage Destructed;
3728204643Srdivacky  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
3729218893Sdim    ParsedType T = getTypeName(*SecondTypeName.Identifier,
3730212904Sdim                               SecondTypeName.StartLocation,
3731218893Sdim                               S, &SS, true, false, ObjectTypePtrForLookup);
3732218893Sdim    if (!T &&
3733204643Srdivacky        ((SS.isSet() && !computeDeclContext(SS, false)) ||
3734204643Srdivacky         (!SS.isSet() && ObjectType->isDependentType()))) {
3735218893Sdim      // The name of the type being destroyed is a dependent name, and we
3736204643Srdivacky      // couldn't find anything useful in scope. Just store the identifier and
3737204643Srdivacky      // it's location, and we'll perform (qualified) name lookup again at
3738204643Srdivacky      // template instantiation time.
3739204643Srdivacky      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
3740204643Srdivacky                                               SecondTypeName.StartLocation);
3741204643Srdivacky    } else if (!T) {
3742218893Sdim      Diag(SecondTypeName.StartLocation,
3743204643Srdivacky           diag::err_pseudo_dtor_destructor_non_type)
3744204643Srdivacky        << SecondTypeName.Identifier << ObjectType;
3745204643Srdivacky      if (isSFINAEContext())
3746204643Srdivacky        return ExprError();
3747218893Sdim
3748204643Srdivacky      // Recover by assuming we had the right type all along.
3749204643Srdivacky      DestructedType = ObjectType;
3750204643Srdivacky    } else
3751204643Srdivacky      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
3752204643Srdivacky  } else {
3753204643Srdivacky    // Resolve the template-id to a type.
3754204643Srdivacky    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
3755204643Srdivacky    ASTTemplateArgsPtr TemplateArgsPtr(*this,
3756204643Srdivacky                                       TemplateId->getTemplateArgs(),
3757204643Srdivacky                                       TemplateId->NumArgs);
3758212904Sdim    TypeResult T = ActOnTemplateIdType(TemplateId->Template,
3759204643Srdivacky                                       TemplateId->TemplateNameLoc,
3760204643Srdivacky                                       TemplateId->LAngleLoc,
3761204643Srdivacky                                       TemplateArgsPtr,
3762204643Srdivacky                                       TemplateId->RAngleLoc);
3763204643Srdivacky    if (T.isInvalid() || !T.get()) {
3764204643Srdivacky      // Recover by assuming we had the right type all along.
3765204643Srdivacky      DestructedType = ObjectType;
3766204643Srdivacky    } else
3767204643Srdivacky      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
3768204643Srdivacky  }
3769218893Sdim
3770218893Sdim  // If we've performed some kind of recovery, (re-)build the type source
3771204643Srdivacky  // information.
3772204643Srdivacky  if (!DestructedType.isNull()) {
3773204643Srdivacky    if (!DestructedTypeInfo)
3774204643Srdivacky      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
3775204643Srdivacky                                                  SecondTypeName.StartLocation);
3776204643Srdivacky    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
3777204643Srdivacky  }
3778218893Sdim
3779204643Srdivacky  // Convert the name of the scope type (the type prior to '::') into a type.
3780204643Srdivacky  TypeSourceInfo *ScopeTypeInfo = 0;
3781204643Srdivacky  QualType ScopeType;
3782218893Sdim  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
3783204643Srdivacky      FirstTypeName.Identifier) {
3784204643Srdivacky    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
3785218893Sdim      ParsedType T = getTypeName(*FirstTypeName.Identifier,
3786212904Sdim                                 FirstTypeName.StartLocation,
3787218893Sdim                                 S, &SS, false, false, ObjectTypePtrForLookup);
3788204643Srdivacky      if (!T) {
3789218893Sdim        Diag(FirstTypeName.StartLocation,
3790204643Srdivacky             diag::err_pseudo_dtor_destructor_non_type)
3791204643Srdivacky          << FirstTypeName.Identifier << ObjectType;
3792218893Sdim
3793204643Srdivacky        if (isSFINAEContext())
3794204643Srdivacky          return ExprError();
3795218893Sdim
3796204643Srdivacky        // Just drop this type. It's unnecessary anyway.
3797204643Srdivacky        ScopeType = QualType();
3798204643Srdivacky      } else
3799204643Srdivacky        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
3800204643Srdivacky    } else {
3801204643Srdivacky      // Resolve the template-id to a type.
3802204643Srdivacky      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
3803204643Srdivacky      ASTTemplateArgsPtr TemplateArgsPtr(*this,
3804204643Srdivacky                                         TemplateId->getTemplateArgs(),
3805204643Srdivacky                                         TemplateId->NumArgs);
3806212904Sdim      TypeResult T = ActOnTemplateIdType(TemplateId->Template,
3807204643Srdivacky                                         TemplateId->TemplateNameLoc,
3808204643Srdivacky                                         TemplateId->LAngleLoc,
3809204643Srdivacky                                         TemplateArgsPtr,
3810204643Srdivacky                                         TemplateId->RAngleLoc);
3811204643Srdivacky      if (T.isInvalid() || !T.get()) {
3812204643Srdivacky        // Recover by dropping this type.
3813204643Srdivacky        ScopeType = QualType();
3814204643Srdivacky      } else
3815218893Sdim        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
3816204643Srdivacky    }
3817204643Srdivacky  }
3818218893Sdim
3819204643Srdivacky  if (!ScopeType.isNull() && !ScopeTypeInfo)
3820204643Srdivacky    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
3821204643Srdivacky                                                  FirstTypeName.StartLocation);
3822204643Srdivacky
3823218893Sdim
3824212904Sdim  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
3825204643Srdivacky                                   ScopeTypeInfo, CCLoc, TildeLoc,
3826204643Srdivacky                                   Destructed, HasTrailingLParen);
3827204643Srdivacky}
3828204643Srdivacky
3829218893SdimExprResult Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
3830218893Sdim                                        CXXMethodDecl *Method) {
3831206084Srdivacky  if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
3832206084Srdivacky                                          FoundDecl, Method))
3833218893Sdim    return true;
3834200583Srdivacky
3835218893Sdim  MemberExpr *ME =
3836212904Sdim      new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
3837218893Sdim                               SourceLocation(), Method->getType(),
3838218893Sdim                               VK_RValue, OK_Ordinary);
3839218893Sdim  QualType ResultType = Method->getResultType();
3840218893Sdim  ExprValueKind VK = Expr::getValueKindForType(ResultType);
3841218893Sdim  ResultType = ResultType.getNonLValueExprType(Context);
3842218893Sdim
3843199990Srdivacky  MarkDeclarationReferenced(Exp->getLocStart(), Method);
3844199990Srdivacky  CXXMemberCallExpr *CE =
3845218893Sdim    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
3846199990Srdivacky                                    Exp->getLocEnd());
3847198092Srdivacky  return CE;
3848198092Srdivacky}
3849198092Srdivacky
3850218893SdimExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
3851218893Sdim                                      SourceLocation RParen) {
3852218893Sdim  return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
3853218893Sdim                                             Operand->CanThrow(Context),
3854218893Sdim                                             KeyLoc, RParen));
3855218893Sdim}
3856218893Sdim
3857218893SdimExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
3858218893Sdim                                   Expr *Operand, SourceLocation RParen) {
3859218893Sdim  return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
3860218893Sdim}
3861218893Sdim
3862218893Sdim/// Perform the conversions required for an expression used in a
3863218893Sdim/// context that ignores the result.
3864218893Sdimvoid Sema::IgnoredValueConversions(Expr *&E) {
3865218893Sdim  // C99 6.3.2.1:
3866218893Sdim  //   [Except in specific positions,] an lvalue that does not have
3867218893Sdim  //   array type is converted to the value stored in the
3868218893Sdim  //   designated object (and is no longer an lvalue).
3869218893Sdim  if (E->isRValue()) return;
3870218893Sdim
3871218893Sdim  // We always want to do this on ObjC property references.
3872218893Sdim  if (E->getObjectKind() == OK_ObjCProperty) {
3873218893Sdim    ConvertPropertyForRValue(E);
3874218893Sdim    if (E->isRValue()) return;
3875218893Sdim  }
3876218893Sdim
3877218893Sdim  // Otherwise, this rule does not apply in C++, at least not for the moment.
3878218893Sdim  if (getLangOptions().CPlusPlus) return;
3879218893Sdim
3880218893Sdim  // GCC seems to also exclude expressions of incomplete enum type.
3881218893Sdim  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
3882218893Sdim    if (!T->getDecl()->isComplete()) {
3883218893Sdim      // FIXME: stupid workaround for a codegen bug!
3884218893Sdim      ImpCastExprToType(E, Context.VoidTy, CK_ToVoid);
3885218893Sdim      return;
3886218893Sdim    }
3887218893Sdim  }
3888218893Sdim
3889218893Sdim  DefaultFunctionArrayLvalueConversion(E);
3890218893Sdim  if (!E->getType()->isVoidType())
3891218893Sdim    RequireCompleteType(E->getExprLoc(), E->getType(),
3892218893Sdim                        diag::err_incomplete_type);
3893218893Sdim}
3894218893Sdim
3895212904SdimExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) {
3896218893Sdim  if (!FullExpr)
3897218893Sdim    return ExprError();
3898218893Sdim
3899218893Sdim  if (DiagnoseUnexpandedParameterPack(FullExpr))
3900218893Sdim    return ExprError();
3901218893Sdim
3902218893Sdim  IgnoredValueConversions(FullExpr);
3903218893Sdim  CheckImplicitConversions(FullExpr);
3904218893Sdim  return MaybeCreateExprWithCleanups(FullExpr);
3905193326Sed}
3906218893Sdim
3907218893SdimStmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
3908218893Sdim  if (!FullStmt) return StmtError();
3909218893Sdim
3910218893Sdim  return MaybeCreateStmtWithCleanups(FullStmt);
3911218893Sdim}
3912