SemaExprCXX.cpp revision 221345
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"
31221345Sdim#include "llvm/Support/ErrorHandling.h"
32193326Sedusing namespace clang;
33212904Sdimusing namespace sema;
34193326Sed
35212904SdimParsedType Sema::getDestructorName(SourceLocation TildeLoc,
36218893Sdim                                   IdentifierInfo &II,
37212904Sdim                                   SourceLocation NameLoc,
38212904Sdim                                   Scope *S, CXXScopeSpec &SS,
39212904Sdim                                   ParsedType ObjectTypePtr,
40212904Sdim                                   bool EnteringContext) {
41204643Srdivacky  // Determine where to perform name lookup.
42204643Srdivacky
43204643Srdivacky  // FIXME: This area of the standard is very messy, and the current
44204643Srdivacky  // wording is rather unclear about which scopes we search for the
45204643Srdivacky  // destructor name; see core issues 399 and 555. Issue 399 in
46204643Srdivacky  // particular shows where the current description of destructor name
47204643Srdivacky  // lookup is completely out of line with existing practice, e.g.,
48204643Srdivacky  // this appears to be ill-formed:
49204643Srdivacky  //
50204643Srdivacky  //   namespace N {
51204643Srdivacky  //     template <typename T> struct S {
52204643Srdivacky  //       ~S();
53204643Srdivacky  //     };
54204643Srdivacky  //   }
55204643Srdivacky  //
56204643Srdivacky  //   void f(N::S<int>* s) {
57204643Srdivacky  //     s->N::S<int>::~S();
58204643Srdivacky  //   }
59204643Srdivacky  //
60204643Srdivacky  // See also PR6358 and PR6359.
61210299Sed  // For this reason, we're currently only doing the C++03 version of this
62210299Sed  // code; the C++0x version has to wait until we get a proper spec.
63204643Srdivacky  QualType SearchType;
64204643Srdivacky  DeclContext *LookupCtx = 0;
65204643Srdivacky  bool isDependent = false;
66204643Srdivacky  bool LookInScope = false;
67204643Srdivacky
68204643Srdivacky  // If we have an object type, it's because we are in a
69204643Srdivacky  // pseudo-destructor-expression or a member access expression, and
70204643Srdivacky  // we know what type we're looking for.
71204643Srdivacky  if (ObjectTypePtr)
72204643Srdivacky    SearchType = GetTypeFromParser(ObjectTypePtr);
73204643Srdivacky
74204643Srdivacky  if (SS.isSet()) {
75204643Srdivacky    NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
76218893Sdim
77204643Srdivacky    bool AlreadySearched = false;
78204643Srdivacky    bool LookAtPrefix = true;
79210299Sed    // C++ [basic.lookup.qual]p6:
80218893Sdim    //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
81210299Sed    //   the type-names are looked up as types in the scope designated by the
82210299Sed    //   nested-name-specifier. In a qualified-id of the form:
83210299Sed    //
84218893Sdim    //     ::[opt] nested-name-specifier  ~ class-name
85218893Sdim    //
86210299Sed    //   where the nested-name-specifier designates a namespace scope, and in
87204643Srdivacky    //   a qualified-id of the form:
88204643Srdivacky    //
89218893Sdim    //     ::opt nested-name-specifier class-name ::  ~ class-name
90204643Srdivacky    //
91218893Sdim    //   the class-names are looked up as types in the scope designated by
92210299Sed    //   the nested-name-specifier.
93204643Srdivacky    //
94210299Sed    // Here, we check the first case (completely) and determine whether the
95218893Sdim    // code below is permitted to look at the prefix of the
96210299Sed    // nested-name-specifier.
97210299Sed    DeclContext *DC = computeDeclContext(SS, EnteringContext);
98210299Sed    if (DC && DC->isFileContext()) {
99210299Sed      AlreadySearched = true;
100210299Sed      LookupCtx = DC;
101210299Sed      isDependent = false;
102210299Sed    } else if (DC && isa<CXXRecordDecl>(DC))
103210299Sed      LookAtPrefix = false;
104218893Sdim
105210299Sed    // The second case from the C++03 rules quoted further above.
106204643Srdivacky    NestedNameSpecifier *Prefix = 0;
107204643Srdivacky    if (AlreadySearched) {
108204643Srdivacky      // Nothing left to do.
109204643Srdivacky    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
110204643Srdivacky      CXXScopeSpec PrefixSS;
111219077Sdim      PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
112204643Srdivacky      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
113204643Srdivacky      isDependent = isDependentScopeSpecifier(PrefixSS);
114204643Srdivacky    } else if (ObjectTypePtr) {
115204643Srdivacky      LookupCtx = computeDeclContext(SearchType);
116204643Srdivacky      isDependent = SearchType->isDependentType();
117204643Srdivacky    } else {
118204643Srdivacky      LookupCtx = computeDeclContext(SS, EnteringContext);
119204643Srdivacky      isDependent = LookupCtx && LookupCtx->isDependentContext();
120204643Srdivacky    }
121218893Sdim
122204643Srdivacky    LookInScope = false;
123204643Srdivacky  } else if (ObjectTypePtr) {
124204643Srdivacky    // C++ [basic.lookup.classref]p3:
125204643Srdivacky    //   If the unqualified-id is ~type-name, the type-name is looked up
126204643Srdivacky    //   in the context of the entire postfix-expression. If the type T
127204643Srdivacky    //   of the object expression is of a class type C, the type-name is
128204643Srdivacky    //   also looked up in the scope of class C. At least one of the
129204643Srdivacky    //   lookups shall find a name that refers to (possibly
130204643Srdivacky    //   cv-qualified) T.
131204643Srdivacky    LookupCtx = computeDeclContext(SearchType);
132204643Srdivacky    isDependent = SearchType->isDependentType();
133218893Sdim    assert((isDependent || !SearchType->isIncompleteType()) &&
134204643Srdivacky           "Caller should have completed object type");
135204643Srdivacky
136204643Srdivacky    LookInScope = true;
137204643Srdivacky  } else {
138204643Srdivacky    // Perform lookup into the current scope (only).
139204643Srdivacky    LookInScope = true;
140204643Srdivacky  }
141204643Srdivacky
142221345Sdim  TypeDecl *NonMatchingTypeDecl = 0;
143204643Srdivacky  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
144204643Srdivacky  for (unsigned Step = 0; Step != 2; ++Step) {
145204643Srdivacky    // Look for the name first in the computed lookup context (if we
146221345Sdim    // have one) and, if that fails to find a match, in the scope (if
147204643Srdivacky    // we're allowed to look there).
148204643Srdivacky    Found.clear();
149204643Srdivacky    if (Step == 0 && LookupCtx)
150204643Srdivacky      LookupQualifiedName(Found, LookupCtx);
151204643Srdivacky    else if (Step == 1 && LookInScope && S)
152204643Srdivacky      LookupName(Found, S);
153204643Srdivacky    else
154204643Srdivacky      continue;
155204643Srdivacky
156204643Srdivacky    // FIXME: Should we be suppressing ambiguities here?
157204643Srdivacky    if (Found.isAmbiguous())
158212904Sdim      return ParsedType();
159204643Srdivacky
160204643Srdivacky    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
161204643Srdivacky      QualType T = Context.getTypeDeclType(Type);
162204643Srdivacky
163204643Srdivacky      if (SearchType.isNull() || SearchType->isDependentType() ||
164204643Srdivacky          Context.hasSameUnqualifiedType(T, SearchType)) {
165204643Srdivacky        // We found our type!
166204643Srdivacky
167212904Sdim        return ParsedType::make(T);
168204643Srdivacky      }
169221345Sdim
170221345Sdim      if (!SearchType.isNull())
171221345Sdim        NonMatchingTypeDecl = Type;
172204643Srdivacky    }
173204643Srdivacky
174204643Srdivacky    // If the name that we found is a class template name, and it is
175204643Srdivacky    // the same name as the template name in the last part of the
176204643Srdivacky    // nested-name-specifier (if present) or the object type, then
177204643Srdivacky    // this is the destructor for that class.
178204643Srdivacky    // FIXME: This is a workaround until we get real drafting for core
179218893Sdim    // issue 399, for which there isn't even an obvious direction.
180204643Srdivacky    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
181204643Srdivacky      QualType MemberOfType;
182204643Srdivacky      if (SS.isSet()) {
183204643Srdivacky        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
184204643Srdivacky          // Figure out the type of the context, if it has one.
185204962Srdivacky          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
186204962Srdivacky            MemberOfType = Context.getTypeDeclType(Record);
187204643Srdivacky        }
188204643Srdivacky      }
189204643Srdivacky      if (MemberOfType.isNull())
190204643Srdivacky        MemberOfType = SearchType;
191218893Sdim
192204643Srdivacky      if (MemberOfType.isNull())
193204643Srdivacky        continue;
194204643Srdivacky
195204643Srdivacky      // We're referring into a class template specialization. If the
196204643Srdivacky      // class template we found is the same as the template being
197204643Srdivacky      // specialized, we found what we are looking for.
198204643Srdivacky      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
199204643Srdivacky        if (ClassTemplateSpecializationDecl *Spec
200204643Srdivacky              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
201204643Srdivacky          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
202204643Srdivacky                Template->getCanonicalDecl())
203212904Sdim            return ParsedType::make(MemberOfType);
204204643Srdivacky        }
205204643Srdivacky
206204643Srdivacky        continue;
207204643Srdivacky      }
208218893Sdim
209204643Srdivacky      // We're referring to an unresolved class template
210204643Srdivacky      // specialization. Determine whether we class template we found
211204643Srdivacky      // is the same as the template being specialized or, if we don't
212204643Srdivacky      // know which template is being specialized, that it at least
213204643Srdivacky      // has the same name.
214204643Srdivacky      if (const TemplateSpecializationType *SpecType
215204643Srdivacky            = MemberOfType->getAs<TemplateSpecializationType>()) {
216204643Srdivacky        TemplateName SpecName = SpecType->getTemplateName();
217204643Srdivacky
218204643Srdivacky        // The class template we found is the same template being
219204643Srdivacky        // specialized.
220204643Srdivacky        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
221204643Srdivacky          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
222212904Sdim            return ParsedType::make(MemberOfType);
223204643Srdivacky
224204643Srdivacky          continue;
225204643Srdivacky        }
226204643Srdivacky
227204643Srdivacky        // The class template we found has the same name as the
228204643Srdivacky        // (dependent) template name being specialized.
229218893Sdim        if (DependentTemplateName *DepTemplate
230204643Srdivacky                                    = SpecName.getAsDependentTemplateName()) {
231204643Srdivacky          if (DepTemplate->isIdentifier() &&
232204643Srdivacky              DepTemplate->getIdentifier() == Template->getIdentifier())
233212904Sdim            return ParsedType::make(MemberOfType);
234204643Srdivacky
235204643Srdivacky          continue;
236204643Srdivacky        }
237204643Srdivacky      }
238204643Srdivacky    }
239204643Srdivacky  }
240204643Srdivacky
241204643Srdivacky  if (isDependent) {
242204643Srdivacky    // We didn't find our type, but that's okay: it's dependent
243204643Srdivacky    // anyway.
244221345Sdim
245221345Sdim    // FIXME: What if we have no nested-name-specifier?
246221345Sdim    QualType T = CheckTypenameType(ETK_None, SourceLocation(),
247221345Sdim                                   SS.getWithLocInContext(Context),
248221345Sdim                                   II, NameLoc);
249212904Sdim    return ParsedType::make(T);
250204643Srdivacky  }
251204643Srdivacky
252221345Sdim  if (NonMatchingTypeDecl) {
253221345Sdim    QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
254221345Sdim    Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
255221345Sdim      << T << SearchType;
256221345Sdim    Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
257221345Sdim      << T;
258221345Sdim  } else if (ObjectTypePtr)
259221345Sdim    Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
260218893Sdim      << &II;
261204643Srdivacky  else
262204643Srdivacky    Diag(NameLoc, diag::err_destructor_class_name);
263204643Srdivacky
264212904Sdim  return ParsedType();
265204643Srdivacky}
266204643Srdivacky
267207619Srdivacky/// \brief Build a C++ typeid expression with a type operand.
268212904SdimExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
269218893Sdim                                SourceLocation TypeidLoc,
270218893Sdim                                TypeSourceInfo *Operand,
271218893Sdim                                SourceLocation RParenLoc) {
272207619Srdivacky  // C++ [expr.typeid]p4:
273218893Sdim  //   The top-level cv-qualifiers of the lvalue expression or the type-id
274207619Srdivacky  //   that is the operand of typeid are always ignored.
275218893Sdim  //   If the type of the type-id is a class type or a reference to a class
276207619Srdivacky  //   type, the class shall be completely-defined.
277210299Sed  Qualifiers Quals;
278210299Sed  QualType T
279210299Sed    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
280210299Sed                                      Quals);
281207619Srdivacky  if (T->getAs<RecordType>() &&
282207619Srdivacky      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
283207619Srdivacky    return ExprError();
284218893Sdim
285207619Srdivacky  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
286207619Srdivacky                                           Operand,
287207619Srdivacky                                           SourceRange(TypeidLoc, RParenLoc)));
288207619Srdivacky}
289207619Srdivacky
290207619Srdivacky/// \brief Build a C++ typeid expression with an expression operand.
291212904SdimExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
292218893Sdim                                SourceLocation TypeidLoc,
293218893Sdim                                Expr *E,
294218893Sdim                                SourceLocation RParenLoc) {
295207619Srdivacky  bool isUnevaluatedOperand = true;
296207619Srdivacky  if (E && !E->isTypeDependent()) {
297207619Srdivacky    QualType T = E->getType();
298207619Srdivacky    if (const RecordType *RecordT = T->getAs<RecordType>()) {
299207619Srdivacky      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
300207619Srdivacky      // C++ [expr.typeid]p3:
301207619Srdivacky      //   [...] If the type of the expression is a class type, the class
302207619Srdivacky      //   shall be completely-defined.
303207619Srdivacky      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
304207619Srdivacky        return ExprError();
305218893Sdim
306207619Srdivacky      // C++ [expr.typeid]p3:
307212904Sdim      //   When typeid is applied to an expression other than an glvalue of a
308207619Srdivacky      //   polymorphic class type [...] [the] expression is an unevaluated
309207619Srdivacky      //   operand. [...]
310212904Sdim      if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
311207619Srdivacky        isUnevaluatedOperand = false;
312208600Srdivacky
313208600Srdivacky        // We require a vtable to query the type at run time.
314208600Srdivacky        MarkVTableUsed(TypeidLoc, RecordD);
315208600Srdivacky      }
316207619Srdivacky    }
317218893Sdim
318207619Srdivacky    // C++ [expr.typeid]p4:
319207619Srdivacky    //   [...] If the type of the type-id is a reference to a possibly
320218893Sdim    //   cv-qualified type, the result of the typeid expression refers to a
321218893Sdim    //   std::type_info object representing the cv-unqualified referenced
322207619Srdivacky    //   type.
323210299Sed    Qualifiers Quals;
324210299Sed    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
325210299Sed    if (!Context.hasSameType(T, UnqualT)) {
326210299Sed      T = UnqualT;
327221345Sdim      E = ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)).take();
328207619Srdivacky    }
329207619Srdivacky  }
330218893Sdim
331207619Srdivacky  // If this is an unevaluated operand, clear out the set of
332207619Srdivacky  // declaration references we have been computing and eliminate any
333207619Srdivacky  // temporaries introduced in its computation.
334207619Srdivacky  if (isUnevaluatedOperand)
335207619Srdivacky    ExprEvalContexts.back().Context = Unevaluated;
336218893Sdim
337207619Srdivacky  return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
338212904Sdim                                           E,
339218893Sdim                                           SourceRange(TypeidLoc, RParenLoc)));
340207619Srdivacky}
341207619Srdivacky
342207619Srdivacky/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
343212904SdimExprResult
344193326SedSema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
345193326Sed                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
346207619Srdivacky  // Find the std::type_info type.
347221345Sdim  if (!getStdNamespace())
348193326Sed    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
349198092Srdivacky
350218893Sdim  if (!CXXTypeInfoDecl) {
351218893Sdim    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
352218893Sdim    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
353218893Sdim    LookupQualifiedName(R, getStdNamespace());
354218893Sdim    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
355218893Sdim    if (!CXXTypeInfoDecl)
356218893Sdim      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
357218893Sdim  }
358218893Sdim
359218893Sdim  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
360218893Sdim
361207619Srdivacky  if (isType) {
362207619Srdivacky    // The operand is a type; handle it as such.
363207619Srdivacky    TypeSourceInfo *TInfo = 0;
364212904Sdim    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
365212904Sdim                                   &TInfo);
366207619Srdivacky    if (T.isNull())
367207619Srdivacky      return ExprError();
368218893Sdim
369207619Srdivacky    if (!TInfo)
370207619Srdivacky      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
371193326Sed
372207619Srdivacky    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
373194711Sed  }
374198092Srdivacky
375218893Sdim  // The operand is an expression.
376212904Sdim  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
377193326Sed}
378193326Sed
379218893Sdim/// Retrieve the UuidAttr associated with QT.
380218893Sdimstatic UuidAttr *GetUuidAttrOfType(QualType QT) {
381218893Sdim  // Optionally remove one level of pointer, reference or array indirection.
382218893Sdim  const Type *Ty = QT.getTypePtr();;
383218893Sdim  if (QT->isPointerType() || QT->isReferenceType())
384218893Sdim    Ty = QT->getPointeeType().getTypePtr();
385218893Sdim  else if (QT->isArrayType())
386218893Sdim    Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
387218893Sdim
388218893Sdim  // Loop all class definition and declaration looking for an uuid attribute.
389218893Sdim  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
390218893Sdim  while (RD) {
391218893Sdim    if (UuidAttr *Uuid = RD->getAttr<UuidAttr>())
392218893Sdim      return Uuid;
393218893Sdim    RD = RD->getPreviousDeclaration();
394218893Sdim  }
395218893Sdim  return 0;
396218893Sdim}
397218893Sdim
398218893Sdim/// \brief Build a Microsoft __uuidof expression with a type operand.
399218893SdimExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
400218893Sdim                                SourceLocation TypeidLoc,
401218893Sdim                                TypeSourceInfo *Operand,
402218893Sdim                                SourceLocation RParenLoc) {
403218893Sdim  if (!Operand->getType()->isDependentType()) {
404218893Sdim    if (!GetUuidAttrOfType(Operand->getType()))
405218893Sdim      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
406218893Sdim  }
407218893Sdim
408218893Sdim  // FIXME: add __uuidof semantic analysis for type operand.
409218893Sdim  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
410218893Sdim                                           Operand,
411218893Sdim                                           SourceRange(TypeidLoc, RParenLoc)));
412218893Sdim}
413218893Sdim
414218893Sdim/// \brief Build a Microsoft __uuidof expression with an expression operand.
415218893SdimExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
416218893Sdim                                SourceLocation TypeidLoc,
417218893Sdim                                Expr *E,
418218893Sdim                                SourceLocation RParenLoc) {
419218893Sdim  if (!E->getType()->isDependentType()) {
420218893Sdim    if (!GetUuidAttrOfType(E->getType()) &&
421218893Sdim        !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
422218893Sdim      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
423218893Sdim  }
424218893Sdim  // FIXME: add __uuidof semantic analysis for type operand.
425218893Sdim  return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
426218893Sdim                                           E,
427218893Sdim                                           SourceRange(TypeidLoc, RParenLoc)));
428218893Sdim}
429218893Sdim
430218893Sdim/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
431218893SdimExprResult
432218893SdimSema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
433218893Sdim                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
434218893Sdim  // If MSVCGuidDecl has not been cached, do the lookup.
435218893Sdim  if (!MSVCGuidDecl) {
436218893Sdim    IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
437218893Sdim    LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
438218893Sdim    LookupQualifiedName(R, Context.getTranslationUnitDecl());
439218893Sdim    MSVCGuidDecl = R.getAsSingle<RecordDecl>();
440218893Sdim    if (!MSVCGuidDecl)
441218893Sdim      return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
442218893Sdim  }
443218893Sdim
444218893Sdim  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
445218893Sdim
446218893Sdim  if (isType) {
447218893Sdim    // The operand is a type; handle it as such.
448218893Sdim    TypeSourceInfo *TInfo = 0;
449218893Sdim    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
450218893Sdim                                   &TInfo);
451218893Sdim    if (T.isNull())
452218893Sdim      return ExprError();
453218893Sdim
454218893Sdim    if (!TInfo)
455218893Sdim      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
456218893Sdim
457218893Sdim    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
458218893Sdim  }
459218893Sdim
460218893Sdim  // The operand is an expression.
461218893Sdim  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
462218893Sdim}
463218893Sdim
464193326Sed/// ActOnCXXBoolLiteral - Parse {true,false} literals.
465212904SdimExprResult
466193326SedSema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
467193326Sed  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
468193326Sed         "Unknown C++ Boolean value!");
469193326Sed  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
470193326Sed                                                Context.BoolTy, OpLoc));
471193326Sed}
472193326Sed
473193326Sed/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
474212904SdimExprResult
475193326SedSema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
476193326Sed  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
477193326Sed}
478193326Sed
479193326Sed/// ActOnCXXThrow - Parse throw expressions.
480212904SdimExprResult
481212904SdimSema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) {
482219077Sdim  // Don't report an error if 'throw' is used in system headers.
483221345Sdim  if (!getLangOptions().CXXExceptions &&
484219077Sdim      !getSourceManager().isInSystemHeader(OpLoc))
485218893Sdim    Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
486218893Sdim
487221345Sdim  if (Ex && !Ex->isTypeDependent()) {
488221345Sdim    ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex);
489221345Sdim    if (ExRes.isInvalid())
490221345Sdim      return ExprError();
491221345Sdim    Ex = ExRes.take();
492221345Sdim  }
493193326Sed  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
494193326Sed}
495193326Sed
496193326Sed/// CheckCXXThrowOperand - Validate the operand of a throw.
497221345SdimExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E) {
498193326Sed  // C++ [except.throw]p3:
499201361Srdivacky  //   A throw-expression initializes a temporary object, called the exception
500201361Srdivacky  //   object, the type of which is determined by removing any top-level
501201361Srdivacky  //   cv-qualifiers from the static type of the operand of throw and adjusting
502218893Sdim  //   the type from "array of T" or "function returning T" to "pointer to T"
503201361Srdivacky  //   or "pointer to function returning T", [...]
504201361Srdivacky  if (E->getType().hasQualifiers())
505221345Sdim    E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
506221345Sdim                      CastCategory(E)).take();
507218893Sdim
508221345Sdim  ExprResult Res = DefaultFunctionArrayConversion(E);
509221345Sdim  if (Res.isInvalid())
510221345Sdim    return ExprError();
511221345Sdim  E = Res.take();
512193326Sed
513193326Sed  //   If the type of the exception would be an incomplete type or a pointer
514193326Sed  //   to an incomplete type other than (cv) void the program is ill-formed.
515193326Sed  QualType Ty = E->getType();
516207619Srdivacky  bool isPointer = false;
517198092Srdivacky  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
518193326Sed    Ty = Ptr->getPointeeType();
519207619Srdivacky    isPointer = true;
520193326Sed  }
521193326Sed  if (!isPointer || !Ty->isVoidType()) {
522193326Sed    if (RequireCompleteType(ThrowLoc, Ty,
523198092Srdivacky                            PDiag(isPointer ? diag::err_throw_incomplete_ptr
524198092Srdivacky                                            : diag::err_throw_incomplete)
525198092Srdivacky                              << E->getSourceRange()))
526221345Sdim      return ExprError();
527204643Srdivacky
528207619Srdivacky    if (RequireNonAbstractType(ThrowLoc, E->getType(),
529207619Srdivacky                               PDiag(diag::err_throw_abstract_type)
530207619Srdivacky                                 << E->getSourceRange()))
531221345Sdim      return ExprError();
532193326Sed  }
533193326Sed
534207619Srdivacky  // Initialize the exception result.  This implicitly weeds out
535207619Srdivacky  // abstract types or types with inaccessible copy constructors.
536218893Sdim  const VarDecl *NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
537218893Sdim
538218893Sdim  // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p32.
539207619Srdivacky  InitializedEntity Entity =
540218893Sdim      InitializedEntity::InitializeException(ThrowLoc, E->getType(),
541218893Sdim                                             /*NRVO=*/false);
542221345Sdim  Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
543221345Sdim                                        QualType(), E);
544207619Srdivacky  if (Res.isInvalid())
545221345Sdim    return ExprError();
546221345Sdim  E = Res.take();
547208600Srdivacky
548210299Sed  // If the exception has class type, we need additional handling.
549210299Sed  const RecordType *RecordTy = Ty->getAs<RecordType>();
550210299Sed  if (!RecordTy)
551221345Sdim    return Owned(E);
552210299Sed  CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
553210299Sed
554208600Srdivacky  // If we are throwing a polymorphic class type or pointer thereof,
555208600Srdivacky  // exception handling will make use of the vtable.
556210299Sed  MarkVTableUsed(ThrowLoc, RD);
557210299Sed
558218893Sdim  // If a pointer is thrown, the referenced object will not be destroyed.
559218893Sdim  if (isPointer)
560221345Sdim    return Owned(E);
561218893Sdim
562210299Sed  // If the class has a non-trivial destructor, we must be able to call it.
563210299Sed  if (RD->hasTrivialDestructor())
564221345Sdim    return Owned(E);
565210299Sed
566218893Sdim  CXXDestructorDecl *Destructor
567210299Sed    = const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
568210299Sed  if (!Destructor)
569221345Sdim    return Owned(E);
570210299Sed
571210299Sed  MarkDeclarationReferenced(E->getExprLoc(), Destructor);
572210299Sed  CheckDestructorAccess(E->getExprLoc(), Destructor,
573210299Sed                        PDiag(diag::err_access_dtor_exception) << Ty);
574221345Sdim  return Owned(E);
575193326Sed}
576193326Sed
577218893SdimCXXMethodDecl *Sema::tryCaptureCXXThis() {
578218893Sdim  // Ignore block scopes: we can capture through them.
579218893Sdim  // Ignore nested enum scopes: we'll diagnose non-constant expressions
580218893Sdim  // where they're invalid, and other uses are legitimate.
581218893Sdim  // Don't ignore nested class scopes: you can't use 'this' in a local class.
582218893Sdim  DeclContext *DC = CurContext;
583218893Sdim  while (true) {
584218893Sdim    if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
585218893Sdim    else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
586218893Sdim    else break;
587218893Sdim  }
588218893Sdim
589218893Sdim  // If we're not in an instance method, error out.
590218893Sdim  CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC);
591218893Sdim  if (!method || !method->isInstance())
592218893Sdim    return 0;
593218893Sdim
594218893Sdim  // Mark that we're closing on 'this' in all the block scopes, if applicable.
595218893Sdim  for (unsigned idx = FunctionScopes.size() - 1;
596218893Sdim       isa<BlockScopeInfo>(FunctionScopes[idx]);
597218893Sdim       --idx)
598218893Sdim    cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis = true;
599218893Sdim
600218893Sdim  return method;
601218893Sdim}
602218893Sdim
603218893SdimExprResult Sema::ActOnCXXThis(SourceLocation loc) {
604193326Sed  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
605193326Sed  /// is a non-lvalue expression whose value is the address of the object for
606193326Sed  /// which the function is called.
607193326Sed
608218893Sdim  CXXMethodDecl *method = tryCaptureCXXThis();
609218893Sdim  if (!method) return Diag(loc, diag::err_invalid_this_use);
610193326Sed
611218893Sdim  return Owned(new (Context) CXXThisExpr(loc, method->getThisType(Context),
612218893Sdim                                         /*isImplicit=*/false));
613193326Sed}
614193326Sed
615212904SdimExprResult
616218893SdimSema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
617193326Sed                                SourceLocation LParenLoc,
618193326Sed                                MultiExprArg exprs,
619193326Sed                                SourceLocation RParenLoc) {
620203955Srdivacky  if (!TypeRep)
621203955Srdivacky    return ExprError();
622203955Srdivacky
623202879Srdivacky  TypeSourceInfo *TInfo;
624202879Srdivacky  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
625202879Srdivacky  if (!TInfo)
626202879Srdivacky    TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
627218893Sdim
628218893Sdim  return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
629218893Sdim}
630218893Sdim
631218893Sdim/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
632218893Sdim/// Can be interpreted either as function-style casting ("int(x)")
633218893Sdim/// or class type construction ("ClassType(x,y,z)")
634218893Sdim/// or creation of a value-initialized type ("int()").
635218893SdimExprResult
636218893SdimSema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
637218893Sdim                                SourceLocation LParenLoc,
638218893Sdim                                MultiExprArg exprs,
639218893Sdim                                SourceLocation RParenLoc) {
640218893Sdim  QualType Ty = TInfo->getType();
641193326Sed  unsigned NumExprs = exprs.size();
642193326Sed  Expr **Exprs = (Expr**)exprs.get();
643218893Sdim  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
644193326Sed  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
645193326Sed
646193326Sed  if (Ty->isDependentType() ||
647193326Sed      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
648193326Sed    exprs.release();
649198092Srdivacky
650218893Sdim    return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
651193326Sed                                                    LParenLoc,
652193326Sed                                                    Exprs, NumExprs,
653193326Sed                                                    RParenLoc));
654193326Sed  }
655193326Sed
656198092Srdivacky  if (Ty->isArrayType())
657198092Srdivacky    return ExprError(Diag(TyBeginLoc,
658198092Srdivacky                          diag::err_value_init_for_array_type) << FullRange);
659198092Srdivacky  if (!Ty->isVoidType() &&
660198092Srdivacky      RequireCompleteType(TyBeginLoc, Ty,
661198092Srdivacky                          PDiag(diag::err_invalid_incomplete_type_use)
662198092Srdivacky                            << FullRange))
663198092Srdivacky    return ExprError();
664218893Sdim
665198092Srdivacky  if (RequireNonAbstractType(TyBeginLoc, Ty,
666198092Srdivacky                             diag::err_allocation_of_abstract_type))
667198092Srdivacky    return ExprError();
668198092Srdivacky
669198092Srdivacky
670193326Sed  // C++ [expr.type.conv]p1:
671193326Sed  // If the expression list is a single expression, the type conversion
672193326Sed  // expression is equivalent (in definedness, and if defined in meaning) to the
673193326Sed  // corresponding cast expression.
674193326Sed  //
675193326Sed  if (NumExprs == 1) {
676218893Sdim    CastKind Kind = CK_Invalid;
677218893Sdim    ExprValueKind VK = VK_RValue;
678212904Sdim    CXXCastPath BasePath;
679221345Sdim    ExprResult CastExpr =
680221345Sdim      CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0],
681221345Sdim                     Kind, VK, BasePath,
682221345Sdim                     /*FunctionalStyle=*/true);
683221345Sdim    if (CastExpr.isInvalid())
684193326Sed      return ExprError();
685221345Sdim    Exprs[0] = CastExpr.take();
686198092Srdivacky
687193326Sed    exprs.release();
688198092Srdivacky
689212904Sdim    return Owned(CXXFunctionalCastExpr::Create(Context,
690218893Sdim                                               Ty.getNonLValueExprType(Context),
691218893Sdim                                               VK, TInfo, TyBeginLoc, Kind,
692212904Sdim                                               Exprs[0], &BasePath,
693212904Sdim                                               RParenLoc));
694193326Sed  }
695193326Sed
696218893Sdim  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
697218893Sdim  InitializationKind Kind
698218893Sdim    = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
699218893Sdim                                                  LParenLoc, RParenLoc)
700218893Sdim               : InitializationKind::CreateValue(TyBeginLoc,
701218893Sdim                                                 LParenLoc, RParenLoc);
702218893Sdim  InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
703218893Sdim  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
704193326Sed
705218893Sdim  // FIXME: Improve AST representation?
706218893Sdim  return move(Result);
707218893Sdim}
708218893Sdim
709218893Sdim/// doesUsualArrayDeleteWantSize - Answers whether the usual
710218893Sdim/// operator delete[] for the given type has a size_t parameter.
711218893Sdimstatic bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
712218893Sdim                                         QualType allocType) {
713218893Sdim  const RecordType *record =
714218893Sdim    allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
715218893Sdim  if (!record) return false;
716218893Sdim
717218893Sdim  // Try to find an operator delete[] in class scope.
718218893Sdim
719218893Sdim  DeclarationName deleteName =
720218893Sdim    S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
721218893Sdim  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
722218893Sdim  S.LookupQualifiedName(ops, record->getDecl());
723218893Sdim
724218893Sdim  // We're just doing this for information.
725218893Sdim  ops.suppressDiagnostics();
726218893Sdim
727218893Sdim  // Very likely: there's no operator delete[].
728218893Sdim  if (ops.empty()) return false;
729218893Sdim
730218893Sdim  // If it's ambiguous, it should be illegal to call operator delete[]
731218893Sdim  // on this thing, so it doesn't matter if we allocate extra space or not.
732218893Sdim  if (ops.isAmbiguous()) return false;
733218893Sdim
734218893Sdim  LookupResult::Filter filter = ops.makeFilter();
735218893Sdim  while (filter.hasNext()) {
736218893Sdim    NamedDecl *del = filter.next()->getUnderlyingDecl();
737218893Sdim
738218893Sdim    // C++0x [basic.stc.dynamic.deallocation]p2:
739218893Sdim    //   A template instance is never a usual deallocation function,
740218893Sdim    //   regardless of its signature.
741218893Sdim    if (isa<FunctionTemplateDecl>(del)) {
742218893Sdim      filter.erase();
743218893Sdim      continue;
744218893Sdim    }
745218893Sdim
746218893Sdim    // C++0x [basic.stc.dynamic.deallocation]p2:
747218893Sdim    //   If class T does not declare [an operator delete[] with one
748218893Sdim    //   parameter] but does declare a member deallocation function
749218893Sdim    //   named operator delete[] with exactly two parameters, the
750218893Sdim    //   second of which has type std::size_t, then this function
751218893Sdim    //   is a usual deallocation function.
752218893Sdim    if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
753218893Sdim      filter.erase();
754218893Sdim      continue;
755218893Sdim    }
756193326Sed  }
757218893Sdim  filter.done();
758193326Sed
759218893Sdim  if (!ops.isSingleResult()) return false;
760193326Sed
761218893Sdim  const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
762218893Sdim  return (del->getNumParams() == 2);
763193326Sed}
764193326Sed
765193326Sed/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
766193326Sed/// @code new (memory) int[size][4] @endcode
767193326Sed/// or
768193326Sed/// @code ::new Foo(23, "hello") @endcode
769193326Sed/// For the interpretation of this heap of arguments, consult the base version.
770212904SdimExprResult
771193326SedSema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
772193326Sed                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
773218893Sdim                  SourceLocation PlacementRParen, SourceRange TypeIdParens,
774193326Sed                  Declarator &D, SourceLocation ConstructorLParen,
775193326Sed                  MultiExprArg ConstructorArgs,
776198092Srdivacky                  SourceLocation ConstructorRParen) {
777218893Sdim  bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
778218893Sdim
779193326Sed  Expr *ArraySize = 0;
780193326Sed  // If the specified type is an array, unwrap it and save the expression.
781193326Sed  if (D.getNumTypeObjects() > 0 &&
782193326Sed      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
783193326Sed    DeclaratorChunk &Chunk = D.getTypeObject(0);
784218893Sdim    if (TypeContainsAuto)
785218893Sdim      return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
786218893Sdim        << D.getSourceRange());
787193326Sed    if (Chunk.Arr.hasStatic)
788193326Sed      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
789193326Sed        << D.getSourceRange());
790193326Sed    if (!Chunk.Arr.NumElts)
791193326Sed      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
792193326Sed        << D.getSourceRange());
793198893Srdivacky
794193326Sed    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
795198893Srdivacky    D.DropFirstTypeObject();
796193326Sed  }
797193326Sed
798198092Srdivacky  // Every dimension shall be of constant size.
799198893Srdivacky  if (ArraySize) {
800198893Srdivacky    for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
801198092Srdivacky      if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
802198092Srdivacky        break;
803193326Sed
804198092Srdivacky      DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
805198092Srdivacky      if (Expr *NumElts = (Expr *)Array.NumElts) {
806198092Srdivacky        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
807198092Srdivacky            !NumElts->isIntegerConstantExpr(Context)) {
808198092Srdivacky          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
809198092Srdivacky            << NumElts->getSourceRange();
810198092Srdivacky          return ExprError();
811198092Srdivacky        }
812198092Srdivacky      }
813193326Sed    }
814193326Sed  }
815198893Srdivacky
816218893Sdim  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0, /*OwnedDecl=*/0,
817218893Sdim                                               /*AllowAuto=*/true);
818210299Sed  QualType AllocType = TInfo->getType();
819198092Srdivacky  if (D.isInvalidType())
820198092Srdivacky    return ExprError();
821218893Sdim
822198092Srdivacky  return BuildCXXNew(StartLoc, UseGlobal,
823193326Sed                     PlacementLParen,
824198092Srdivacky                     move(PlacementArgs),
825193326Sed                     PlacementRParen,
826210299Sed                     TypeIdParens,
827198092Srdivacky                     AllocType,
828218893Sdim                     TInfo,
829212904Sdim                     ArraySize,
830193326Sed                     ConstructorLParen,
831193326Sed                     move(ConstructorArgs),
832218893Sdim                     ConstructorRParen,
833218893Sdim                     TypeContainsAuto);
834193326Sed}
835193326Sed
836212904SdimExprResult
837193326SedSema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
838193326Sed                  SourceLocation PlacementLParen,
839193326Sed                  MultiExprArg PlacementArgs,
840193326Sed                  SourceLocation PlacementRParen,
841210299Sed                  SourceRange TypeIdParens,
842193326Sed                  QualType AllocType,
843218893Sdim                  TypeSourceInfo *AllocTypeInfo,
844212904Sdim                  Expr *ArraySize,
845193326Sed                  SourceLocation ConstructorLParen,
846193326Sed                  MultiExprArg ConstructorArgs,
847218893Sdim                  SourceLocation ConstructorRParen,
848218893Sdim                  bool TypeMayContainAuto) {
849218893Sdim  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
850193326Sed
851218893Sdim  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
852218893Sdim  if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
853218893Sdim    if (ConstructorArgs.size() == 0)
854218893Sdim      return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
855218893Sdim                       << AllocType << TypeRange);
856218893Sdim    if (ConstructorArgs.size() != 1) {
857218893Sdim      Expr *FirstBad = ConstructorArgs.get()[1];
858218893Sdim      return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
859218893Sdim                            diag::err_auto_new_ctor_multiple_expressions)
860218893Sdim                       << AllocType << TypeRange);
861218893Sdim    }
862221345Sdim    TypeSourceInfo *DeducedType = 0;
863221345Sdim    if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedType))
864218893Sdim      return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
865218893Sdim                       << AllocType
866218893Sdim                       << ConstructorArgs.get()[0]->getType()
867218893Sdim                       << TypeRange
868218893Sdim                       << ConstructorArgs.get()[0]->getSourceRange());
869221345Sdim    if (!DeducedType)
870221345Sdim      return ExprError();
871218893Sdim
872221345Sdim    AllocTypeInfo = DeducedType;
873221345Sdim    AllocType = AllocTypeInfo->getType();
874218893Sdim  }
875218893Sdim
876208600Srdivacky  // Per C++0x [expr.new]p5, the type being constructed may be a
877208600Srdivacky  // typedef of an array type.
878212904Sdim  if (!ArraySize) {
879208600Srdivacky    if (const ConstantArrayType *Array
880208600Srdivacky                              = Context.getAsConstantArrayType(AllocType)) {
881212904Sdim      ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
882212904Sdim                                         Context.getSizeType(),
883212904Sdim                                         TypeRange.getEnd());
884208600Srdivacky      AllocType = Array->getElementType();
885208600Srdivacky    }
886208600Srdivacky  }
887208600Srdivacky
888218893Sdim  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
889218893Sdim    return ExprError();
890218893Sdim
891193326Sed  QualType ResultType = Context.getPointerType(AllocType);
892193326Sed
893193326Sed  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
894193326Sed  //   or enumeration type with a non-negative value."
895193326Sed  if (ArraySize && !ArraySize->isTypeDependent()) {
896218893Sdim
897193326Sed    QualType SizeType = ArraySize->getType();
898218893Sdim
899212904Sdim    ExprResult ConvertedSize
900212904Sdim      = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
901210299Sed                                       PDiag(diag::err_array_size_not_integral),
902210299Sed                                     PDiag(diag::err_array_size_incomplete_type)
903210299Sed                                       << ArraySize->getSourceRange(),
904210299Sed                               PDiag(diag::err_array_size_explicit_conversion),
905210299Sed                                       PDiag(diag::note_array_size_conversion),
906210299Sed                               PDiag(diag::err_array_size_ambiguous_conversion),
907210299Sed                                       PDiag(diag::note_array_size_conversion),
908218893Sdim                          PDiag(getLangOptions().CPlusPlus0x? 0
909210299Sed                                            : diag::ext_array_size_conversion));
910210299Sed    if (ConvertedSize.isInvalid())
911210299Sed      return ExprError();
912218893Sdim
913212904Sdim    ArraySize = ConvertedSize.take();
914210299Sed    SizeType = ArraySize->getType();
915218893Sdim    if (!SizeType->isIntegralOrUnscopedEnumerationType())
916210299Sed      return ExprError();
917218893Sdim
918193326Sed    // Let's see if this is a constant < 0. If so, we reject it out of hand.
919193326Sed    // We don't care about special rules, so we tell the machinery it's not
920193326Sed    // evaluated - it gives us a result in more cases.
921193326Sed    if (!ArraySize->isValueDependent()) {
922193326Sed      llvm::APSInt Value;
923193326Sed      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
924193326Sed        if (Value < llvm::APSInt(
925218893Sdim                        llvm::APInt::getNullValue(Value.getBitWidth()),
926198092Srdivacky                                 Value.isUnsigned()))
927193326Sed          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
928212904Sdim                                diag::err_typecheck_negative_array_size)
929193326Sed            << ArraySize->getSourceRange());
930218893Sdim
931212904Sdim        if (!AllocType->isDependentType()) {
932212904Sdim          unsigned ActiveSizeBits
933212904Sdim            = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
934212904Sdim          if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
935218893Sdim            Diag(ArraySize->getSourceRange().getBegin(),
936212904Sdim                 diag::err_array_too_large)
937212904Sdim              << Value.toString(10)
938212904Sdim              << ArraySize->getSourceRange();
939212904Sdim            return ExprError();
940212904Sdim          }
941212904Sdim        }
942210299Sed      } else if (TypeIdParens.isValid()) {
943210299Sed        // Can't have dynamic array size when the type-id is in parentheses.
944210299Sed        Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
945210299Sed          << ArraySize->getSourceRange()
946210299Sed          << FixItHint::CreateRemoval(TypeIdParens.getBegin())
947210299Sed          << FixItHint::CreateRemoval(TypeIdParens.getEnd());
948218893Sdim
949210299Sed        TypeIdParens = SourceRange();
950193326Sed      }
951193326Sed    }
952218893Sdim
953221345Sdim    ArraySize = ImpCastExprToType(ArraySize, Context.getSizeType(),
954221345Sdim                      CK_IntegralCast).take();
955193326Sed  }
956193326Sed
957193326Sed  FunctionDecl *OperatorNew = 0;
958193326Sed  FunctionDecl *OperatorDelete = 0;
959193326Sed  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
960193326Sed  unsigned NumPlaceArgs = PlacementArgs.size();
961218893Sdim
962193326Sed  if (!AllocType->isDependentType() &&
963193326Sed      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
964193326Sed      FindAllocationFunctions(StartLoc,
965193326Sed                              SourceRange(PlacementLParen, PlacementRParen),
966193326Sed                              UseGlobal, AllocType, ArraySize, PlaceArgs,
967193326Sed                              NumPlaceArgs, OperatorNew, OperatorDelete))
968193326Sed    return ExprError();
969218893Sdim
970218893Sdim  // If this is an array allocation, compute whether the usual array
971218893Sdim  // deallocation function for the type has a size_t parameter.
972218893Sdim  bool UsualArrayDeleteWantsSize = false;
973218893Sdim  if (ArraySize && !AllocType->isDependentType())
974218893Sdim    UsualArrayDeleteWantsSize
975218893Sdim      = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
976218893Sdim
977199990Srdivacky  llvm::SmallVector<Expr *, 8> AllPlaceArgs;
978199990Srdivacky  if (OperatorNew) {
979199990Srdivacky    // Add default arguments, if any.
980218893Sdim    const FunctionProtoType *Proto =
981199990Srdivacky      OperatorNew->getType()->getAs<FunctionProtoType>();
982218893Sdim    VariadicCallType CallType =
983199990Srdivacky      Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
984218893Sdim
985207619Srdivacky    if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
986218893Sdim                               Proto, 1, PlaceArgs, NumPlaceArgs,
987207619Srdivacky                               AllPlaceArgs, CallType))
988199990Srdivacky      return ExprError();
989218893Sdim
990199990Srdivacky    NumPlaceArgs = AllPlaceArgs.size();
991199990Srdivacky    if (NumPlaceArgs > 0)
992199990Srdivacky      PlaceArgs = &AllPlaceArgs[0];
993199990Srdivacky  }
994218893Sdim
995193326Sed  bool Init = ConstructorLParen.isValid();
996193326Sed  // --- Choosing a constructor ---
997193326Sed  CXXConstructorDecl *Constructor = 0;
998193326Sed  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
999193326Sed  unsigned NumConsArgs = ConstructorArgs.size();
1000212904Sdim  ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
1001199482Srdivacky
1002207619Srdivacky  // Array 'new' can't have any initializers.
1003208600Srdivacky  if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
1004207619Srdivacky    SourceRange InitRange(ConsArgs[0]->getLocStart(),
1005207619Srdivacky                          ConsArgs[NumConsArgs - 1]->getLocEnd());
1006218893Sdim
1007207619Srdivacky    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1008207619Srdivacky    return ExprError();
1009207619Srdivacky  }
1010207619Srdivacky
1011201361Srdivacky  if (!AllocType->isDependentType() &&
1012201361Srdivacky      !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
1013201361Srdivacky    // C++0x [expr.new]p15:
1014201361Srdivacky    //   A new-expression that creates an object of type T initializes that
1015201361Srdivacky    //   object as follows:
1016201361Srdivacky    InitializationKind Kind
1017201361Srdivacky    //     - If the new-initializer is omitted, the object is default-
1018201361Srdivacky    //       initialized (8.5); if no initialization is performed,
1019201361Srdivacky    //       the object has indeterminate value
1020218893Sdim      = !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
1021218893Sdim    //     - Otherwise, the new-initializer is interpreted according to the
1022201361Srdivacky    //       initialization rules of 8.5 for direct-initialization.
1023218893Sdim             : InitializationKind::CreateDirect(TypeRange.getBegin(),
1024218893Sdim                                                ConstructorLParen,
1025201361Srdivacky                                                ConstructorRParen);
1026218893Sdim
1027201361Srdivacky    InitializedEntity Entity
1028201361Srdivacky      = InitializedEntity::InitializeNew(StartLoc, AllocType);
1029201361Srdivacky    InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
1030218893Sdim    ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1031201361Srdivacky                                                move(ConstructorArgs));
1032201361Srdivacky    if (FullInit.isInvalid())
1033193326Sed      return ExprError();
1034218893Sdim
1035218893Sdim    // FullInit is our initializer; walk through it to determine if it's a
1036201361Srdivacky    // constructor call, which CXXNewExpr handles directly.
1037201361Srdivacky    if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
1038201361Srdivacky      if (CXXBindTemporaryExpr *Binder
1039201361Srdivacky            = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
1040201361Srdivacky        FullInitExpr = Binder->getSubExpr();
1041201361Srdivacky      if (CXXConstructExpr *Construct
1042201361Srdivacky                    = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
1043201361Srdivacky        Constructor = Construct->getConstructor();
1044201361Srdivacky        for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
1045201361Srdivacky                                         AEnd = Construct->arg_end();
1046201361Srdivacky             A != AEnd; ++A)
1047218893Sdim          ConvertedConstructorArgs.push_back(*A);
1048201361Srdivacky      } else {
1049201361Srdivacky        // Take the converted initializer.
1050201361Srdivacky        ConvertedConstructorArgs.push_back(FullInit.release());
1051201361Srdivacky      }
1052201361Srdivacky    } else {
1053201361Srdivacky      // No initialization required.
1054201361Srdivacky    }
1055218893Sdim
1056201361Srdivacky    // Take the converted arguments and use them for the new expression.
1057198092Srdivacky    NumConsArgs = ConvertedConstructorArgs.size();
1058198092Srdivacky    ConsArgs = (Expr **)ConvertedConstructorArgs.take();
1059193326Sed  }
1060218893Sdim
1061204643Srdivacky  // Mark the new and delete operators as referenced.
1062204643Srdivacky  if (OperatorNew)
1063204643Srdivacky    MarkDeclarationReferenced(StartLoc, OperatorNew);
1064204643Srdivacky  if (OperatorDelete)
1065204643Srdivacky    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1066204643Srdivacky
1067193326Sed  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
1068218893Sdim
1069193326Sed  PlacementArgs.release();
1070193326Sed  ConstructorArgs.release();
1071218893Sdim
1072203955Srdivacky  return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
1073210299Sed                                        PlaceArgs, NumPlaceArgs, TypeIdParens,
1074203955Srdivacky                                        ArraySize, Constructor, Init,
1075203955Srdivacky                                        ConsArgs, NumConsArgs, OperatorDelete,
1076218893Sdim                                        UsualArrayDeleteWantsSize,
1077218893Sdim                                        ResultType, AllocTypeInfo,
1078218893Sdim                                        StartLoc,
1079203955Srdivacky                                        Init ? ConstructorRParen :
1080218893Sdim                                               TypeRange.getEnd(),
1081218893Sdim                                        ConstructorLParen, ConstructorRParen));
1082193326Sed}
1083193326Sed
1084193326Sed/// CheckAllocatedType - Checks that a type is suitable as the allocated type
1085193326Sed/// in a new-expression.
1086193326Sed/// dimension off and stores the size expression in ArraySize.
1087193326Sedbool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1088198092Srdivacky                              SourceRange R) {
1089193326Sed  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1090193326Sed  //   abstract class type or array thereof.
1091193326Sed  if (AllocType->isFunctionType())
1092193326Sed    return Diag(Loc, diag::err_bad_new_type)
1093193326Sed      << AllocType << 0 << R;
1094193326Sed  else if (AllocType->isReferenceType())
1095193326Sed    return Diag(Loc, diag::err_bad_new_type)
1096193326Sed      << AllocType << 1 << R;
1097193326Sed  else if (!AllocType->isDependentType() &&
1098193326Sed           RequireCompleteType(Loc, AllocType,
1099198092Srdivacky                               PDiag(diag::err_new_incomplete_type)
1100198092Srdivacky                                 << R))
1101193326Sed    return true;
1102193326Sed  else if (RequireNonAbstractType(Loc, AllocType,
1103193326Sed                                  diag::err_allocation_of_abstract_type))
1104193326Sed    return true;
1105218893Sdim  else if (AllocType->isVariablyModifiedType())
1106218893Sdim    return Diag(Loc, diag::err_variably_modified_new_type)
1107218893Sdim             << AllocType;
1108221345Sdim  else if (unsigned AddressSpace = AllocType.getAddressSpace())
1109221345Sdim    return Diag(Loc, diag::err_address_space_qualified_new)
1110221345Sdim      << AllocType.getUnqualifiedType() << AddressSpace;
1111221345Sdim
1112193326Sed  return false;
1113193326Sed}
1114193326Sed
1115204643Srdivacky/// \brief Determine whether the given function is a non-placement
1116204643Srdivacky/// deallocation function.
1117204643Srdivackystatic bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1118204643Srdivacky  if (FD->isInvalidDecl())
1119204643Srdivacky    return false;
1120204643Srdivacky
1121204643Srdivacky  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1122204643Srdivacky    return Method->isUsualDeallocationFunction();
1123204643Srdivacky
1124204643Srdivacky  return ((FD->getOverloadedOperator() == OO_Delete ||
1125204643Srdivacky           FD->getOverloadedOperator() == OO_Array_Delete) &&
1126204643Srdivacky          FD->getNumParams() == 1);
1127204643Srdivacky}
1128204643Srdivacky
1129193326Sed/// FindAllocationFunctions - Finds the overloads of operator new and delete
1130193326Sed/// that are appropriate for the allocation.
1131193326Sedbool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1132193326Sed                                   bool UseGlobal, QualType AllocType,
1133193326Sed                                   bool IsArray, Expr **PlaceArgs,
1134193326Sed                                   unsigned NumPlaceArgs,
1135193326Sed                                   FunctionDecl *&OperatorNew,
1136198092Srdivacky                                   FunctionDecl *&OperatorDelete) {
1137193326Sed  // --- Choosing an allocation function ---
1138193326Sed  // C++ 5.3.4p8 - 14 & 18
1139193326Sed  // 1) If UseGlobal is true, only look in the global scope. Else, also look
1140193326Sed  //   in the scope of the allocated class.
1141193326Sed  // 2) If an array size is given, look for operator new[], else look for
1142193326Sed  //   operator new.
1143193326Sed  // 3) The first argument is always size_t. Append the arguments from the
1144193326Sed  //   placement form.
1145193326Sed
1146193326Sed  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
1147193326Sed  // We don't care about the actual value of this argument.
1148193326Sed  // FIXME: Should the Sema create the expression and embed it in the syntax
1149193326Sed  // tree? Or should the consumer just recalculate the value?
1150212904Sdim  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1151198092Srdivacky                      Context.Target.getPointerWidth(0)),
1152198092Srdivacky                      Context.getSizeType(),
1153198092Srdivacky                      SourceLocation());
1154198092Srdivacky  AllocArgs[0] = &Size;
1155193326Sed  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1156193326Sed
1157204643Srdivacky  // C++ [expr.new]p8:
1158204643Srdivacky  //   If the allocated type is a non-array type, the allocation
1159218893Sdim  //   function's name is operator new and the deallocation function's
1160204643Srdivacky  //   name is operator delete. If the allocated type is an array
1161218893Sdim  //   type, the allocation function's name is operator new[] and the
1162218893Sdim  //   deallocation function's name is operator delete[].
1163193326Sed  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1164193326Sed                                        IsArray ? OO_Array_New : OO_New);
1165204643Srdivacky  DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1166204643Srdivacky                                        IsArray ? OO_Array_Delete : OO_Delete);
1167204643Srdivacky
1168212904Sdim  QualType AllocElemType = Context.getBaseElementType(AllocType);
1169212904Sdim
1170212904Sdim  if (AllocElemType->isRecordType() && !UseGlobal) {
1171198092Srdivacky    CXXRecordDecl *Record
1172212904Sdim      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1173193326Sed    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1174193326Sed                          AllocArgs.size(), Record, /*AllowMissing=*/true,
1175193326Sed                          OperatorNew))
1176193326Sed      return true;
1177193326Sed  }
1178193326Sed  if (!OperatorNew) {
1179193326Sed    // Didn't find a member overload. Look for a global one.
1180193326Sed    DeclareGlobalNewDelete();
1181193326Sed    DeclContext *TUDecl = Context.getTranslationUnitDecl();
1182193326Sed    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
1183193326Sed                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1184193326Sed                          OperatorNew))
1185193326Sed      return true;
1186193326Sed  }
1187193326Sed
1188207619Srdivacky  // We don't need an operator delete if we're running under
1189207619Srdivacky  // -fno-exceptions.
1190207619Srdivacky  if (!getLangOptions().Exceptions) {
1191207619Srdivacky    OperatorDelete = 0;
1192207619Srdivacky    return false;
1193207619Srdivacky  }
1194207619Srdivacky
1195193326Sed  // FindAllocationOverload can change the passed in arguments, so we need to
1196193326Sed  // copy them back.
1197193326Sed  if (NumPlaceArgs > 0)
1198193326Sed    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
1199198092Srdivacky
1200204643Srdivacky  // C++ [expr.new]p19:
1201204643Srdivacky  //
1202204643Srdivacky  //   If the new-expression begins with a unary :: operator, the
1203218893Sdim  //   deallocation function's name is looked up in the global
1204204643Srdivacky  //   scope. Otherwise, if the allocated type is a class type T or an
1205218893Sdim  //   array thereof, the deallocation function's name is looked up in
1206204643Srdivacky  //   the scope of T. If this lookup fails to find the name, or if
1207204643Srdivacky  //   the allocated type is not a class type or array thereof, the
1208218893Sdim  //   deallocation function's name is looked up in the global scope.
1209204643Srdivacky  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
1210212904Sdim  if (AllocElemType->isRecordType() && !UseGlobal) {
1211204643Srdivacky    CXXRecordDecl *RD
1212212904Sdim      = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1213204643Srdivacky    LookupQualifiedName(FoundDelete, RD);
1214204643Srdivacky  }
1215205408Srdivacky  if (FoundDelete.isAmbiguous())
1216205408Srdivacky    return true; // FIXME: clean up expressions?
1217204643Srdivacky
1218204643Srdivacky  if (FoundDelete.empty()) {
1219204643Srdivacky    DeclareGlobalNewDelete();
1220204643Srdivacky    LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1221204643Srdivacky  }
1222204643Srdivacky
1223204643Srdivacky  FoundDelete.suppressDiagnostics();
1224205408Srdivacky
1225205408Srdivacky  llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
1226205408Srdivacky
1227218893Sdim  // Whether we're looking for a placement operator delete is dictated
1228218893Sdim  // by whether we selected a placement operator new, not by whether
1229218893Sdim  // we had explicit placement arguments.  This matters for things like
1230218893Sdim  //   struct A { void *operator new(size_t, int = 0); ... };
1231218893Sdim  //   A *a = new A()
1232218893Sdim  bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1233218893Sdim
1234218893Sdim  if (isPlacementNew) {
1235204643Srdivacky    // C++ [expr.new]p20:
1236204643Srdivacky    //   A declaration of a placement deallocation function matches the
1237204643Srdivacky    //   declaration of a placement allocation function if it has the
1238204643Srdivacky    //   same number of parameters and, after parameter transformations
1239204643Srdivacky    //   (8.3.5), all parameter types except the first are
1240204643Srdivacky    //   identical. [...]
1241218893Sdim    //
1242204643Srdivacky    // To perform this comparison, we compute the function type that
1243204643Srdivacky    // the deallocation function should have, and use that type both
1244204643Srdivacky    // for template argument deduction and for comparison purposes.
1245218893Sdim    //
1246218893Sdim    // FIXME: this comparison should ignore CC and the like.
1247204643Srdivacky    QualType ExpectedFunctionType;
1248204643Srdivacky    {
1249204643Srdivacky      const FunctionProtoType *Proto
1250204643Srdivacky        = OperatorNew->getType()->getAs<FunctionProtoType>();
1251218893Sdim
1252204643Srdivacky      llvm::SmallVector<QualType, 4> ArgTypes;
1253218893Sdim      ArgTypes.push_back(Context.VoidPtrTy);
1254204643Srdivacky      for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1255204643Srdivacky        ArgTypes.push_back(Proto->getArgType(I));
1256204643Srdivacky
1257218893Sdim      FunctionProtoType::ExtProtoInfo EPI;
1258218893Sdim      EPI.Variadic = Proto->isVariadic();
1259218893Sdim
1260204643Srdivacky      ExpectedFunctionType
1261204643Srdivacky        = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
1262218893Sdim                                  ArgTypes.size(), EPI);
1263204643Srdivacky    }
1264204643Srdivacky
1265218893Sdim    for (LookupResult::iterator D = FoundDelete.begin(),
1266204643Srdivacky                             DEnd = FoundDelete.end();
1267204643Srdivacky         D != DEnd; ++D) {
1268204643Srdivacky      FunctionDecl *Fn = 0;
1269218893Sdim      if (FunctionTemplateDecl *FnTmpl
1270204643Srdivacky            = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1271204643Srdivacky        // Perform template argument deduction to try to match the
1272204643Srdivacky        // expected function type.
1273204643Srdivacky        TemplateDeductionInfo Info(Context, StartLoc);
1274204643Srdivacky        if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1275204643Srdivacky          continue;
1276204643Srdivacky      } else
1277204643Srdivacky        Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1278204643Srdivacky
1279204643Srdivacky      if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
1280205408Srdivacky        Matches.push_back(std::make_pair(D.getPair(), Fn));
1281204643Srdivacky    }
1282204643Srdivacky  } else {
1283204643Srdivacky    // C++ [expr.new]p20:
1284204643Srdivacky    //   [...] Any non-placement deallocation function matches a
1285204643Srdivacky    //   non-placement allocation function. [...]
1286218893Sdim    for (LookupResult::iterator D = FoundDelete.begin(),
1287204643Srdivacky                             DEnd = FoundDelete.end();
1288204643Srdivacky         D != DEnd; ++D) {
1289204643Srdivacky      if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1290204643Srdivacky        if (isNonPlacementDeallocationFunction(Fn))
1291205408Srdivacky          Matches.push_back(std::make_pair(D.getPair(), Fn));
1292204643Srdivacky    }
1293204643Srdivacky  }
1294204643Srdivacky
1295204643Srdivacky  // C++ [expr.new]p20:
1296204643Srdivacky  //   [...] If the lookup finds a single matching deallocation
1297204643Srdivacky  //   function, that function will be called; otherwise, no
1298204643Srdivacky  //   deallocation function will be called.
1299204643Srdivacky  if (Matches.size() == 1) {
1300205408Srdivacky    OperatorDelete = Matches[0].second;
1301204643Srdivacky
1302204643Srdivacky    // C++0x [expr.new]p20:
1303204643Srdivacky    //   If the lookup finds the two-parameter form of a usual
1304204643Srdivacky    //   deallocation function (3.7.4.2) and that function, considered
1305204643Srdivacky    //   as a placement deallocation function, would have been
1306204643Srdivacky    //   selected as a match for the allocation function, the program
1307204643Srdivacky    //   is ill-formed.
1308204643Srdivacky    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1309204643Srdivacky        isNonPlacementDeallocationFunction(OperatorDelete)) {
1310204643Srdivacky      Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1311218893Sdim        << SourceRange(PlaceArgs[0]->getLocStart(),
1312204643Srdivacky                       PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1313204643Srdivacky      Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1314204643Srdivacky        << DeleteName;
1315205408Srdivacky    } else {
1316205408Srdivacky      CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
1317205408Srdivacky                            Matches[0].first);
1318204643Srdivacky    }
1319204643Srdivacky  }
1320204643Srdivacky
1321193326Sed  return false;
1322193326Sed}
1323193326Sed
1324193326Sed/// FindAllocationOverload - Find an fitting overload for the allocation
1325193326Sed/// function in the specified scope.
1326193326Sedbool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1327193326Sed                                  DeclarationName Name, Expr** Args,
1328193326Sed                                  unsigned NumArgs, DeclContext *Ctx,
1329198092Srdivacky                                  bool AllowMissing, FunctionDecl *&Operator) {
1330199482Srdivacky  LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1331199482Srdivacky  LookupQualifiedName(R, Ctx);
1332198092Srdivacky  if (R.empty()) {
1333193326Sed    if (AllowMissing)
1334193326Sed      return false;
1335193326Sed    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1336193326Sed      << Name << Range;
1337193326Sed  }
1338193326Sed
1339205408Srdivacky  if (R.isAmbiguous())
1340205408Srdivacky    return true;
1341198092Srdivacky
1342205408Srdivacky  R.suppressDiagnostics();
1343205408Srdivacky
1344203955Srdivacky  OverloadCandidateSet Candidates(StartLoc);
1345218893Sdim  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1346198092Srdivacky       Alloc != AllocEnd; ++Alloc) {
1347193326Sed    // Even member operator new/delete are implicitly treated as
1348193326Sed    // static, so don't use AddMemberCandidate.
1349205408Srdivacky    NamedDecl *D = (*Alloc)->getUnderlyingDecl();
1350203955Srdivacky
1351205408Srdivacky    if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1352205408Srdivacky      AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
1353203955Srdivacky                                   /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1354203955Srdivacky                                   Candidates,
1355203955Srdivacky                                   /*SuppressUserConversions=*/false);
1356198092Srdivacky      continue;
1357203955Srdivacky    }
1358203955Srdivacky
1359205408Srdivacky    FunctionDecl *Fn = cast<FunctionDecl>(D);
1360205408Srdivacky    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
1361203955Srdivacky                         /*SuppressUserConversions=*/false);
1362193326Sed  }
1363193326Sed
1364193326Sed  // Do the resolution.
1365193326Sed  OverloadCandidateSet::iterator Best;
1366212904Sdim  switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
1367193326Sed  case OR_Success: {
1368193326Sed    // Got one!
1369193326Sed    FunctionDecl *FnDecl = Best->Function;
1370219077Sdim    MarkDeclarationReferenced(StartLoc, FnDecl);
1371193326Sed    // The first argument is size_t, and the first parameter must be size_t,
1372193326Sed    // too. This is checked on declaration and can be assumed. (It can't be
1373193326Sed    // asserted on, though, since invalid decls are left in there.)
1374205408Srdivacky    // Watch out for variadic allocator function.
1375199990Srdivacky    unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1376199990Srdivacky    for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
1377212904Sdim      ExprResult Result
1378206084Srdivacky        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1379218893Sdim                                                       Context,
1380206084Srdivacky                                                       FnDecl->getParamDecl(i)),
1381206084Srdivacky                                    SourceLocation(),
1382218893Sdim                                    Owned(Args[i]));
1383206084Srdivacky      if (Result.isInvalid())
1384193326Sed        return true;
1385218893Sdim
1386206084Srdivacky      Args[i] = Result.takeAs<Expr>();
1387193326Sed    }
1388193326Sed    Operator = FnDecl;
1389205408Srdivacky    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
1390193326Sed    return false;
1391193326Sed  }
1392193326Sed
1393193326Sed  case OR_No_Viable_Function:
1394193326Sed    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1395193326Sed      << Name << Range;
1396212904Sdim    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1397193326Sed    return true;
1398193326Sed
1399193326Sed  case OR_Ambiguous:
1400193326Sed    Diag(StartLoc, diag::err_ovl_ambiguous_call)
1401193326Sed      << Name << Range;
1402212904Sdim    Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
1403193326Sed    return true;
1404193326Sed
1405221345Sdim  case OR_Deleted: {
1406193326Sed    Diag(StartLoc, diag::err_ovl_deleted_call)
1407193326Sed      << Best->Function->isDeleted()
1408219077Sdim      << Name
1409221345Sdim      << getDeletedOrUnavailableSuffix(Best->Function)
1410219077Sdim      << Range;
1411212904Sdim    Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
1412193326Sed    return true;
1413193326Sed  }
1414221345Sdim  }
1415193326Sed  assert(false && "Unreachable, bad result from BestViableFunction");
1416193326Sed  return true;
1417193326Sed}
1418193326Sed
1419193326Sed
1420193326Sed/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1421193326Sed/// delete. These are:
1422193326Sed/// @code
1423221345Sdim///   // C++03:
1424193326Sed///   void* operator new(std::size_t) throw(std::bad_alloc);
1425193326Sed///   void* operator new[](std::size_t) throw(std::bad_alloc);
1426193326Sed///   void operator delete(void *) throw();
1427193326Sed///   void operator delete[](void *) throw();
1428221345Sdim///   // C++0x:
1429221345Sdim///   void* operator new(std::size_t);
1430221345Sdim///   void* operator new[](std::size_t);
1431221345Sdim///   void operator delete(void *);
1432221345Sdim///   void operator delete[](void *);
1433193326Sed/// @endcode
1434221345Sdim/// C++0x operator delete is implicitly noexcept.
1435193326Sed/// Note that the placement and nothrow forms of new are *not* implicitly
1436193326Sed/// declared. Their use requires including \<new\>.
1437198092Srdivackyvoid Sema::DeclareGlobalNewDelete() {
1438193326Sed  if (GlobalNewDeleteDeclared)
1439193326Sed    return;
1440218893Sdim
1441198092Srdivacky  // C++ [basic.std.dynamic]p2:
1442218893Sdim  //   [...] The following allocation and deallocation functions (18.4) are
1443218893Sdim  //   implicitly declared in global scope in each translation unit of a
1444198092Srdivacky  //   program
1445218893Sdim  //
1446221345Sdim  //     C++03:
1447198092Srdivacky  //     void* operator new(std::size_t) throw(std::bad_alloc);
1448218893Sdim  //     void* operator new[](std::size_t) throw(std::bad_alloc);
1449218893Sdim  //     void  operator delete(void*) throw();
1450198092Srdivacky  //     void  operator delete[](void*) throw();
1451221345Sdim  //     C++0x:
1452221345Sdim  //     void* operator new(std::size_t);
1453221345Sdim  //     void* operator new[](std::size_t);
1454221345Sdim  //     void  operator delete(void*);
1455221345Sdim  //     void  operator delete[](void*);
1456198092Srdivacky  //
1457218893Sdim  //   These implicit declarations introduce only the function names operator
1458198092Srdivacky  //   new, operator new[], operator delete, operator delete[].
1459198092Srdivacky  //
1460198092Srdivacky  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1461198092Srdivacky  // "std" or "bad_alloc" as necessary to form the exception specification.
1462198092Srdivacky  // However, we do not make these implicit declarations visible to name
1463198092Srdivacky  // lookup.
1464221345Sdim  // Note that the C++0x versions of operator delete are deallocation functions,
1465221345Sdim  // and thus are implicitly noexcept.
1466221345Sdim  if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
1467198092Srdivacky    // The "std::bad_alloc" class has not yet been declared, so build it
1468198092Srdivacky    // implicitly.
1469218893Sdim    StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1470218893Sdim                                        getOrCreateStdNamespace(),
1471221345Sdim                                        SourceLocation(), SourceLocation(),
1472218893Sdim                                      &PP.getIdentifierTable().get("bad_alloc"),
1473221345Sdim                                        0);
1474212904Sdim    getStdBadAlloc()->setImplicit(true);
1475198092Srdivacky  }
1476218893Sdim
1477193326Sed  GlobalNewDeleteDeclared = true;
1478193326Sed
1479193326Sed  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1480193326Sed  QualType SizeT = Context.getSizeType();
1481201361Srdivacky  bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
1482193326Sed
1483193326Sed  DeclareGlobalAllocationFunction(
1484193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_New),
1485201361Srdivacky      VoidPtr, SizeT, AssumeSaneOperatorNew);
1486193326Sed  DeclareGlobalAllocationFunction(
1487193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
1488201361Srdivacky      VoidPtr, SizeT, AssumeSaneOperatorNew);
1489193326Sed  DeclareGlobalAllocationFunction(
1490193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1491193326Sed      Context.VoidTy, VoidPtr);
1492193326Sed  DeclareGlobalAllocationFunction(
1493193326Sed      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1494193326Sed      Context.VoidTy, VoidPtr);
1495193326Sed}
1496193326Sed
1497193326Sed/// DeclareGlobalAllocationFunction - Declares a single implicit global
1498193326Sed/// allocation function if it doesn't already exist.
1499193326Sedvoid Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
1500201361Srdivacky                                           QualType Return, QualType Argument,
1501201361Srdivacky                                           bool AddMallocAttr) {
1502193326Sed  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1503193326Sed
1504193326Sed  // Check if this function is already declared.
1505193326Sed  {
1506193326Sed    DeclContext::lookup_iterator Alloc, AllocEnd;
1507195341Sed    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
1508193326Sed         Alloc != AllocEnd; ++Alloc) {
1509203955Srdivacky      // Only look at non-template functions, as it is the predefined,
1510203955Srdivacky      // non-templated allocation function we are trying to declare here.
1511203955Srdivacky      if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1512203955Srdivacky        QualType InitialParamType =
1513201361Srdivacky          Context.getCanonicalType(
1514203955Srdivacky            Func->getParamDecl(0)->getType().getUnqualifiedType());
1515203955Srdivacky        // FIXME: Do we need to check for default arguments here?
1516212904Sdim        if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1517212904Sdim          if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
1518212904Sdim            Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1519203955Srdivacky          return;
1520212904Sdim        }
1521203955Srdivacky      }
1522193326Sed    }
1523193326Sed  }
1524193326Sed
1525198092Srdivacky  QualType BadAllocType;
1526218893Sdim  bool HasBadAllocExceptionSpec
1527198092Srdivacky    = (Name.getCXXOverloadedOperator() == OO_New ||
1528198092Srdivacky       Name.getCXXOverloadedOperator() == OO_Array_New);
1529221345Sdim  if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
1530198092Srdivacky    assert(StdBadAlloc && "Must have std::bad_alloc declared");
1531212904Sdim    BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
1532198092Srdivacky  }
1533218893Sdim
1534218893Sdim  FunctionProtoType::ExtProtoInfo EPI;
1535218893Sdim  if (HasBadAllocExceptionSpec) {
1536221345Sdim    if (!getLangOptions().CPlusPlus0x) {
1537221345Sdim      EPI.ExceptionSpecType = EST_Dynamic;
1538221345Sdim      EPI.NumExceptions = 1;
1539221345Sdim      EPI.Exceptions = &BadAllocType;
1540221345Sdim    }
1541221345Sdim  } else {
1542221345Sdim    EPI.ExceptionSpecType = getLangOptions().CPlusPlus0x ?
1543221345Sdim                                EST_BasicNoexcept : EST_DynamicNone;
1544218893Sdim  }
1545218893Sdim
1546218893Sdim  QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
1547193326Sed  FunctionDecl *Alloc =
1548221345Sdim    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1549221345Sdim                         SourceLocation(), Name,
1550212904Sdim                         FnType, /*TInfo=*/0, SC_None,
1551212904Sdim                         SC_None, false, true);
1552193326Sed  Alloc->setImplicit();
1553218893Sdim
1554201361Srdivacky  if (AddMallocAttr)
1555212904Sdim    Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
1556218893Sdim
1557193326Sed  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
1558221345Sdim                                           SourceLocation(), 0,
1559221345Sdim                                           Argument, /*TInfo=*/0,
1560221345Sdim                                           SC_None, SC_None, 0);
1561203955Srdivacky  Alloc->setParams(&Param, 1);
1562193326Sed
1563193326Sed  // FIXME: Also add this declaration to the IdentifierResolver, but
1564193326Sed  // make sure it is at the end of the chain to coincide with the
1565193326Sed  // global scope.
1566212904Sdim  Context.getTranslationUnitDecl()->addDecl(Alloc);
1567193326Sed}
1568193326Sed
1569199482Srdivackybool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1570199482Srdivacky                                    DeclarationName Name,
1571199482Srdivacky                                    FunctionDecl* &Operator) {
1572199482Srdivacky  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
1573199482Srdivacky  // Try to find operator delete/operator delete[] in class scope.
1574199482Srdivacky  LookupQualifiedName(Found, RD);
1575218893Sdim
1576199482Srdivacky  if (Found.isAmbiguous())
1577199482Srdivacky    return true;
1578199482Srdivacky
1579210299Sed  Found.suppressDiagnostics();
1580210299Sed
1581212904Sdim  llvm::SmallVector<DeclAccessPair,4> Matches;
1582199482Srdivacky  for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1583199482Srdivacky       F != FEnd; ++F) {
1584212904Sdim    NamedDecl *ND = (*F)->getUnderlyingDecl();
1585212904Sdim
1586212904Sdim    // Ignore template operator delete members from the check for a usual
1587212904Sdim    // deallocation function.
1588212904Sdim    if (isa<FunctionTemplateDecl>(ND))
1589212904Sdim      continue;
1590212904Sdim
1591212904Sdim    if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
1592212904Sdim      Matches.push_back(F.getPair());
1593199482Srdivacky  }
1594199482Srdivacky
1595212904Sdim  // There's exactly one suitable operator;  pick it.
1596212904Sdim  if (Matches.size() == 1) {
1597212904Sdim    Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
1598212904Sdim    CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1599212904Sdim                          Matches[0]);
1600212904Sdim    return false;
1601212904Sdim
1602212904Sdim  // We found multiple suitable operators;  complain about the ambiguity.
1603212904Sdim  } else if (!Matches.empty()) {
1604212904Sdim    Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1605212904Sdim      << Name << RD;
1606212904Sdim
1607212904Sdim    for (llvm::SmallVectorImpl<DeclAccessPair>::iterator
1608212904Sdim           F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1609212904Sdim      Diag((*F)->getUnderlyingDecl()->getLocation(),
1610212904Sdim           diag::note_member_declared_here) << Name;
1611212904Sdim    return true;
1612212904Sdim  }
1613212904Sdim
1614199482Srdivacky  // We did find operator delete/operator delete[] declarations, but
1615199482Srdivacky  // none of them were suitable.
1616199482Srdivacky  if (!Found.empty()) {
1617199482Srdivacky    Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1618199482Srdivacky      << Name << RD;
1619218893Sdim
1620199482Srdivacky    for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1621212904Sdim         F != FEnd; ++F)
1622212904Sdim      Diag((*F)->getUnderlyingDecl()->getLocation(),
1623212904Sdim           diag::note_member_declared_here) << Name;
1624199482Srdivacky
1625199482Srdivacky    return true;
1626199482Srdivacky  }
1627199482Srdivacky
1628199482Srdivacky  // Look for a global declaration.
1629199482Srdivacky  DeclareGlobalNewDelete();
1630199482Srdivacky  DeclContext *TUDecl = Context.getTranslationUnitDecl();
1631218893Sdim
1632199482Srdivacky  CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1633199482Srdivacky  Expr* DeallocArgs[1];
1634199482Srdivacky  DeallocArgs[0] = &Null;
1635199482Srdivacky  if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1636199482Srdivacky                             DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1637199482Srdivacky                             Operator))
1638199482Srdivacky    return true;
1639199482Srdivacky
1640199482Srdivacky  assert(Operator && "Did not find a deallocation function!");
1641199482Srdivacky  return false;
1642199482Srdivacky}
1643199482Srdivacky
1644193326Sed/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1645193326Sed/// @code ::delete ptr; @endcode
1646193326Sed/// or
1647193326Sed/// @code delete [] ptr; @endcode
1648212904SdimExprResult
1649193326SedSema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
1650221345Sdim                     bool ArrayForm, Expr *ExE) {
1651198092Srdivacky  // C++ [expr.delete]p1:
1652198092Srdivacky  //   The operand shall have a pointer type, or a class type having a single
1653198092Srdivacky  //   conversion function to a pointer type. The result has type void.
1654198092Srdivacky  //
1655193326Sed  // DR599 amends "pointer type" to "pointer to object type" in both cases.
1656193326Sed
1657221345Sdim  ExprResult Ex = Owned(ExE);
1658198092Srdivacky  FunctionDecl *OperatorDelete = 0;
1659218893Sdim  bool ArrayFormAsWritten = ArrayForm;
1660218893Sdim  bool UsualArrayDeleteWantsSize = false;
1661198092Srdivacky
1662221345Sdim  if (!Ex.get()->isTypeDependent()) {
1663221345Sdim    QualType Type = Ex.get()->getType();
1664193326Sed
1665198092Srdivacky    if (const RecordType *Record = Type->getAs<RecordType>()) {
1666218893Sdim      if (RequireCompleteType(StartLoc, Type,
1667212904Sdim                              PDiag(diag::err_delete_incomplete_class_type)))
1668212904Sdim        return ExprError();
1669218893Sdim
1670206084Srdivacky      llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1671206084Srdivacky
1672198092Srdivacky      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1673218893Sdim      const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
1674202879Srdivacky      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1675199990Srdivacky             E = Conversions->end(); I != E; ++I) {
1676206084Srdivacky        NamedDecl *D = I.getDecl();
1677206084Srdivacky        if (isa<UsingShadowDecl>(D))
1678206084Srdivacky          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1679206084Srdivacky
1680198092Srdivacky        // Skip over templated conversion functions; they aren't considered.
1681206084Srdivacky        if (isa<FunctionTemplateDecl>(D))
1682198092Srdivacky          continue;
1683218893Sdim
1684206084Srdivacky        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
1685218893Sdim
1686198092Srdivacky        QualType ConvType = Conv->getConversionType().getNonReferenceType();
1687198092Srdivacky        if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1688212904Sdim          if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
1689198092Srdivacky            ObjectPtrConversions.push_back(Conv);
1690198092Srdivacky      }
1691198092Srdivacky      if (ObjectPtrConversions.size() == 1) {
1692198092Srdivacky        // We have a single conversion to a pointer-to-object type. Perform
1693198092Srdivacky        // that conversion.
1694206084Srdivacky        // TODO: don't redo the conversion calculation.
1695221345Sdim        ExprResult Res =
1696221345Sdim          PerformImplicitConversion(Ex.get(),
1697206084Srdivacky                            ObjectPtrConversions.front()->getConversionType(),
1698221345Sdim                                    AA_Converting);
1699221345Sdim        if (Res.isUsable()) {
1700221345Sdim          Ex = move(Res);
1701221345Sdim          Type = Ex.get()->getType();
1702198092Srdivacky        }
1703198092Srdivacky      }
1704198092Srdivacky      else if (ObjectPtrConversions.size() > 1) {
1705198092Srdivacky        Diag(StartLoc, diag::err_ambiguous_delete_operand)
1706221345Sdim              << Type << Ex.get()->getSourceRange();
1707206084Srdivacky        for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1708206084Srdivacky          NoteOverloadCandidate(ObjectPtrConversions[i]);
1709198092Srdivacky        return ExprError();
1710198092Srdivacky      }
1711193326Sed    }
1712193326Sed
1713193326Sed    if (!Type->isPointerType())
1714193326Sed      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1715221345Sdim        << Type << Ex.get()->getSourceRange());
1716193326Sed
1717198092Srdivacky    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
1718208600Srdivacky    if (Pointee->isVoidType() && !isSFINAEContext()) {
1719218893Sdim      // The C++ standard bans deleting a pointer to a non-object type, which
1720208600Srdivacky      // effectively bans deletion of "void*". However, most compilers support
1721208600Srdivacky      // this, so we treat it as a warning unless we're in a SFINAE context.
1722208600Srdivacky      Diag(StartLoc, diag::ext_delete_void_ptr_operand)
1723221345Sdim        << Type << Ex.get()->getSourceRange();
1724208600Srdivacky    } else if (Pointee->isFunctionType() || Pointee->isVoidType())
1725193326Sed      return ExprError(Diag(StartLoc, diag::err_delete_operand)
1726221345Sdim        << Type << Ex.get()->getSourceRange());
1727193326Sed    else if (!Pointee->isDependentType() &&
1728198092Srdivacky             RequireCompleteType(StartLoc, Pointee,
1729198092Srdivacky                                 PDiag(diag::warn_delete_incomplete)
1730221345Sdim                                   << Ex.get()->getSourceRange()))
1731193326Sed      return ExprError();
1732221345Sdim    else if (unsigned AddressSpace = Pointee.getAddressSpace())
1733221345Sdim      return Diag(Ex.get()->getLocStart(),
1734221345Sdim                  diag::err_address_space_qualified_delete)
1735221345Sdim               << Pointee.getUnqualifiedType() << AddressSpace;
1736198092Srdivacky    // C++ [expr.delete]p2:
1737218893Sdim    //   [Note: a pointer to a const type can be the operand of a
1738218893Sdim    //   delete-expression; it is not necessary to cast away the constness
1739218893Sdim    //   (5.2.11) of the pointer expression before it is used as the operand
1740198092Srdivacky    //   of the delete-expression. ]
1741221345Sdim    Ex = ImpCastExprToType(Ex.take(), Context.getPointerType(Context.VoidTy),
1742212904Sdim                      CK_NoOp);
1743218893Sdim
1744218893Sdim    if (Pointee->isArrayType() && !ArrayForm) {
1745218893Sdim      Diag(StartLoc, diag::warn_delete_array_type)
1746221345Sdim          << Type << Ex.get()->getSourceRange()
1747218893Sdim          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
1748218893Sdim      ArrayForm = true;
1749218893Sdim    }
1750218893Sdim
1751198092Srdivacky    DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1752198092Srdivacky                                      ArrayForm ? OO_Array_Delete : OO_Delete);
1753198092Srdivacky
1754212904Sdim    QualType PointeeElem = Context.getBaseElementType(Pointee);
1755212904Sdim    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1756199482Srdivacky      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1757199482Srdivacky
1758218893Sdim      if (!UseGlobal &&
1759199482Srdivacky          FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
1760199482Srdivacky        return ExprError();
1761218893Sdim
1762218893Sdim      // If we're allocating an array of records, check whether the
1763218893Sdim      // usual operator delete[] has a size_t parameter.
1764218893Sdim      if (ArrayForm) {
1765218893Sdim        // If the user specifically asked to use the global allocator,
1766218893Sdim        // we'll need to do the lookup into the class.
1767218893Sdim        if (UseGlobal)
1768218893Sdim          UsualArrayDeleteWantsSize =
1769218893Sdim            doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
1770218893Sdim
1771218893Sdim        // Otherwise, the usual operator delete[] should be the
1772218893Sdim        // function we just found.
1773218893Sdim        else if (isa<CXXMethodDecl>(OperatorDelete))
1774218893Sdim          UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
1775218893Sdim      }
1776218893Sdim
1777199482Srdivacky      if (!RD->hasTrivialDestructor())
1778218893Sdim        if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1779198092Srdivacky          MarkDeclarationReferenced(StartLoc,
1780198092Srdivacky                                    const_cast<CXXDestructorDecl*>(Dtor));
1781218893Sdim          DiagnoseUseOfDecl(Dtor, StartLoc);
1782218893Sdim        }
1783198092Srdivacky    }
1784218893Sdim
1785198092Srdivacky    if (!OperatorDelete) {
1786199482Srdivacky      // Look for a global declaration.
1787198092Srdivacky      DeclareGlobalNewDelete();
1788198092Srdivacky      DeclContext *TUDecl = Context.getTranslationUnitDecl();
1789221345Sdim      Expr *Arg = Ex.get();
1790198092Srdivacky      if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
1791221345Sdim                                 &Arg, 1, TUDecl, /*AllowMissing=*/false,
1792198092Srdivacky                                 OperatorDelete))
1793198092Srdivacky        return ExprError();
1794198092Srdivacky    }
1795198092Srdivacky
1796207619Srdivacky    MarkDeclarationReferenced(StartLoc, OperatorDelete);
1797218893Sdim
1798218893Sdim    // Check access and ambiguity of operator delete and destructor.
1799218893Sdim    if (const RecordType *RT = PointeeElem->getAs<RecordType>()) {
1800218893Sdim      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1801218893Sdim      if (CXXDestructorDecl *Dtor = LookupDestructor(RD)) {
1802221345Sdim          CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
1803218893Sdim                      PDiag(diag::err_access_dtor) << PointeeElem);
1804218893Sdim      }
1805218893Sdim    }
1806207619Srdivacky
1807193326Sed  }
1808193326Sed
1809193326Sed  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
1810218893Sdim                                           ArrayFormAsWritten,
1811218893Sdim                                           UsualArrayDeleteWantsSize,
1812221345Sdim                                           OperatorDelete, Ex.take(), StartLoc));
1813193326Sed}
1814193326Sed
1815199990Srdivacky/// \brief Check the use of the given variable as a C++ condition in an if,
1816199990Srdivacky/// while, do-while, or switch statement.
1817212904SdimExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1818218893Sdim                                        SourceLocation StmtLoc,
1819218893Sdim                                        bool ConvertToBoolean) {
1820199990Srdivacky  QualType T = ConditionVar->getType();
1821218893Sdim
1822199990Srdivacky  // C++ [stmt.select]p2:
1823199990Srdivacky  //   The declarator shall not specify a function or an array.
1824199990Srdivacky  if (T->isFunctionType())
1825218893Sdim    return ExprError(Diag(ConditionVar->getLocation(),
1826199990Srdivacky                          diag::err_invalid_use_of_function_type)
1827199990Srdivacky                       << ConditionVar->getSourceRange());
1828199990Srdivacky  else if (T->isArrayType())
1829218893Sdim    return ExprError(Diag(ConditionVar->getLocation(),
1830199990Srdivacky                          diag::err_invalid_use_of_array_type)
1831199990Srdivacky                     << ConditionVar->getSourceRange());
1832193326Sed
1833221345Sdim  ExprResult Condition =
1834221345Sdim    Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1835221345Sdim                                        ConditionVar,
1836218893Sdim                                        ConditionVar->getLocation(),
1837218893Sdim                            ConditionVar->getType().getNonReferenceType(),
1838221345Sdim                              VK_LValue));
1839221345Sdim  if (ConvertToBoolean) {
1840221345Sdim    Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
1841221345Sdim    if (Condition.isInvalid())
1842221345Sdim      return ExprError();
1843221345Sdim  }
1844218893Sdim
1845221345Sdim  return move(Condition);
1846193326Sed}
1847193326Sed
1848193326Sed/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1849221345SdimExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
1850193326Sed  // C++ 6.4p4:
1851193326Sed  // The value of a condition that is an initialized declaration in a statement
1852193326Sed  // other than a switch statement is the value of the declared variable
1853193326Sed  // implicitly converted to type bool. If that conversion is ill-formed, the
1854193326Sed  // program is ill-formed.
1855193326Sed  // The value of a condition that is an expression is the value of the
1856193326Sed  // expression, implicitly converted to bool.
1857193326Sed  //
1858193326Sed  return PerformContextuallyConvertToBool(CondExpr);
1859193326Sed}
1860193326Sed
1861193326Sed/// Helper function to determine whether this is the (deprecated) C++
1862193326Sed/// conversion from a string literal to a pointer to non-const char or
1863193326Sed/// non-const wchar_t (for narrow and wide string literals,
1864193326Sed/// respectively).
1865198092Srdivackybool
1866193326SedSema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1867193326Sed  // Look inside the implicit cast, if it exists.
1868193326Sed  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1869193326Sed    From = Cast->getSubExpr();
1870193326Sed
1871193326Sed  // A string literal (2.13.4) that is not a wide string literal can
1872193326Sed  // be converted to an rvalue of type "pointer to char"; a wide
1873193326Sed  // string literal can be converted to an rvalue of type "pointer
1874193326Sed  // to wchar_t" (C++ 4.2p2).
1875210299Sed  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
1876198092Srdivacky    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
1877198092Srdivacky      if (const BuiltinType *ToPointeeType
1878198092Srdivacky          = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
1879193326Sed        // This conversion is considered only when there is an
1880193326Sed        // explicit appropriate pointer target type (C++ 4.2p2).
1881198092Srdivacky        if (!ToPtrType->getPointeeType().hasQualifiers() &&
1882193326Sed            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1883193326Sed             (!StrLit->isWide() &&
1884193326Sed              (ToPointeeType->getKind() == BuiltinType::Char_U ||
1885193326Sed               ToPointeeType->getKind() == BuiltinType::Char_S))))
1886193326Sed          return true;
1887193326Sed      }
1888193326Sed
1889193326Sed  return false;
1890193326Sed}
1891193326Sed
1892218893Sdimstatic ExprResult BuildCXXCastArgument(Sema &S,
1893212904Sdim                                       SourceLocation CastLoc,
1894212904Sdim                                       QualType Ty,
1895212904Sdim                                       CastKind Kind,
1896212904Sdim                                       CXXMethodDecl *Method,
1897218893Sdim                                       NamedDecl *FoundDecl,
1898212904Sdim                                       Expr *From) {
1899207619Srdivacky  switch (Kind) {
1900207619Srdivacky  default: assert(0 && "Unhandled cast kind!");
1901212904Sdim  case CK_ConstructorConversion: {
1902212904Sdim    ASTOwningVector<Expr*> ConstructorArgs(S);
1903218893Sdim
1904207619Srdivacky    if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1905212904Sdim                                  MultiExprArg(&From, 1),
1906207619Srdivacky                                  CastLoc, ConstructorArgs))
1907212904Sdim      return ExprError();
1908218893Sdim
1909218893Sdim    ExprResult Result =
1910218893Sdim    S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1911212904Sdim                            move_arg(ConstructorArgs),
1912218893Sdim                            /*ZeroInit*/ false, CXXConstructExpr::CK_Complete,
1913218893Sdim                            SourceRange());
1914207619Srdivacky    if (Result.isInvalid())
1915212904Sdim      return ExprError();
1916218893Sdim
1917207619Srdivacky    return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1918193326Sed  }
1919218893Sdim
1920212904Sdim  case CK_UserDefinedConversion: {
1921207619Srdivacky    assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1922218893Sdim
1923207619Srdivacky    // Create an implicit call expr that calls it.
1924218893Sdim    ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Method);
1925218893Sdim    if (Result.isInvalid())
1926218893Sdim      return ExprError();
1927218893Sdim
1928218893Sdim    return S.MaybeBindToTemporary(Result.get());
1929193326Sed  }
1930207619Srdivacky  }
1931218893Sdim}
1932193326Sed
1933193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
1934193326Sed/// expression From to the type ToType using the pre-computed implicit
1935221345Sdim/// conversion sequence ICS. Returns the converted
1936201361Srdivacky/// expression. Action is the kind of conversion we're performing,
1937193326Sed/// used in the error message.
1938221345SdimExprResult
1939221345SdimSema::PerformImplicitConversion(Expr *From, QualType ToType,
1940193326Sed                                const ImplicitConversionSequence &ICS,
1941218893Sdim                                AssignmentAction Action, bool CStyle) {
1942202379Srdivacky  switch (ICS.getKind()) {
1943221345Sdim  case ImplicitConversionSequence::StandardConversion: {
1944221345Sdim    ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
1945221345Sdim                                               Action, CStyle);
1946221345Sdim    if (Res.isInvalid())
1947221345Sdim      return ExprError();
1948221345Sdim    From = Res.take();
1949193326Sed    break;
1950221345Sdim  }
1951193326Sed
1952198092Srdivacky  case ImplicitConversionSequence::UserDefinedConversion: {
1953218893Sdim
1954198092Srdivacky      FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1955218893Sdim      CastKind CastKind;
1956198092Srdivacky      QualType BeforeToType;
1957198092Srdivacky      if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
1958212904Sdim        CastKind = CK_UserDefinedConversion;
1959218893Sdim
1960198092Srdivacky        // If the user-defined conversion is specified by a conversion function,
1961198092Srdivacky        // the initial standard conversion sequence converts the source type to
1962198092Srdivacky        // the implicit object parameter of the conversion function.
1963198092Srdivacky        BeforeToType = Context.getTagDeclType(Conv->getParent());
1964218893Sdim      } else {
1965218893Sdim        const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
1966212904Sdim        CastKind = CK_ConstructorConversion;
1967199482Srdivacky        // Do no conversion if dealing with ... for the first conversion.
1968199990Srdivacky        if (!ICS.UserDefined.EllipsisConversion) {
1969218893Sdim          // If the user-defined conversion is specified by a constructor, the
1970199482Srdivacky          // initial standard conversion sequence converts the source type to the
1971199482Srdivacky          // type required by the argument of the constructor
1972199990Srdivacky          BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1973199990Srdivacky        }
1974218893Sdim      }
1975218893Sdim      // Watch out for elipsis conversion.
1976199482Srdivacky      if (!ICS.UserDefined.EllipsisConversion) {
1977221345Sdim        ExprResult Res =
1978221345Sdim          PerformImplicitConversion(From, BeforeToType,
1979221345Sdim                                    ICS.UserDefined.Before, AA_Converting,
1980221345Sdim                                    CStyle);
1981221345Sdim        if (Res.isInvalid())
1982221345Sdim          return ExprError();
1983221345Sdim        From = Res.take();
1984199482Srdivacky      }
1985218893Sdim
1986218893Sdim      ExprResult CastArg
1987207619Srdivacky        = BuildCXXCastArgument(*this,
1988207619Srdivacky                               From->getLocStart(),
1989198092Srdivacky                               ToType.getNonReferenceType(),
1990218893Sdim                               CastKind, cast<CXXMethodDecl>(FD),
1991218893Sdim                               ICS.UserDefined.FoundConversionFunction,
1992212904Sdim                               From);
1993198092Srdivacky
1994198092Srdivacky      if (CastArg.isInvalid())
1995221345Sdim        return ExprError();
1996199990Srdivacky
1997221345Sdim      From = CastArg.take();
1998199990Srdivacky
1999199990Srdivacky      return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2000218893Sdim                                       AA_Converting, CStyle);
2001198398Srdivacky  }
2002202379Srdivacky
2003202379Srdivacky  case ImplicitConversionSequence::AmbiguousConversion:
2004212904Sdim    ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
2005202379Srdivacky                          PDiag(diag::err_typecheck_ambiguous_condition)
2006202379Srdivacky                            << From->getSourceRange());
2007221345Sdim     return ExprError();
2008218893Sdim
2009193326Sed  case ImplicitConversionSequence::EllipsisConversion:
2010193326Sed    assert(false && "Cannot perform an ellipsis conversion");
2011221345Sdim    return Owned(From);
2012193326Sed
2013193326Sed  case ImplicitConversionSequence::BadConversion:
2014221345Sdim    return ExprError();
2015193326Sed  }
2016193326Sed
2017193326Sed  // Everything went well.
2018221345Sdim  return Owned(From);
2019193326Sed}
2020193326Sed
2021193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the
2022193326Sed/// expression From to the type ToType by following the standard
2023221345Sdim/// conversion sequence SCS. Returns the converted
2024193326Sed/// expression. Flavor is the context in which we're performing this
2025193326Sed/// conversion, for use in error messages.
2026221345SdimExprResult
2027221345SdimSema::PerformImplicitConversion(Expr *From, QualType ToType,
2028193326Sed                                const StandardConversionSequence& SCS,
2029218893Sdim                                AssignmentAction Action, bool CStyle) {
2030193326Sed  // Overall FIXME: we are recomputing too many types here and doing far too
2031193326Sed  // much extra work. What this means is that we need to keep track of more
2032193326Sed  // information that is computed when we try the implicit conversion initially,
2033193326Sed  // so that we don't need to recompute anything here.
2034193326Sed  QualType FromType = From->getType();
2035193326Sed
2036193326Sed  if (SCS.CopyConstructor) {
2037193326Sed    // FIXME: When can ToType be a reference type?
2038193326Sed    assert(!ToType->isReferenceType());
2039198092Srdivacky    if (SCS.Second == ICK_Derived_To_Base) {
2040212904Sdim      ASTOwningVector<Expr*> ConstructorArgs(*this);
2041198092Srdivacky      if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
2042212904Sdim                                  MultiExprArg(*this, &From, 1),
2043218893Sdim                                  /*FIXME:ConstructLoc*/SourceLocation(),
2044198092Srdivacky                                  ConstructorArgs))
2045221345Sdim        return ExprError();
2046221345Sdim      return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2047221345Sdim                                   ToType, SCS.CopyConstructor,
2048221345Sdim                                   move_arg(ConstructorArgs),
2049221345Sdim                                   /*ZeroInit*/ false,
2050221345Sdim                                   CXXConstructExpr::CK_Complete,
2051221345Sdim                                   SourceRange());
2052198092Srdivacky    }
2053221345Sdim    return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2054221345Sdim                                 ToType, SCS.CopyConstructor,
2055221345Sdim                                 MultiExprArg(*this, &From, 1),
2056221345Sdim                                 /*ZeroInit*/ false,
2057221345Sdim                                 CXXConstructExpr::CK_Complete,
2058221345Sdim                                 SourceRange());
2059193326Sed  }
2060193326Sed
2061207619Srdivacky  // Resolve overloaded function references.
2062207619Srdivacky  if (Context.hasSameType(FromType, Context.OverloadTy)) {
2063207619Srdivacky    DeclAccessPair Found;
2064207619Srdivacky    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2065207619Srdivacky                                                          true, Found);
2066207619Srdivacky    if (!Fn)
2067221345Sdim      return ExprError();
2068207619Srdivacky
2069207619Srdivacky    if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
2070221345Sdim      return ExprError();
2071207619Srdivacky
2072207619Srdivacky    From = FixOverloadedFunctionReference(From, Found, Fn);
2073207619Srdivacky    FromType = From->getType();
2074207619Srdivacky  }
2075207619Srdivacky
2076193326Sed  // Perform the first implicit conversion.
2077193326Sed  switch (SCS.First) {
2078193326Sed  case ICK_Identity:
2079193326Sed    // Nothing to do.
2080193326Sed    break;
2081193326Sed
2082218893Sdim  case ICK_Lvalue_To_Rvalue:
2083218893Sdim    // Should this get its own ICK?
2084218893Sdim    if (From->getObjectKind() == OK_ObjCProperty) {
2085221345Sdim      ExprResult FromRes = ConvertPropertyForRValue(From);
2086221345Sdim      if (FromRes.isInvalid())
2087221345Sdim        return ExprError();
2088221345Sdim      From = FromRes.take();
2089218893Sdim      if (!From->isGLValue()) break;
2090218893Sdim    }
2091218893Sdim
2092218893Sdim    // Check for trivial buffer overflows.
2093221345Sdim    CheckArrayAccess(From);
2094218893Sdim
2095218893Sdim    FromType = FromType.getUnqualifiedType();
2096218893Sdim    From = ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
2097218893Sdim                                    From, 0, VK_RValue);
2098218893Sdim    break;
2099218893Sdim
2100193326Sed  case ICK_Array_To_Pointer:
2101193326Sed    FromType = Context.getArrayDecayedType(FromType);
2102221345Sdim    From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay).take();
2103193326Sed    break;
2104193326Sed
2105193326Sed  case ICK_Function_To_Pointer:
2106193326Sed    FromType = Context.getPointerType(FromType);
2107221345Sdim    From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay).take();
2108193326Sed    break;
2109193326Sed
2110193326Sed  default:
2111193326Sed    assert(false && "Improper first standard conversion");
2112193326Sed    break;
2113193326Sed  }
2114193326Sed
2115193326Sed  // Perform the second implicit conversion
2116193326Sed  switch (SCS.Second) {
2117193326Sed  case ICK_Identity:
2118198092Srdivacky    // If both sides are functions (or pointers/references to them), there could
2119198092Srdivacky    // be incompatible exception declarations.
2120198092Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
2121221345Sdim      return ExprError();
2122198092Srdivacky    // Nothing else to do.
2123193326Sed    break;
2124193326Sed
2125200583Srdivacky  case ICK_NoReturn_Adjustment:
2126200583Srdivacky    // If both sides are functions (or pointers/references to them), there could
2127200583Srdivacky    // be incompatible exception declarations.
2128200583Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
2129221345Sdim      return ExprError();
2130218893Sdim
2131221345Sdim    From = ImpCastExprToType(From, ToType, CK_NoOp).take();
2132200583Srdivacky    break;
2133218893Sdim
2134193326Sed  case ICK_Integral_Promotion:
2135198398Srdivacky  case ICK_Integral_Conversion:
2136221345Sdim    From = ImpCastExprToType(From, ToType, CK_IntegralCast).take();
2137198398Srdivacky    break;
2138198398Srdivacky
2139193326Sed  case ICK_Floating_Promotion:
2140198398Srdivacky  case ICK_Floating_Conversion:
2141221345Sdim    From = ImpCastExprToType(From, ToType, CK_FloatingCast).take();
2142198398Srdivacky    break;
2143198398Srdivacky
2144193326Sed  case ICK_Complex_Promotion:
2145218893Sdim  case ICK_Complex_Conversion: {
2146218893Sdim    QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2147218893Sdim    QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2148218893Sdim    CastKind CK;
2149218893Sdim    if (FromEl->isRealFloatingType()) {
2150218893Sdim      if (ToEl->isRealFloatingType())
2151218893Sdim        CK = CK_FloatingComplexCast;
2152218893Sdim      else
2153218893Sdim        CK = CK_FloatingComplexToIntegralComplex;
2154218893Sdim    } else if (ToEl->isRealFloatingType()) {
2155218893Sdim      CK = CK_IntegralComplexToFloatingComplex;
2156218893Sdim    } else {
2157218893Sdim      CK = CK_IntegralComplexCast;
2158218893Sdim    }
2159221345Sdim    From = ImpCastExprToType(From, ToType, CK).take();
2160198398Srdivacky    break;
2161218893Sdim  }
2162198398Srdivacky
2163193326Sed  case ICK_Floating_Integral:
2164210299Sed    if (ToType->isRealFloatingType())
2165221345Sdim      From = ImpCastExprToType(From, ToType, CK_IntegralToFloating).take();
2166198398Srdivacky    else
2167221345Sdim      From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral).take();
2168198398Srdivacky    break;
2169198398Srdivacky
2170193326Sed  case ICK_Compatible_Conversion:
2171221345Sdim    From = ImpCastExprToType(From, ToType, CK_NoOp).take();
2172193326Sed    break;
2173193326Sed
2174198092Srdivacky  case ICK_Pointer_Conversion: {
2175218893Sdim    if (SCS.IncompatibleObjC && Action != AA_Casting) {
2176193326Sed      // Diagnose incompatible Objective-C conversions
2177221345Sdim      if (Action == AA_Initializing)
2178221345Sdim        Diag(From->getSourceRange().getBegin(),
2179221345Sdim             diag::ext_typecheck_convert_incompatible_pointer)
2180221345Sdim          << ToType << From->getType() << Action
2181221345Sdim          << From->getSourceRange();
2182221345Sdim      else
2183221345Sdim        Diag(From->getSourceRange().getBegin(),
2184221345Sdim             diag::ext_typecheck_convert_incompatible_pointer)
2185221345Sdim          << From->getType() << ToType << Action
2186221345Sdim          << From->getSourceRange();
2187193326Sed    }
2188193326Sed
2189218893Sdim    CastKind Kind = CK_Invalid;
2190212904Sdim    CXXCastPath BasePath;
2191218893Sdim    if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
2192221345Sdim      return ExprError();
2193221345Sdim    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
2194193326Sed    break;
2195198092Srdivacky  }
2196218893Sdim
2197198092Srdivacky  case ICK_Pointer_Member: {
2198218893Sdim    CastKind Kind = CK_Invalid;
2199212904Sdim    CXXCastPath BasePath;
2200218893Sdim    if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
2201221345Sdim      return ExprError();
2202198092Srdivacky    if (CheckExceptionSpecCompatibility(From, ToType))
2203221345Sdim      return ExprError();
2204221345Sdim    From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath).take();
2205193326Sed    break;
2206198092Srdivacky  }
2207218893Sdim
2208221345Sdim  case ICK_Boolean_Conversion:
2209221345Sdim    From = ImpCastExprToType(From, Context.BoolTy,
2210221345Sdim                             ScalarTypeToBooleanCastKind(FromType)).take();
2211193326Sed    break;
2212193326Sed
2213208600Srdivacky  case ICK_Derived_To_Base: {
2214212904Sdim    CXXCastPath BasePath;
2215218893Sdim    if (CheckDerivedToBaseConversion(From->getType(),
2216199482Srdivacky                                     ToType.getNonReferenceType(),
2217199482Srdivacky                                     From->getLocStart(),
2218218893Sdim                                     From->getSourceRange(),
2219208600Srdivacky                                     &BasePath,
2220218893Sdim                                     CStyle))
2221221345Sdim      return ExprError();
2222208600Srdivacky
2223221345Sdim    From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2224212904Sdim                      CK_DerivedToBase, CastCategory(From),
2225221345Sdim                      &BasePath).take();
2226199482Srdivacky    break;
2227208600Srdivacky  }
2228208600Srdivacky
2229208600Srdivacky  case ICK_Vector_Conversion:
2230221345Sdim    From = ImpCastExprToType(From, ToType, CK_BitCast).take();
2231208600Srdivacky    break;
2232208600Srdivacky
2233208600Srdivacky  case ICK_Vector_Splat:
2234221345Sdim    From = ImpCastExprToType(From, ToType, CK_VectorSplat).take();
2235208600Srdivacky    break;
2236218893Sdim
2237208600Srdivacky  case ICK_Complex_Real:
2238218893Sdim    // Case 1.  x -> _Complex y
2239218893Sdim    if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2240218893Sdim      QualType ElType = ToComplex->getElementType();
2241218893Sdim      bool isFloatingComplex = ElType->isRealFloatingType();
2242218893Sdim
2243218893Sdim      // x -> y
2244218893Sdim      if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2245218893Sdim        // do nothing
2246218893Sdim      } else if (From->getType()->isRealFloatingType()) {
2247221345Sdim        From = ImpCastExprToType(From, ElType,
2248221345Sdim                isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
2249218893Sdim      } else {
2250218893Sdim        assert(From->getType()->isIntegerType());
2251221345Sdim        From = ImpCastExprToType(From, ElType,
2252221345Sdim                isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
2253218893Sdim      }
2254218893Sdim      // y -> _Complex y
2255221345Sdim      From = ImpCastExprToType(From, ToType,
2256218893Sdim                   isFloatingComplex ? CK_FloatingRealToComplex
2257221345Sdim                                     : CK_IntegralRealToComplex).take();
2258218893Sdim
2259218893Sdim    // Case 2.  _Complex x -> y
2260218893Sdim    } else {
2261218893Sdim      const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2262218893Sdim      assert(FromComplex);
2263218893Sdim
2264218893Sdim      QualType ElType = FromComplex->getElementType();
2265218893Sdim      bool isFloatingComplex = ElType->isRealFloatingType();
2266218893Sdim
2267218893Sdim      // _Complex x -> x
2268221345Sdim      From = ImpCastExprToType(From, ElType,
2269218893Sdim                   isFloatingComplex ? CK_FloatingComplexToReal
2270221345Sdim                                     : CK_IntegralComplexToReal).take();
2271218893Sdim
2272218893Sdim      // x -> y
2273218893Sdim      if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2274218893Sdim        // do nothing
2275218893Sdim      } else if (ToType->isRealFloatingType()) {
2276221345Sdim        From = ImpCastExprToType(From, ToType,
2277221345Sdim                isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating).take();
2278218893Sdim      } else {
2279218893Sdim        assert(ToType->isIntegerType());
2280221345Sdim        From = ImpCastExprToType(From, ToType,
2281221345Sdim                isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast).take();
2282218893Sdim      }
2283218893Sdim    }
2284208600Srdivacky    break;
2285218893Sdim
2286218893Sdim  case ICK_Block_Pointer_Conversion: {
2287221345Sdim      From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2288221345Sdim                               VK_RValue).take();
2289218893Sdim      break;
2290218893Sdim    }
2291208600Srdivacky
2292221345Sdim  case ICK_TransparentUnionConversion: {
2293221345Sdim    ExprResult FromRes = Owned(From);
2294221345Sdim    Sema::AssignConvertType ConvTy =
2295221345Sdim      CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2296221345Sdim    if (FromRes.isInvalid())
2297221345Sdim      return ExprError();
2298221345Sdim    From = FromRes.take();
2299221345Sdim    assert ((ConvTy == Sema::Compatible) &&
2300221345Sdim            "Improper transparent union conversion");
2301221345Sdim    (void)ConvTy;
2302221345Sdim    break;
2303221345Sdim  }
2304221345Sdim
2305208600Srdivacky  case ICK_Lvalue_To_Rvalue:
2306208600Srdivacky  case ICK_Array_To_Pointer:
2307208600Srdivacky  case ICK_Function_To_Pointer:
2308208600Srdivacky  case ICK_Qualification:
2309208600Srdivacky  case ICK_Num_Conversion_Kinds:
2310193326Sed    assert(false && "Improper second standard conversion");
2311193326Sed    break;
2312193326Sed  }
2313193326Sed
2314193326Sed  switch (SCS.Third) {
2315193326Sed  case ICK_Identity:
2316193326Sed    // Nothing to do.
2317193326Sed    break;
2318193326Sed
2319212904Sdim  case ICK_Qualification: {
2320212904Sdim    // The qualification keeps the category of the inner expression, unless the
2321212904Sdim    // target type isn't a reference.
2322212904Sdim    ExprValueKind VK = ToType->isReferenceType() ?
2323212904Sdim                                  CastCategory(From) : VK_RValue;
2324221345Sdim    From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2325221345Sdim                             CK_NoOp, VK).take();
2326204643Srdivacky
2327221345Sdim    if (SCS.DeprecatedStringLiteralToCharPtr &&
2328221345Sdim        !getLangOptions().WritableStrings)
2329204643Srdivacky      Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2330204643Srdivacky        << ToType.getNonReferenceType();
2331204643Srdivacky
2332193326Sed    break;
2333212904Sdim    }
2334212904Sdim
2335193326Sed  default:
2336208600Srdivacky    assert(false && "Improper third standard conversion");
2337193326Sed    break;
2338193326Sed  }
2339193326Sed
2340221345Sdim  return Owned(From);
2341193326Sed}
2342193326Sed
2343218893SdimExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
2344218893Sdim                                     SourceLocation KWLoc,
2345218893Sdim                                     ParsedType Ty,
2346218893Sdim                                     SourceLocation RParen) {
2347218893Sdim  TypeSourceInfo *TSInfo;
2348218893Sdim  QualType T = GetTypeFromParser(Ty, &TSInfo);
2349193326Sed
2350218893Sdim  if (!TSInfo)
2351218893Sdim    TSInfo = Context.getTrivialTypeSourceInfo(T);
2352218893Sdim  return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
2353218893Sdim}
2354218893Sdim
2355221345Sdim/// \brief Check the completeness of a type in a unary type trait.
2356221345Sdim///
2357221345Sdim/// If the particular type trait requires a complete type, tries to complete
2358221345Sdim/// it. If completing the type fails, a diagnostic is emitted and false
2359221345Sdim/// returned. If completing the type succeeds or no completion was required,
2360221345Sdim/// returns true.
2361221345Sdimstatic bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2362221345Sdim                                                UnaryTypeTrait UTT,
2363221345Sdim                                                SourceLocation Loc,
2364221345Sdim                                                QualType ArgTy) {
2365221345Sdim  // C++0x [meta.unary.prop]p3:
2366221345Sdim  //   For all of the class templates X declared in this Clause, instantiating
2367221345Sdim  //   that template with a template argument that is a class template
2368221345Sdim  //   specialization may result in the implicit instantiation of the template
2369221345Sdim  //   argument if and only if the semantics of X require that the argument
2370221345Sdim  //   must be a complete type.
2371221345Sdim  // We apply this rule to all the type trait expressions used to implement
2372221345Sdim  // these class templates. We also try to follow any GCC documented behavior
2373221345Sdim  // in these expressions to ensure portability of standard libraries.
2374221345Sdim  switch (UTT) {
2375221345Sdim    // is_complete_type somewhat obviously cannot require a complete type.
2376221345Sdim  case UTT_IsCompleteType:
2377221345Sdim    // Fall-through
2378221345Sdim
2379221345Sdim    // These traits are modeled on the type predicates in C++0x
2380221345Sdim    // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2381221345Sdim    // requiring a complete type, as whether or not they return true cannot be
2382221345Sdim    // impacted by the completeness of the type.
2383221345Sdim  case UTT_IsVoid:
2384221345Sdim  case UTT_IsIntegral:
2385221345Sdim  case UTT_IsFloatingPoint:
2386221345Sdim  case UTT_IsArray:
2387221345Sdim  case UTT_IsPointer:
2388221345Sdim  case UTT_IsLvalueReference:
2389221345Sdim  case UTT_IsRvalueReference:
2390221345Sdim  case UTT_IsMemberFunctionPointer:
2391221345Sdim  case UTT_IsMemberObjectPointer:
2392221345Sdim  case UTT_IsEnum:
2393221345Sdim  case UTT_IsUnion:
2394221345Sdim  case UTT_IsClass:
2395221345Sdim  case UTT_IsFunction:
2396221345Sdim  case UTT_IsReference:
2397221345Sdim  case UTT_IsArithmetic:
2398221345Sdim  case UTT_IsFundamental:
2399221345Sdim  case UTT_IsObject:
2400221345Sdim  case UTT_IsScalar:
2401221345Sdim  case UTT_IsCompound:
2402221345Sdim  case UTT_IsMemberPointer:
2403221345Sdim    // Fall-through
2404221345Sdim
2405221345Sdim    // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2406221345Sdim    // which requires some of its traits to have the complete type. However,
2407221345Sdim    // the completeness of the type cannot impact these traits' semantics, and
2408221345Sdim    // so they don't require it. This matches the comments on these traits in
2409221345Sdim    // Table 49.
2410221345Sdim  case UTT_IsConst:
2411221345Sdim  case UTT_IsVolatile:
2412221345Sdim  case UTT_IsSigned:
2413221345Sdim  case UTT_IsUnsigned:
2414221345Sdim    return true;
2415221345Sdim
2416221345Sdim    // C++0x [meta.unary.prop] Table 49 requires the following traits to be
2417221345Sdim    // applied to a complete type.
2418221345Sdim  case UTT_IsTrivial:
2419221345Sdim  case UTT_IsStandardLayout:
2420221345Sdim  case UTT_IsPOD:
2421221345Sdim  case UTT_IsLiteral:
2422221345Sdim  case UTT_IsEmpty:
2423221345Sdim  case UTT_IsPolymorphic:
2424221345Sdim  case UTT_IsAbstract:
2425221345Sdim    // Fall-through
2426221345Sdim
2427221345Sdim    // These trait expressions are designed to help implement predicates in
2428221345Sdim    // [meta.unary.prop] despite not being named the same. They are specified
2429221345Sdim    // by both GCC and the Embarcadero C++ compiler, and require the complete
2430221345Sdim    // type due to the overarching C++0x type predicates being implemented
2431221345Sdim    // requiring the complete type.
2432221345Sdim  case UTT_HasNothrowAssign:
2433221345Sdim  case UTT_HasNothrowConstructor:
2434221345Sdim  case UTT_HasNothrowCopy:
2435221345Sdim  case UTT_HasTrivialAssign:
2436221345Sdim  case UTT_HasTrivialConstructor:
2437221345Sdim  case UTT_HasTrivialCopy:
2438221345Sdim  case UTT_HasTrivialDestructor:
2439221345Sdim  case UTT_HasVirtualDestructor:
2440221345Sdim    // Arrays of unknown bound are expressly allowed.
2441221345Sdim    QualType ElTy = ArgTy;
2442221345Sdim    if (ArgTy->isIncompleteArrayType())
2443221345Sdim      ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2444221345Sdim
2445221345Sdim    // The void type is expressly allowed.
2446221345Sdim    if (ElTy->isVoidType())
2447221345Sdim      return true;
2448221345Sdim
2449221345Sdim    return !S.RequireCompleteType(
2450221345Sdim      Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
2451221345Sdim  }
2452221345Sdim  llvm_unreachable("Type trait not handled by switch");
2453221345Sdim}
2454221345Sdim
2455221345Sdimstatic bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2456221345Sdim                                   SourceLocation KeyLoc, QualType T) {
2457221345Sdim  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
2458221345Sdim
2459218893Sdim  ASTContext &C = Self.Context;
2460218893Sdim  switch(UTT) {
2461221345Sdim    // Type trait expressions corresponding to the primary type category
2462221345Sdim    // predicates in C++0x [meta.unary.cat].
2463221345Sdim  case UTT_IsVoid:
2464221345Sdim    return T->isVoidType();
2465221345Sdim  case UTT_IsIntegral:
2466221345Sdim    return T->isIntegralType(C);
2467221345Sdim  case UTT_IsFloatingPoint:
2468221345Sdim    return T->isFloatingType();
2469221345Sdim  case UTT_IsArray:
2470221345Sdim    return T->isArrayType();
2471221345Sdim  case UTT_IsPointer:
2472221345Sdim    return T->isPointerType();
2473221345Sdim  case UTT_IsLvalueReference:
2474221345Sdim    return T->isLValueReferenceType();
2475221345Sdim  case UTT_IsRvalueReference:
2476221345Sdim    return T->isRValueReferenceType();
2477221345Sdim  case UTT_IsMemberFunctionPointer:
2478221345Sdim    return T->isMemberFunctionPointerType();
2479221345Sdim  case UTT_IsMemberObjectPointer:
2480221345Sdim    return T->isMemberDataPointerType();
2481221345Sdim  case UTT_IsEnum:
2482221345Sdim    return T->isEnumeralType();
2483218893Sdim  case UTT_IsUnion:
2484221345Sdim    return T->isUnionType();
2485221345Sdim  case UTT_IsClass:
2486221345Sdim    return T->isClassType() || T->isStructureType();
2487221345Sdim  case UTT_IsFunction:
2488221345Sdim    return T->isFunctionType();
2489221345Sdim
2490221345Sdim    // Type trait expressions which correspond to the convenient composition
2491221345Sdim    // predicates in C++0x [meta.unary.comp].
2492221345Sdim  case UTT_IsReference:
2493221345Sdim    return T->isReferenceType();
2494221345Sdim  case UTT_IsArithmetic:
2495221345Sdim    return T->isArithmeticType() && !T->isEnumeralType();
2496221345Sdim  case UTT_IsFundamental:
2497221345Sdim    return T->isFundamentalType();
2498221345Sdim  case UTT_IsObject:
2499221345Sdim    return T->isObjectType();
2500221345Sdim  case UTT_IsScalar:
2501221345Sdim    return T->isScalarType();
2502221345Sdim  case UTT_IsCompound:
2503221345Sdim    return T->isCompoundType();
2504221345Sdim  case UTT_IsMemberPointer:
2505221345Sdim    return T->isMemberPointerType();
2506221345Sdim
2507221345Sdim    // Type trait expressions which correspond to the type property predicates
2508221345Sdim    // in C++0x [meta.unary.prop].
2509221345Sdim  case UTT_IsConst:
2510221345Sdim    return T.isConstQualified();
2511221345Sdim  case UTT_IsVolatile:
2512221345Sdim    return T.isVolatileQualified();
2513221345Sdim  case UTT_IsTrivial:
2514221345Sdim    return T->isTrivialType();
2515221345Sdim  case UTT_IsStandardLayout:
2516221345Sdim    return T->isStandardLayoutType();
2517221345Sdim  case UTT_IsPOD:
2518221345Sdim    return T->isPODType();
2519221345Sdim  case UTT_IsLiteral:
2520221345Sdim    return T->isLiteralType();
2521221345Sdim  case UTT_IsEmpty:
2522221345Sdim    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2523221345Sdim      return !RD->isUnion() && RD->isEmpty();
2524218893Sdim    return false;
2525218893Sdim  case UTT_IsPolymorphic:
2526221345Sdim    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2527221345Sdim      return RD->isPolymorphic();
2528218893Sdim    return false;
2529218893Sdim  case UTT_IsAbstract:
2530221345Sdim    if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2531221345Sdim      return RD->isAbstract();
2532218893Sdim    return false;
2533221345Sdim  case UTT_IsSigned:
2534221345Sdim    return T->isSignedIntegerType();
2535221345Sdim  case UTT_IsUnsigned:
2536221345Sdim    return T->isUnsignedIntegerType();
2537221345Sdim
2538221345Sdim    // Type trait expressions which query classes regarding their construction,
2539221345Sdim    // destruction, and copying. Rather than being based directly on the
2540221345Sdim    // related type predicates in the standard, they are specified by both
2541221345Sdim    // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
2542221345Sdim    // specifications.
2543221345Sdim    //
2544221345Sdim    //   1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
2545221345Sdim    //   2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2546218893Sdim  case UTT_HasTrivialConstructor:
2547218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2548218893Sdim    //   If __is_pod (type) is true then the trait is true, else if type is
2549218893Sdim    //   a cv class or union type (or array thereof) with a trivial default
2550218893Sdim    //   constructor ([class.ctor]) then the trait is true, else it is false.
2551218893Sdim    if (T->isPODType())
2552218893Sdim      return true;
2553218893Sdim    if (const RecordType *RT =
2554218893Sdim          C.getBaseElementType(T)->getAs<RecordType>())
2555218893Sdim      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor();
2556218893Sdim    return false;
2557218893Sdim  case UTT_HasTrivialCopy:
2558218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2559218893Sdim    //   If __is_pod (type) is true or type is a reference type then
2560218893Sdim    //   the trait is true, else if type is a cv class or union type
2561218893Sdim    //   with a trivial copy constructor ([class.copy]) then the trait
2562218893Sdim    //   is true, else it is false.
2563218893Sdim    if (T->isPODType() || T->isReferenceType())
2564218893Sdim      return true;
2565218893Sdim    if (const RecordType *RT = T->getAs<RecordType>())
2566218893Sdim      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
2567218893Sdim    return false;
2568218893Sdim  case UTT_HasTrivialAssign:
2569218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2570218893Sdim    //   If type is const qualified or is a reference type then the
2571218893Sdim    //   trait is false. Otherwise if __is_pod (type) is true then the
2572218893Sdim    //   trait is true, else if type is a cv class or union type with
2573218893Sdim    //   a trivial copy assignment ([class.copy]) then the trait is
2574218893Sdim    //   true, else it is false.
2575218893Sdim    // Note: the const and reference restrictions are interesting,
2576218893Sdim    // given that const and reference members don't prevent a class
2577218893Sdim    // from having a trivial copy assignment operator (but do cause
2578218893Sdim    // errors if the copy assignment operator is actually used, q.v.
2579218893Sdim    // [class.copy]p12).
2580218893Sdim
2581218893Sdim    if (C.getBaseElementType(T).isConstQualified())
2582218893Sdim      return false;
2583218893Sdim    if (T->isPODType())
2584218893Sdim      return true;
2585218893Sdim    if (const RecordType *RT = T->getAs<RecordType>())
2586218893Sdim      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
2587218893Sdim    return false;
2588218893Sdim  case UTT_HasTrivialDestructor:
2589218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2590218893Sdim    //   If __is_pod (type) is true or type is a reference type
2591218893Sdim    //   then the trait is true, else if type is a cv class or union
2592218893Sdim    //   type (or array thereof) with a trivial destructor
2593218893Sdim    //   ([class.dtor]) then the trait is true, else it is
2594218893Sdim    //   false.
2595218893Sdim    if (T->isPODType() || T->isReferenceType())
2596218893Sdim      return true;
2597218893Sdim    if (const RecordType *RT =
2598218893Sdim          C.getBaseElementType(T)->getAs<RecordType>())
2599218893Sdim      return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
2600218893Sdim    return false;
2601218893Sdim  // TODO: Propagate nothrowness for implicitly declared special members.
2602218893Sdim  case UTT_HasNothrowAssign:
2603218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2604218893Sdim    //   If type is const qualified or is a reference type then the
2605218893Sdim    //   trait is false. Otherwise if __has_trivial_assign (type)
2606218893Sdim    //   is true then the trait is true, else if type is a cv class
2607218893Sdim    //   or union type with copy assignment operators that are known
2608218893Sdim    //   not to throw an exception then the trait is true, else it is
2609218893Sdim    //   false.
2610218893Sdim    if (C.getBaseElementType(T).isConstQualified())
2611218893Sdim      return false;
2612218893Sdim    if (T->isReferenceType())
2613218893Sdim      return false;
2614218893Sdim    if (T->isPODType())
2615218893Sdim      return true;
2616218893Sdim    if (const RecordType *RT = T->getAs<RecordType>()) {
2617218893Sdim      CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
2618218893Sdim      if (RD->hasTrivialCopyAssignment())
2619218893Sdim        return true;
2620218893Sdim
2621218893Sdim      bool FoundAssign = false;
2622218893Sdim      bool AllNoThrow = true;
2623218893Sdim      DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
2624218893Sdim      LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
2625218893Sdim                       Sema::LookupOrdinaryName);
2626218893Sdim      if (Self.LookupQualifiedName(Res, RD)) {
2627218893Sdim        for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
2628218893Sdim             Op != OpEnd; ++Op) {
2629218893Sdim          CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
2630218893Sdim          if (Operator->isCopyAssignmentOperator()) {
2631218893Sdim            FoundAssign = true;
2632218893Sdim            const FunctionProtoType *CPT
2633218893Sdim                = Operator->getType()->getAs<FunctionProtoType>();
2634221345Sdim            if (!CPT->isNothrow(Self.Context)) {
2635218893Sdim              AllNoThrow = false;
2636218893Sdim              break;
2637218893Sdim            }
2638218893Sdim          }
2639218893Sdim        }
2640218893Sdim      }
2641218893Sdim
2642218893Sdim      return FoundAssign && AllNoThrow;
2643218893Sdim    }
2644218893Sdim    return false;
2645218893Sdim  case UTT_HasNothrowCopy:
2646218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2647218893Sdim    //   If __has_trivial_copy (type) is true then the trait is true, else
2648218893Sdim    //   if type is a cv class or union type with copy constructors that are
2649218893Sdim    //   known not to throw an exception then the trait is true, else it is
2650218893Sdim    //   false.
2651218893Sdim    if (T->isPODType() || T->isReferenceType())
2652218893Sdim      return true;
2653218893Sdim    if (const RecordType *RT = T->getAs<RecordType>()) {
2654218893Sdim      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2655218893Sdim      if (RD->hasTrivialCopyConstructor())
2656218893Sdim        return true;
2657218893Sdim
2658218893Sdim      bool FoundConstructor = false;
2659218893Sdim      bool AllNoThrow = true;
2660218893Sdim      unsigned FoundTQs;
2661218893Sdim      DeclContext::lookup_const_iterator Con, ConEnd;
2662218893Sdim      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2663218893Sdim           Con != ConEnd; ++Con) {
2664218893Sdim        // A template constructor is never a copy constructor.
2665218893Sdim        // FIXME: However, it may actually be selected at the actual overload
2666218893Sdim        // resolution point.
2667218893Sdim        if (isa<FunctionTemplateDecl>(*Con))
2668218893Sdim          continue;
2669218893Sdim        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2670218893Sdim        if (Constructor->isCopyConstructor(FoundTQs)) {
2671218893Sdim          FoundConstructor = true;
2672218893Sdim          const FunctionProtoType *CPT
2673218893Sdim              = Constructor->getType()->getAs<FunctionProtoType>();
2674221345Sdim          // FIXME: check whether evaluating default arguments can throw.
2675218893Sdim          // For now, we'll be conservative and assume that they can throw.
2676221345Sdim          if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) {
2677218893Sdim            AllNoThrow = false;
2678218893Sdim            break;
2679218893Sdim          }
2680218893Sdim        }
2681218893Sdim      }
2682218893Sdim
2683218893Sdim      return FoundConstructor && AllNoThrow;
2684218893Sdim    }
2685218893Sdim    return false;
2686218893Sdim  case UTT_HasNothrowConstructor:
2687218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2688218893Sdim    //   If __has_trivial_constructor (type) is true then the trait is
2689218893Sdim    //   true, else if type is a cv class or union type (or array
2690218893Sdim    //   thereof) with a default constructor that is known not to
2691218893Sdim    //   throw an exception then the trait is true, else it is false.
2692218893Sdim    if (T->isPODType())
2693218893Sdim      return true;
2694218893Sdim    if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
2695218893Sdim      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2696218893Sdim      if (RD->hasTrivialConstructor())
2697218893Sdim        return true;
2698218893Sdim
2699218893Sdim      DeclContext::lookup_const_iterator Con, ConEnd;
2700218893Sdim      for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
2701218893Sdim           Con != ConEnd; ++Con) {
2702218893Sdim        // FIXME: In C++0x, a constructor template can be a default constructor.
2703218893Sdim        if (isa<FunctionTemplateDecl>(*Con))
2704218893Sdim          continue;
2705218893Sdim        CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2706218893Sdim        if (Constructor->isDefaultConstructor()) {
2707218893Sdim          const FunctionProtoType *CPT
2708218893Sdim              = Constructor->getType()->getAs<FunctionProtoType>();
2709218893Sdim          // TODO: check whether evaluating default arguments can throw.
2710218893Sdim          // For now, we'll be conservative and assume that they can throw.
2711221345Sdim          return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
2712218893Sdim        }
2713218893Sdim      }
2714218893Sdim    }
2715218893Sdim    return false;
2716218893Sdim  case UTT_HasVirtualDestructor:
2717218893Sdim    // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
2718218893Sdim    //   If type is a class type with a virtual destructor ([class.dtor])
2719218893Sdim    //   then the trait is true, else it is false.
2720218893Sdim    if (const RecordType *Record = T->getAs<RecordType>()) {
2721218893Sdim      CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2722218893Sdim      if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
2723218893Sdim        return Destructor->isVirtual();
2724218893Sdim    }
2725218893Sdim    return false;
2726221345Sdim
2727221345Sdim    // These type trait expressions are modeled on the specifications for the
2728221345Sdim    // Embarcadero C++0x type trait functions:
2729221345Sdim    //   http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
2730221345Sdim  case UTT_IsCompleteType:
2731221345Sdim    // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
2732221345Sdim    //   Returns True if and only if T is a complete type at the point of the
2733221345Sdim    //   function call.
2734221345Sdim    return !T->isIncompleteType();
2735218893Sdim  }
2736221345Sdim  llvm_unreachable("Type trait not covered by switch");
2737218893Sdim}
2738218893Sdim
2739218893SdimExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
2740218893Sdim                                     SourceLocation KWLoc,
2741218893Sdim                                     TypeSourceInfo *TSInfo,
2742218893Sdim                                     SourceLocation RParen) {
2743218893Sdim  QualType T = TSInfo->getType();
2744221345Sdim  if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
2745221345Sdim    return ExprError();
2746218893Sdim
2747218893Sdim  bool Value = false;
2748218893Sdim  if (!T->isDependentType())
2749221345Sdim    Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
2750218893Sdim
2751218893Sdim  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
2752198092Srdivacky                                                RParen, Context.BoolTy));
2753193326Sed}
2754193326Sed
2755218893SdimExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
2756218893Sdim                                      SourceLocation KWLoc,
2757218893Sdim                                      ParsedType LhsTy,
2758218893Sdim                                      ParsedType RhsTy,
2759218893Sdim                                      SourceLocation RParen) {
2760218893Sdim  TypeSourceInfo *LhsTSInfo;
2761218893Sdim  QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
2762218893Sdim  if (!LhsTSInfo)
2763218893Sdim    LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
2764218893Sdim
2765218893Sdim  TypeSourceInfo *RhsTSInfo;
2766218893Sdim  QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
2767218893Sdim  if (!RhsTSInfo)
2768218893Sdim    RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
2769218893Sdim
2770218893Sdim  return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
2771218893Sdim}
2772218893Sdim
2773218893Sdimstatic bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
2774218893Sdim                                    QualType LhsT, QualType RhsT,
2775218893Sdim                                    SourceLocation KeyLoc) {
2776221345Sdim  assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
2777221345Sdim         "Cannot evaluate traits of dependent types");
2778218893Sdim
2779218893Sdim  switch(BTT) {
2780218893Sdim  case BTT_IsBaseOf: {
2781218893Sdim    // C++0x [meta.rel]p2
2782218893Sdim    // Base is a base class of Derived without regard to cv-qualifiers or
2783218893Sdim    // Base and Derived are not unions and name the same class type without
2784218893Sdim    // regard to cv-qualifiers.
2785218893Sdim
2786218893Sdim    const RecordType *lhsRecord = LhsT->getAs<RecordType>();
2787218893Sdim    if (!lhsRecord) return false;
2788218893Sdim
2789218893Sdim    const RecordType *rhsRecord = RhsT->getAs<RecordType>();
2790218893Sdim    if (!rhsRecord) return false;
2791218893Sdim
2792218893Sdim    assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
2793218893Sdim             == (lhsRecord == rhsRecord));
2794218893Sdim
2795218893Sdim    if (lhsRecord == rhsRecord)
2796218893Sdim      return !lhsRecord->getDecl()->isUnion();
2797218893Sdim
2798218893Sdim    // C++0x [meta.rel]p2:
2799218893Sdim    //   If Base and Derived are class types and are different types
2800218893Sdim    //   (ignoring possible cv-qualifiers) then Derived shall be a
2801218893Sdim    //   complete type.
2802218893Sdim    if (Self.RequireCompleteType(KeyLoc, RhsT,
2803218893Sdim                          diag::err_incomplete_type_used_in_type_trait_expr))
2804218893Sdim      return false;
2805218893Sdim
2806218893Sdim    return cast<CXXRecordDecl>(rhsRecord->getDecl())
2807218893Sdim      ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
2808218893Sdim  }
2809221345Sdim  case BTT_IsSame:
2810221345Sdim    return Self.Context.hasSameType(LhsT, RhsT);
2811218893Sdim  case BTT_TypeCompatible:
2812218893Sdim    return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
2813218893Sdim                                           RhsT.getUnqualifiedType());
2814221345Sdim  case BTT_IsConvertible:
2815218893Sdim  case BTT_IsConvertibleTo: {
2816218893Sdim    // C++0x [meta.rel]p4:
2817218893Sdim    //   Given the following function prototype:
2818218893Sdim    //
2819218893Sdim    //     template <class T>
2820218893Sdim    //       typename add_rvalue_reference<T>::type create();
2821218893Sdim    //
2822218893Sdim    //   the predicate condition for a template specialization
2823218893Sdim    //   is_convertible<From, To> shall be satisfied if and only if
2824218893Sdim    //   the return expression in the following code would be
2825218893Sdim    //   well-formed, including any implicit conversions to the return
2826218893Sdim    //   type of the function:
2827218893Sdim    //
2828218893Sdim    //     To test() {
2829218893Sdim    //       return create<From>();
2830218893Sdim    //     }
2831218893Sdim    //
2832218893Sdim    //   Access checking is performed as if in a context unrelated to To and
2833218893Sdim    //   From. Only the validity of the immediate context of the expression
2834218893Sdim    //   of the return-statement (including conversions to the return type)
2835218893Sdim    //   is considered.
2836218893Sdim    //
2837218893Sdim    // We model the initialization as a copy-initialization of a temporary
2838218893Sdim    // of the appropriate type, which for this expression is identical to the
2839218893Sdim    // return statement (since NRVO doesn't apply).
2840218893Sdim    if (LhsT->isObjectType() || LhsT->isFunctionType())
2841218893Sdim      LhsT = Self.Context.getRValueReferenceType(LhsT);
2842218893Sdim
2843218893Sdim    InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
2844218893Sdim    OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
2845218893Sdim                         Expr::getValueKindForType(LhsT));
2846218893Sdim    Expr *FromPtr = &From;
2847218893Sdim    InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
2848218893Sdim                                                           SourceLocation()));
2849218893Sdim
2850218893Sdim    // Perform the initialization within a SFINAE trap at translation unit
2851218893Sdim    // scope.
2852218893Sdim    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
2853218893Sdim    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
2854218893Sdim    InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
2855218893Sdim    if (Init.getKind() == InitializationSequence::FailedSequence)
2856218893Sdim      return false;
2857218893Sdim
2858218893Sdim    ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
2859218893Sdim    return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
2860218893Sdim  }
2861218893Sdim  }
2862218893Sdim  llvm_unreachable("Unknown type trait or not implemented");
2863218893Sdim}
2864218893Sdim
2865218893SdimExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
2866218893Sdim                                      SourceLocation KWLoc,
2867218893Sdim                                      TypeSourceInfo *LhsTSInfo,
2868218893Sdim                                      TypeSourceInfo *RhsTSInfo,
2869218893Sdim                                      SourceLocation RParen) {
2870218893Sdim  QualType LhsT = LhsTSInfo->getType();
2871218893Sdim  QualType RhsT = RhsTSInfo->getType();
2872218893Sdim
2873218893Sdim  if (BTT == BTT_TypeCompatible) {
2874218893Sdim    if (getLangOptions().CPlusPlus) {
2875218893Sdim      Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
2876218893Sdim        << SourceRange(KWLoc, RParen);
2877218893Sdim      return ExprError();
2878218893Sdim    }
2879218893Sdim  }
2880218893Sdim
2881218893Sdim  bool Value = false;
2882218893Sdim  if (!LhsT->isDependentType() && !RhsT->isDependentType())
2883218893Sdim    Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
2884218893Sdim
2885218893Sdim  // Select trait result type.
2886218893Sdim  QualType ResultType;
2887218893Sdim  switch (BTT) {
2888218893Sdim  case BTT_IsBaseOf:       ResultType = Context.BoolTy; break;
2889221345Sdim  case BTT_IsConvertible:  ResultType = Context.BoolTy; break;
2890221345Sdim  case BTT_IsSame:         ResultType = Context.BoolTy; break;
2891218893Sdim  case BTT_TypeCompatible: ResultType = Context.IntTy; break;
2892218893Sdim  case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
2893218893Sdim  }
2894218893Sdim
2895218893Sdim  return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
2896218893Sdim                                                 RhsTSInfo, Value, RParen,
2897218893Sdim                                                 ResultType));
2898218893Sdim}
2899218893Sdim
2900221345SdimExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
2901221345Sdim                                     SourceLocation KWLoc,
2902221345Sdim                                     ParsedType Ty,
2903221345Sdim                                     Expr* DimExpr,
2904221345Sdim                                     SourceLocation RParen) {
2905221345Sdim  TypeSourceInfo *TSInfo;
2906221345Sdim  QualType T = GetTypeFromParser(Ty, &TSInfo);
2907221345Sdim  if (!TSInfo)
2908221345Sdim    TSInfo = Context.getTrivialTypeSourceInfo(T);
2909221345Sdim
2910221345Sdim  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
2911221345Sdim}
2912221345Sdim
2913221345Sdimstatic uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
2914221345Sdim                                           QualType T, Expr *DimExpr,
2915221345Sdim                                           SourceLocation KeyLoc) {
2916221345Sdim  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
2917221345Sdim
2918221345Sdim  switch(ATT) {
2919221345Sdim  case ATT_ArrayRank:
2920221345Sdim    if (T->isArrayType()) {
2921221345Sdim      unsigned Dim = 0;
2922221345Sdim      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2923221345Sdim        ++Dim;
2924221345Sdim        T = AT->getElementType();
2925221345Sdim      }
2926221345Sdim      return Dim;
2927221345Sdim    }
2928221345Sdim    return 0;
2929221345Sdim
2930221345Sdim  case ATT_ArrayExtent: {
2931221345Sdim    llvm::APSInt Value;
2932221345Sdim    uint64_t Dim;
2933221345Sdim    if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
2934221345Sdim      if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
2935221345Sdim        Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2936221345Sdim          DimExpr->getSourceRange();
2937221345Sdim        return false;
2938221345Sdim      }
2939221345Sdim      Dim = Value.getLimitedValue();
2940221345Sdim    } else {
2941221345Sdim      Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
2942221345Sdim        DimExpr->getSourceRange();
2943221345Sdim      return false;
2944221345Sdim    }
2945221345Sdim
2946221345Sdim    if (T->isArrayType()) {
2947221345Sdim      unsigned D = 0;
2948221345Sdim      bool Matched = false;
2949221345Sdim      while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
2950221345Sdim        if (Dim == D) {
2951221345Sdim          Matched = true;
2952221345Sdim          break;
2953221345Sdim        }
2954221345Sdim        ++D;
2955221345Sdim        T = AT->getElementType();
2956221345Sdim      }
2957221345Sdim
2958221345Sdim      if (Matched && T->isArrayType()) {
2959221345Sdim        if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
2960221345Sdim          return CAT->getSize().getLimitedValue();
2961221345Sdim      }
2962221345Sdim    }
2963221345Sdim    return 0;
2964221345Sdim  }
2965221345Sdim  }
2966221345Sdim  llvm_unreachable("Unknown type trait or not implemented");
2967221345Sdim}
2968221345Sdim
2969221345SdimExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
2970221345Sdim                                     SourceLocation KWLoc,
2971221345Sdim                                     TypeSourceInfo *TSInfo,
2972221345Sdim                                     Expr* DimExpr,
2973221345Sdim                                     SourceLocation RParen) {
2974221345Sdim  QualType T = TSInfo->getType();
2975221345Sdim
2976221345Sdim  // FIXME: This should likely be tracked as an APInt to remove any host
2977221345Sdim  // assumptions about the width of size_t on the target.
2978221345Sdim  uint64_t Value = 0;
2979221345Sdim  if (!T->isDependentType())
2980221345Sdim    Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
2981221345Sdim
2982221345Sdim  // While the specification for these traits from the Embarcadero C++
2983221345Sdim  // compiler's documentation says the return type is 'unsigned int', Clang
2984221345Sdim  // returns 'size_t'. On Windows, the primary platform for the Embarcadero
2985221345Sdim  // compiler, there is no difference. On several other platforms this is an
2986221345Sdim  // important distinction.
2987221345Sdim  return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
2988221345Sdim                                                DimExpr, RParen,
2989221345Sdim                                                Context.getSizeType()));
2990221345Sdim}
2991221345Sdim
2992221345SdimExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
2993221345Sdim                                      SourceLocation KWLoc,
2994221345Sdim                                      Expr *Queried,
2995221345Sdim                                      SourceLocation RParen) {
2996221345Sdim  // If error parsing the expression, ignore.
2997221345Sdim  if (!Queried)
2998221345Sdim    return ExprError();
2999221345Sdim
3000221345Sdim  ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
3001221345Sdim
3002221345Sdim  return move(Result);
3003221345Sdim}
3004221345Sdim
3005221345Sdimstatic bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3006221345Sdim  switch (ET) {
3007221345Sdim  case ET_IsLValueExpr: return E->isLValue();
3008221345Sdim  case ET_IsRValueExpr: return E->isRValue();
3009221345Sdim  }
3010221345Sdim  llvm_unreachable("Expression trait not covered by switch");
3011221345Sdim}
3012221345Sdim
3013221345SdimExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
3014221345Sdim                                      SourceLocation KWLoc,
3015221345Sdim                                      Expr *Queried,
3016221345Sdim                                      SourceLocation RParen) {
3017221345Sdim  if (Queried->isTypeDependent()) {
3018221345Sdim    // Delay type-checking for type-dependent expressions.
3019221345Sdim  } else if (Queried->getType()->isPlaceholderType()) {
3020221345Sdim    ExprResult PE = CheckPlaceholderExpr(Queried);
3021221345Sdim    if (PE.isInvalid()) return ExprError();
3022221345Sdim    return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3023221345Sdim  }
3024221345Sdim
3025221345Sdim  bool Value = EvaluateExpressionTrait(ET, Queried);
3026221345Sdim
3027221345Sdim  return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3028221345Sdim                                                 RParen, Context.BoolTy));
3029221345Sdim}
3030221345Sdim
3031221345SdimQualType Sema::CheckPointerToMemberOperands(ExprResult &lex, ExprResult &rex,
3032218893Sdim                                            ExprValueKind &VK,
3033218893Sdim                                            SourceLocation Loc,
3034218893Sdim                                            bool isIndirect) {
3035193326Sed  const char *OpSpelling = isIndirect ? "->*" : ".*";
3036193326Sed  // C++ 5.5p2
3037193326Sed  //   The binary operator .* [p3: ->*] binds its second operand, which shall
3038193326Sed  //   be of type "pointer to member of T" (where T is a completely-defined
3039193326Sed  //   class type) [...]
3040221345Sdim  QualType RType = rex.get()->getType();
3041198092Srdivacky  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
3042193326Sed  if (!MemPtr) {
3043193326Sed    Diag(Loc, diag::err_bad_memptr_rhs)
3044221345Sdim      << OpSpelling << RType << rex.get()->getSourceRange();
3045193326Sed    return QualType();
3046198092Srdivacky  }
3047193326Sed
3048193326Sed  QualType Class(MemPtr->getClass(), 0);
3049193326Sed
3050218893Sdim  // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3051218893Sdim  // member pointer points must be completely-defined. However, there is no
3052218893Sdim  // reason for this semantic distinction, and the rule is not enforced by
3053218893Sdim  // other compilers. Therefore, we do not check this property, as it is
3054218893Sdim  // likely to be considered a defect.
3055207619Srdivacky
3056193326Sed  // C++ 5.5p2
3057193326Sed  //   [...] to its first operand, which shall be of class T or of a class of
3058193326Sed  //   which T is an unambiguous and accessible base class. [p3: a pointer to
3059193326Sed  //   such a class]
3060221345Sdim  QualType LType = lex.get()->getType();
3061193326Sed  if (isIndirect) {
3062198092Srdivacky    if (const PointerType *Ptr = LType->getAs<PointerType>())
3063218893Sdim      LType = Ptr->getPointeeType();
3064193326Sed    else {
3065193326Sed      Diag(Loc, diag::err_bad_memptr_lhs)
3066198893Srdivacky        << OpSpelling << 1 << LType
3067206084Srdivacky        << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
3068193326Sed      return QualType();
3069193326Sed    }
3070193326Sed  }
3071193326Sed
3072199482Srdivacky  if (!Context.hasSameUnqualifiedType(Class, LType)) {
3073207619Srdivacky    // If we want to check the hierarchy, we need a complete type.
3074207619Srdivacky    if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
3075207619Srdivacky        << OpSpelling << (int)isIndirect)) {
3076207619Srdivacky      return QualType();
3077207619Srdivacky    }
3078207619Srdivacky    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3079198092Srdivacky                       /*DetectVirtual=*/false);
3080193326Sed    // FIXME: Would it be useful to print full ambiguity paths, or is that
3081193326Sed    // overkill?
3082193326Sed    if (!IsDerivedFrom(LType, Class, Paths) ||
3083193326Sed        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3084193326Sed      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
3085221345Sdim        << (int)isIndirect << lex.get()->getType();
3086193326Sed      return QualType();
3087193326Sed    }
3088202879Srdivacky    // Cast LHS to type of use.
3089202879Srdivacky    QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
3090212904Sdim    ExprValueKind VK =
3091221345Sdim        isIndirect ? VK_RValue : CastCategory(lex.get());
3092212904Sdim
3093212904Sdim    CXXCastPath BasePath;
3094207619Srdivacky    BuildBasePathArray(Paths, BasePath);
3095221345Sdim    lex = ImpCastExprToType(lex.take(), UseType, CK_DerivedToBase, VK, &BasePath);
3096193326Sed  }
3097193326Sed
3098221345Sdim  if (isa<CXXScalarValueInitExpr>(rex.get()->IgnoreParens())) {
3099199512Srdivacky    // Diagnose use of pointer-to-member type which when used as
3100199512Srdivacky    // the functional cast in a pointer-to-member expression.
3101199512Srdivacky    Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3102199512Srdivacky     return QualType();
3103199512Srdivacky  }
3104218893Sdim
3105193326Sed  // C++ 5.5p2
3106193326Sed  //   The result is an object or a function of the type specified by the
3107193326Sed  //   second operand.
3108193326Sed  // The cv qualifiers are the union of those in the pointer and the left side,
3109193326Sed  // in accordance with 5.5p5 and 5.2.5.
3110193326Sed  QualType Result = MemPtr->getPointeeType();
3111198092Srdivacky  Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
3112218893Sdim
3113218893Sdim  // C++0x [expr.mptr.oper]p6:
3114218893Sdim  //   In a .* expression whose object expression is an rvalue, the program is
3115218893Sdim  //   ill-formed if the second operand is a pointer to member function with
3116218893Sdim  //   ref-qualifier &. In a ->* expression or in a .* expression whose object
3117218893Sdim  //   expression is an lvalue, the program is ill-formed if the second operand
3118218893Sdim  //   is a pointer to member function with ref-qualifier &&.
3119218893Sdim  if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3120218893Sdim    switch (Proto->getRefQualifier()) {
3121218893Sdim    case RQ_None:
3122218893Sdim      // Do nothing
3123218893Sdim      break;
3124218893Sdim
3125218893Sdim    case RQ_LValue:
3126221345Sdim      if (!isIndirect && !lex.get()->Classify(Context).isLValue())
3127218893Sdim        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3128221345Sdim          << RType << 1 << lex.get()->getSourceRange();
3129218893Sdim      break;
3130218893Sdim
3131218893Sdim    case RQ_RValue:
3132221345Sdim      if (isIndirect || !lex.get()->Classify(Context).isRValue())
3133218893Sdim        Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
3134221345Sdim          << RType << 0 << lex.get()->getSourceRange();
3135218893Sdim      break;
3136218893Sdim    }
3137218893Sdim  }
3138218893Sdim
3139218893Sdim  // C++ [expr.mptr.oper]p6:
3140218893Sdim  //   The result of a .* expression whose second operand is a pointer
3141218893Sdim  //   to a data member is of the same value category as its
3142218893Sdim  //   first operand. The result of a .* expression whose second
3143218893Sdim  //   operand is a pointer to a member function is a prvalue. The
3144218893Sdim  //   result of an ->* expression is an lvalue if its second operand
3145218893Sdim  //   is a pointer to data member and a prvalue otherwise.
3146221345Sdim  if (Result->isFunctionType()) {
3147218893Sdim    VK = VK_RValue;
3148221345Sdim    return Context.BoundMemberTy;
3149221345Sdim  } else if (isIndirect) {
3150218893Sdim    VK = VK_LValue;
3151221345Sdim  } else {
3152221345Sdim    VK = lex.get()->getValueKind();
3153221345Sdim  }
3154218893Sdim
3155193326Sed  return Result;
3156193326Sed}
3157193326Sed
3158193326Sed/// \brief Try to convert a type to another according to C++0x 5.16p3.
3159193326Sed///
3160193326Sed/// This is part of the parameter validation for the ? operator. If either
3161193326Sed/// value operand is a class type, the two operands are attempted to be
3162193326Sed/// converted to each other. This function does the conversion in one direction.
3163206084Srdivacky/// It returns true if the program is ill-formed and has already been diagnosed
3164206084Srdivacky/// as such.
3165193326Sedstatic bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3166193326Sed                                SourceLocation QuestionLoc,
3167206084Srdivacky                                bool &HaveConversion,
3168206084Srdivacky                                QualType &ToType) {
3169206084Srdivacky  HaveConversion = false;
3170206084Srdivacky  ToType = To->getType();
3171218893Sdim
3172218893Sdim  InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
3173206084Srdivacky                                                           SourceLocation());
3174193326Sed  // C++0x 5.16p3
3175193326Sed  //   The process for determining whether an operand expression E1 of type T1
3176193326Sed  //   can be converted to match an operand expression E2 of type T2 is defined
3177193326Sed  //   as follows:
3178193326Sed  //   -- If E2 is an lvalue:
3179218893Sdim  bool ToIsLvalue = To->isLValue();
3180206084Srdivacky  if (ToIsLvalue) {
3181193326Sed    //   E1 can be converted to match E2 if E1 can be implicitly converted to
3182193326Sed    //   type "lvalue reference to T2", subject to the constraint that in the
3183193326Sed    //   conversion the reference must bind directly to E1.
3184206084Srdivacky    QualType T = Self.Context.getLValueReferenceType(ToType);
3185206084Srdivacky    InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3186218893Sdim
3187206084Srdivacky    InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3188206084Srdivacky    if (InitSeq.isDirectReferenceBinding()) {
3189206084Srdivacky      ToType = T;
3190206084Srdivacky      HaveConversion = true;
3191206084Srdivacky      return false;
3192193326Sed    }
3193218893Sdim
3194206084Srdivacky    if (InitSeq.isAmbiguous())
3195206084Srdivacky      return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3196193326Sed  }
3197204643Srdivacky
3198193326Sed  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
3199193326Sed  //      -- if E1 and E2 have class type, and the underlying class types are
3200193326Sed  //         the same or one is a base class of the other:
3201193326Sed  QualType FTy = From->getType();
3202193326Sed  QualType TTy = To->getType();
3203198092Srdivacky  const RecordType *FRec = FTy->getAs<RecordType>();
3204198092Srdivacky  const RecordType *TRec = TTy->getAs<RecordType>();
3205218893Sdim  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
3206206084Srdivacky                       Self.IsDerivedFrom(FTy, TTy);
3207218893Sdim  if (FRec && TRec &&
3208206084Srdivacky      (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
3209193326Sed    //         E1 can be converted to match E2 if the class of T2 is the
3210193326Sed    //         same type as, or a base class of, the class of T1, and
3211193326Sed    //         [cv2 > cv1].
3212204643Srdivacky    if (FRec == TRec || FDerivedFromT) {
3213204643Srdivacky      if (TTy.isAtLeastAsQualifiedAs(FTy)) {
3214206084Srdivacky        InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3215206084Srdivacky        InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3216206084Srdivacky        if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
3217206084Srdivacky          HaveConversion = true;
3218206084Srdivacky          return false;
3219206084Srdivacky        }
3220218893Sdim
3221206084Srdivacky        if (InitSeq.isAmbiguous())
3222206084Srdivacky          return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3223218893Sdim      }
3224193326Sed    }
3225218893Sdim
3226206084Srdivacky    return false;
3227206084Srdivacky  }
3228218893Sdim
3229206084Srdivacky  //     -- Otherwise: E1 can be converted to match E2 if E1 can be
3230206084Srdivacky  //        implicitly converted to the type that expression E2 would have
3231218893Sdim  //        if E2 were converted to an rvalue (or the type it has, if E2 is
3232206084Srdivacky  //        an rvalue).
3233206084Srdivacky  //
3234206084Srdivacky  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3235206084Srdivacky  // to the array-to-pointer or function-to-pointer conversions.
3236206084Srdivacky  if (!TTy->getAs<TagType>())
3237206084Srdivacky    TTy = TTy.getUnqualifiedType();
3238218893Sdim
3239206084Srdivacky  InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3240206084Srdivacky  InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3241218893Sdim  HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
3242206084Srdivacky  ToType = TTy;
3243206084Srdivacky  if (InitSeq.isAmbiguous())
3244206084Srdivacky    return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3245193326Sed
3246193326Sed  return false;
3247193326Sed}
3248193326Sed
3249193326Sed/// \brief Try to find a common type for two according to C++0x 5.16p5.
3250193326Sed///
3251193326Sed/// This is part of the parameter validation for the ? operator. If either
3252193326Sed/// value operand is a class type, overload resolution is used to find a
3253193326Sed/// conversion to a common type.
3254221345Sdimstatic bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
3255218893Sdim                                    SourceLocation QuestionLoc) {
3256221345Sdim  Expr *Args[2] = { LHS.get(), RHS.get() };
3257218893Sdim  OverloadCandidateSet CandidateSet(QuestionLoc);
3258218893Sdim  Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3259218893Sdim                                    CandidateSet);
3260193326Sed
3261193326Sed  OverloadCandidateSet::iterator Best;
3262218893Sdim  switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
3263221345Sdim    case OR_Success: {
3264193326Sed      // We found a match. Perform the conversions on the arguments and move on.
3265221345Sdim      ExprResult LHSRes =
3266221345Sdim        Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3267221345Sdim                                       Best->Conversions[0], Sema::AA_Converting);
3268221345Sdim      if (LHSRes.isInvalid())
3269193326Sed        break;
3270221345Sdim      LHS = move(LHSRes);
3271221345Sdim
3272221345Sdim      ExprResult RHSRes =
3273221345Sdim        Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3274221345Sdim                                       Best->Conversions[1], Sema::AA_Converting);
3275221345Sdim      if (RHSRes.isInvalid())
3276221345Sdim        break;
3277221345Sdim      RHS = move(RHSRes);
3278219077Sdim      if (Best->Function)
3279219077Sdim        Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
3280193326Sed      return false;
3281221345Sdim    }
3282221345Sdim
3283200583Srdivacky    case OR_No_Viable_Function:
3284218893Sdim
3285218893Sdim      // Emit a better diagnostic if one of the expressions is a null pointer
3286218893Sdim      // constant and the other is a pointer type. In this case, the user most
3287218893Sdim      // likely forgot to take the address of the other expression.
3288221345Sdim      if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3289218893Sdim        return true;
3290218893Sdim
3291218893Sdim      Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3292221345Sdim        << LHS.get()->getType() << RHS.get()->getType()
3293221345Sdim        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3294193326Sed      return true;
3295193326Sed
3296200583Srdivacky    case OR_Ambiguous:
3297218893Sdim      Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
3298221345Sdim        << LHS.get()->getType() << RHS.get()->getType()
3299221345Sdim        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3300193326Sed      // FIXME: Print the possible common types by printing the return types of
3301193326Sed      // the viable candidates.
3302193326Sed      break;
3303193326Sed
3304200583Srdivacky    case OR_Deleted:
3305193326Sed      assert(false && "Conditional operator has only built-in overloads");
3306193326Sed      break;
3307193326Sed  }
3308193326Sed  return true;
3309193326Sed}
3310193326Sed
3311193326Sed/// \brief Perform an "extended" implicit conversion as returned by
3312193326Sed/// TryClassUnification.
3313221345Sdimstatic bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
3314206084Srdivacky  InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
3315221345Sdim  InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
3316206084Srdivacky                                                           SourceLocation());
3317221345Sdim  Expr *Arg = E.take();
3318221345Sdim  InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
3319221345Sdim  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
3320206084Srdivacky  if (Result.isInvalid())
3321193326Sed    return true;
3322218893Sdim
3323221345Sdim  E = Result;
3324193326Sed  return false;
3325193326Sed}
3326193326Sed
3327193326Sed/// \brief Check the operands of ?: under C++ semantics.
3328193326Sed///
3329193326Sed/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
3330193326Sed/// extension. In this case, LHS == Cond. (But they're not aliases.)
3331221345SdimQualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
3332218893Sdim                                           ExprValueKind &VK, ExprObjectKind &OK,
3333193326Sed                                           SourceLocation QuestionLoc) {
3334193326Sed  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
3335193326Sed  // interface pointers.
3336193326Sed
3337193326Sed  // C++0x 5.16p1
3338193326Sed  //   The first expression is contextually converted to bool.
3339221345Sdim  if (!Cond.get()->isTypeDependent()) {
3340221345Sdim    ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
3341221345Sdim    if (CondRes.isInvalid())
3342193326Sed      return QualType();
3343221345Sdim    Cond = move(CondRes);
3344193326Sed  }
3345193326Sed
3346218893Sdim  // Assume r-value.
3347218893Sdim  VK = VK_RValue;
3348218893Sdim  OK = OK_Ordinary;
3349218893Sdim
3350193326Sed  // Either of the arguments dependent?
3351221345Sdim  if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
3352193326Sed    return Context.DependentTy;
3353193326Sed
3354193326Sed  // C++0x 5.16p2
3355193326Sed  //   If either the second or the third operand has type (cv) void, ...
3356221345Sdim  QualType LTy = LHS.get()->getType();
3357221345Sdim  QualType RTy = RHS.get()->getType();
3358193326Sed  bool LVoid = LTy->isVoidType();
3359193326Sed  bool RVoid = RTy->isVoidType();
3360193326Sed  if (LVoid || RVoid) {
3361193326Sed    //   ... then the [l2r] conversions are performed on the second and third
3362193326Sed    //   operands ...
3363221345Sdim    LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3364221345Sdim    RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3365221345Sdim    if (LHS.isInvalid() || RHS.isInvalid())
3366221345Sdim      return QualType();
3367221345Sdim    LTy = LHS.get()->getType();
3368221345Sdim    RTy = RHS.get()->getType();
3369193326Sed
3370193326Sed    //   ... and one of the following shall hold:
3371193326Sed    //   -- The second or the third operand (but not both) is a throw-
3372193326Sed    //      expression; the result is of the type of the other and is an rvalue.
3373221345Sdim    bool LThrow = isa<CXXThrowExpr>(LHS.get());
3374221345Sdim    bool RThrow = isa<CXXThrowExpr>(RHS.get());
3375193326Sed    if (LThrow && !RThrow)
3376193326Sed      return RTy;
3377193326Sed    if (RThrow && !LThrow)
3378193326Sed      return LTy;
3379193326Sed
3380193326Sed    //   -- Both the second and third operands have type void; the result is of
3381193326Sed    //      type void and is an rvalue.
3382193326Sed    if (LVoid && RVoid)
3383193326Sed      return Context.VoidTy;
3384193326Sed
3385193326Sed    // Neither holds, error.
3386193326Sed    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
3387193326Sed      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
3388221345Sdim      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3389193326Sed    return QualType();
3390193326Sed  }
3391193326Sed
3392193326Sed  // Neither is void.
3393193326Sed
3394193326Sed  // C++0x 5.16p3
3395193326Sed  //   Otherwise, if the second and third operand have different types, and
3396193326Sed  //   either has (cv) class type, and attempt is made to convert each of those
3397193326Sed  //   operands to the other.
3398218893Sdim  if (!Context.hasSameType(LTy, RTy) &&
3399193326Sed      (LTy->isRecordType() || RTy->isRecordType())) {
3400193326Sed    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
3401193326Sed    // These return true if a single direction is already ambiguous.
3402206084Srdivacky    QualType L2RType, R2LType;
3403206084Srdivacky    bool HaveL2R, HaveR2L;
3404221345Sdim    if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
3405193326Sed      return QualType();
3406221345Sdim    if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
3407193326Sed      return QualType();
3408218893Sdim
3409193326Sed    //   If both can be converted, [...] the program is ill-formed.
3410193326Sed    if (HaveL2R && HaveR2L) {
3411193326Sed      Diag(QuestionLoc, diag::err_conditional_ambiguous)
3412221345Sdim        << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3413193326Sed      return QualType();
3414193326Sed    }
3415193326Sed
3416193326Sed    //   If exactly one conversion is possible, that conversion is applied to
3417193326Sed    //   the chosen operand and the converted operands are used in place of the
3418193326Sed    //   original operands for the remainder of this section.
3419193326Sed    if (HaveL2R) {
3420221345Sdim      if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
3421193326Sed        return QualType();
3422221345Sdim      LTy = LHS.get()->getType();
3423193326Sed    } else if (HaveR2L) {
3424221345Sdim      if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
3425193326Sed        return QualType();
3426221345Sdim      RTy = RHS.get()->getType();
3427193326Sed    }
3428193326Sed  }
3429193326Sed
3430193326Sed  // C++0x 5.16p4
3431218893Sdim  //   If the second and third operands are glvalues of the same value
3432218893Sdim  //   category and have the same type, the result is of that type and
3433218893Sdim  //   value category and it is a bit-field if the second or the third
3434218893Sdim  //   operand is a bit-field, or if both are bit-fields.
3435218893Sdim  // We only extend this to bitfields, not to the crazy other kinds of
3436218893Sdim  // l-values.
3437206084Srdivacky  bool Same = Context.hasSameType(LTy, RTy);
3438218893Sdim  if (Same &&
3439221345Sdim      LHS.get()->isGLValue() &&
3440221345Sdim      LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
3441221345Sdim      LHS.get()->isOrdinaryOrBitFieldObject() &&
3442221345Sdim      RHS.get()->isOrdinaryOrBitFieldObject()) {
3443221345Sdim    VK = LHS.get()->getValueKind();
3444221345Sdim    if (LHS.get()->getObjectKind() == OK_BitField ||
3445221345Sdim        RHS.get()->getObjectKind() == OK_BitField)
3446218893Sdim      OK = OK_BitField;
3447193326Sed    return LTy;
3448218893Sdim  }
3449193326Sed
3450193326Sed  // C++0x 5.16p5
3451193326Sed  //   Otherwise, the result is an rvalue. If the second and third operands
3452193326Sed  //   do not have the same type, and either has (cv) class type, ...
3453193326Sed  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
3454193326Sed    //   ... overload resolution is used to determine the conversions (if any)
3455193326Sed    //   to be applied to the operands. If the overload resolution fails, the
3456193326Sed    //   program is ill-formed.
3457193326Sed    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
3458193326Sed      return QualType();
3459193326Sed  }
3460193326Sed
3461193326Sed  // C++0x 5.16p6
3462193326Sed  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
3463193326Sed  //   conversions are performed on the second and third operands.
3464221345Sdim  LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
3465221345Sdim  RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
3466221345Sdim  if (LHS.isInvalid() || RHS.isInvalid())
3467221345Sdim    return QualType();
3468221345Sdim  LTy = LHS.get()->getType();
3469221345Sdim  RTy = RHS.get()->getType();
3470193326Sed
3471193326Sed  //   After those conversions, one of the following shall hold:
3472193326Sed  //   -- The second and third operands have the same type; the result
3473208600Srdivacky  //      is of that type. If the operands have class type, the result
3474208600Srdivacky  //      is a prvalue temporary of the result type, which is
3475208600Srdivacky  //      copy-initialized from either the second operand or the third
3476208600Srdivacky  //      operand depending on the value of the first operand.
3477208600Srdivacky  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
3478208600Srdivacky    if (LTy->isRecordType()) {
3479208600Srdivacky      // The operands have class type. Make a temporary copy.
3480208600Srdivacky      InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
3481218893Sdim      ExprResult LHSCopy = PerformCopyInitialization(Entity,
3482218893Sdim                                                     SourceLocation(),
3483221345Sdim                                                     LHS);
3484208600Srdivacky      if (LHSCopy.isInvalid())
3485208600Srdivacky        return QualType();
3486218893Sdim
3487218893Sdim      ExprResult RHSCopy = PerformCopyInitialization(Entity,
3488218893Sdim                                                     SourceLocation(),
3489221345Sdim                                                     RHS);
3490208600Srdivacky      if (RHSCopy.isInvalid())
3491208600Srdivacky        return QualType();
3492218893Sdim
3493221345Sdim      LHS = LHSCopy;
3494221345Sdim      RHS = RHSCopy;
3495208600Srdivacky    }
3496208600Srdivacky
3497193326Sed    return LTy;
3498208600Srdivacky  }
3499193326Sed
3500208600Srdivacky  // Extension: conditional operator involving vector types.
3501218893Sdim  if (LTy->isVectorType() || RTy->isVectorType())
3502208600Srdivacky    return CheckVectorOperands(QuestionLoc, LHS, RHS);
3503208600Srdivacky
3504193326Sed  //   -- The second and third operands have arithmetic or enumeration type;
3505193326Sed  //      the usual arithmetic conversions are performed to bring them to a
3506193326Sed  //      common type, and the result is of that type.
3507193326Sed  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
3508193326Sed    UsualArithmeticConversions(LHS, RHS);
3509221345Sdim    if (LHS.isInvalid() || RHS.isInvalid())
3510221345Sdim      return QualType();
3511221345Sdim    return LHS.get()->getType();
3512193326Sed  }
3513193326Sed
3514193326Sed  //   -- The second and third operands have pointer type, or one has pointer
3515193326Sed  //      type and the other is a null pointer constant; pointer conversions
3516193326Sed  //      and qualification conversions are performed to bring them to their
3517193326Sed  //      composite pointer type. The result is of the composite pointer type.
3518202379Srdivacky  //   -- The second and third operands have pointer to member type, or one has
3519202379Srdivacky  //      pointer to member type and the other is a null pointer constant;
3520202379Srdivacky  //      pointer to member conversions and qualification conversions are
3521202379Srdivacky  //      performed to bring them to a common type, whose cv-qualification
3522202379Srdivacky  //      shall match the cv-qualification of either the second or the third
3523202379Srdivacky  //      operand. The result is of the common type.
3524204643Srdivacky  bool NonStandardCompositeType = false;
3525207619Srdivacky  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
3526204643Srdivacky                              isSFINAEContext()? 0 : &NonStandardCompositeType);
3527204643Srdivacky  if (!Composite.isNull()) {
3528204643Srdivacky    if (NonStandardCompositeType)
3529218893Sdim      Diag(QuestionLoc,
3530204643Srdivacky           diag::ext_typecheck_cond_incompatible_operands_nonstandard)
3531204643Srdivacky        << LTy << RTy << Composite
3532221345Sdim        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3533218893Sdim
3534193326Sed    return Composite;
3535204643Srdivacky  }
3536218893Sdim
3537206084Srdivacky  // Similarly, attempt to find composite type of two objective-c pointers.
3538200583Srdivacky  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
3539200583Srdivacky  if (!Composite.isNull())
3540200583Srdivacky    return Composite;
3541193326Sed
3542218893Sdim  // Check if we are using a null with a non-pointer type.
3543221345Sdim  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
3544218893Sdim    return QualType();
3545218893Sdim
3546193326Sed  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3547221345Sdim    << LHS.get()->getType() << RHS.get()->getType()
3548221345Sdim    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
3549193326Sed  return QualType();
3550193326Sed}
3551193326Sed
3552193326Sed/// \brief Find a merged pointer type and convert the two expressions to it.
3553193326Sed///
3554198092Srdivacky/// This finds the composite pointer type (or member pointer type) for @p E1
3555198092Srdivacky/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
3556198092Srdivacky/// type and returns it.
3557193326Sed/// It does not emit diagnostics.
3558204643Srdivacky///
3559207619Srdivacky/// \param Loc The location of the operator requiring these two expressions to
3560207619Srdivacky/// be converted to the composite pointer type.
3561207619Srdivacky///
3562204643Srdivacky/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
3563204643Srdivacky/// a non-standard (but still sane) composite type to which both expressions
3564204643Srdivacky/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
3565204643Srdivacky/// will be set true.
3566218893SdimQualType Sema::FindCompositePointerType(SourceLocation Loc,
3567207619Srdivacky                                        Expr *&E1, Expr *&E2,
3568204643Srdivacky                                        bool *NonStandardCompositeType) {
3569204643Srdivacky  if (NonStandardCompositeType)
3570204643Srdivacky    *NonStandardCompositeType = false;
3571218893Sdim
3572193326Sed  assert(getLangOptions().CPlusPlus && "This function assumes C++");
3573193326Sed  QualType T1 = E1->getType(), T2 = E2->getType();
3574193326Sed
3575200583Srdivacky  if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
3576200583Srdivacky      !T2->isAnyPointerType() && !T2->isMemberPointerType())
3577198092Srdivacky   return QualType();
3578198092Srdivacky
3579193326Sed  // C++0x 5.9p2
3580193326Sed  //   Pointer conversions and qualification conversions are performed on
3581193326Sed  //   pointer operands to bring them to their composite pointer type. If
3582193326Sed  //   one operand is a null pointer constant, the composite pointer type is
3583193326Sed  //   the type of the other operand.
3584198092Srdivacky  if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3585198398Srdivacky    if (T2->isMemberPointerType())
3586221345Sdim      E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
3587198398Srdivacky    else
3588221345Sdim      E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
3589193326Sed    return T2;
3590193326Sed  }
3591198092Srdivacky  if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3592198398Srdivacky    if (T1->isMemberPointerType())
3593221345Sdim      E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
3594198398Srdivacky    else
3595221345Sdim      E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
3596193326Sed    return T1;
3597193326Sed  }
3598198092Srdivacky
3599198092Srdivacky  // Now both have to be pointers or member pointers.
3600199482Srdivacky  if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
3601199482Srdivacky      (!T2->isPointerType() && !T2->isMemberPointerType()))
3602193326Sed    return QualType();
3603193326Sed
3604193326Sed  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
3605193326Sed  //   the other has type "pointer to cv2 T" and the composite pointer type is
3606193326Sed  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
3607193326Sed  //   Otherwise, the composite pointer type is a pointer type similar to the
3608193326Sed  //   type of one of the operands, with a cv-qualification signature that is
3609193326Sed  //   the union of the cv-qualification signatures of the operand types.
3610193326Sed  // In practice, the first part here is redundant; it's subsumed by the second.
3611193326Sed  // What we do here is, we build the two possible composite types, and try the
3612193326Sed  // conversions in both directions. If only one works, or if the two composite
3613193326Sed  // types are the same, we have succeeded.
3614198092Srdivacky  // FIXME: extended qualifiers?
3615199482Srdivacky  typedef llvm::SmallVector<unsigned, 4> QualifierVector;
3616199482Srdivacky  QualifierVector QualifierUnion;
3617199482Srdivacky  typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
3618199482Srdivacky      ContainingClassVector;
3619199482Srdivacky  ContainingClassVector MemberOfClass;
3620199482Srdivacky  QualType Composite1 = Context.getCanonicalType(T1),
3621199482Srdivacky           Composite2 = Context.getCanonicalType(T2);
3622218893Sdim  unsigned NeedConstBefore = 0;
3623198092Srdivacky  do {
3624198092Srdivacky    const PointerType *Ptr1, *Ptr2;
3625198092Srdivacky    if ((Ptr1 = Composite1->getAs<PointerType>()) &&
3626198092Srdivacky        (Ptr2 = Composite2->getAs<PointerType>())) {
3627198092Srdivacky      Composite1 = Ptr1->getPointeeType();
3628198092Srdivacky      Composite2 = Ptr2->getPointeeType();
3629218893Sdim
3630204643Srdivacky      // If we're allowed to create a non-standard composite type, keep track
3631218893Sdim      // of where we need to fill in additional 'const' qualifiers.
3632204643Srdivacky      if (NonStandardCompositeType &&
3633204643Srdivacky          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3634204643Srdivacky        NeedConstBefore = QualifierUnion.size();
3635218893Sdim
3636198092Srdivacky      QualifierUnion.push_back(
3637198092Srdivacky                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3638198092Srdivacky      MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
3639198092Srdivacky      continue;
3640198092Srdivacky    }
3641198092Srdivacky
3642198092Srdivacky    const MemberPointerType *MemPtr1, *MemPtr2;
3643198092Srdivacky    if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
3644198092Srdivacky        (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
3645198092Srdivacky      Composite1 = MemPtr1->getPointeeType();
3646198092Srdivacky      Composite2 = MemPtr2->getPointeeType();
3647218893Sdim
3648204643Srdivacky      // If we're allowed to create a non-standard composite type, keep track
3649218893Sdim      // of where we need to fill in additional 'const' qualifiers.
3650204643Srdivacky      if (NonStandardCompositeType &&
3651204643Srdivacky          Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
3652204643Srdivacky        NeedConstBefore = QualifierUnion.size();
3653218893Sdim
3654198092Srdivacky      QualifierUnion.push_back(
3655198092Srdivacky                 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
3656198092Srdivacky      MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
3657198092Srdivacky                                             MemPtr2->getClass()));
3658198092Srdivacky      continue;
3659198092Srdivacky    }
3660198092Srdivacky
3661198092Srdivacky    // FIXME: block pointer types?
3662198092Srdivacky
3663198092Srdivacky    // Cannot unwrap any more types.
3664198092Srdivacky    break;
3665198092Srdivacky  } while (true);
3666198092Srdivacky
3667204643Srdivacky  if (NeedConstBefore && NonStandardCompositeType) {
3668204643Srdivacky    // Extension: Add 'const' to qualifiers that come before the first qualifier
3669218893Sdim    // mismatch, so that our (non-standard!) composite type meets the
3670204643Srdivacky    // requirements of C++ [conv.qual]p4 bullet 3.
3671204643Srdivacky    for (unsigned I = 0; I != NeedConstBefore; ++I) {
3672204643Srdivacky      if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
3673204643Srdivacky        QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
3674204643Srdivacky        *NonStandardCompositeType = true;
3675204643Srdivacky      }
3676204643Srdivacky    }
3677204643Srdivacky  }
3678218893Sdim
3679198092Srdivacky  // Rewrap the composites as pointers or member pointers with the union CVRs.
3680199482Srdivacky  ContainingClassVector::reverse_iterator MOC
3681199482Srdivacky    = MemberOfClass.rbegin();
3682199482Srdivacky  for (QualifierVector::reverse_iterator
3683199482Srdivacky         I = QualifierUnion.rbegin(),
3684199482Srdivacky         E = QualifierUnion.rend();
3685198092Srdivacky       I != E; (void)++I, ++MOC) {
3686198092Srdivacky    Qualifiers Quals = Qualifiers::fromCVRMask(*I);
3687198092Srdivacky    if (MOC->first && MOC->second) {
3688198092Srdivacky      // Rebuild member pointer type
3689198092Srdivacky      Composite1 = Context.getMemberPointerType(
3690198092Srdivacky                                    Context.getQualifiedType(Composite1, Quals),
3691198092Srdivacky                                    MOC->first);
3692198092Srdivacky      Composite2 = Context.getMemberPointerType(
3693198092Srdivacky                                    Context.getQualifiedType(Composite2, Quals),
3694198092Srdivacky                                    MOC->second);
3695198092Srdivacky    } else {
3696198092Srdivacky      // Rebuild pointer type
3697198092Srdivacky      Composite1
3698198092Srdivacky        = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
3699198092Srdivacky      Composite2
3700198092Srdivacky        = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
3701198092Srdivacky    }
3702193326Sed  }
3703193326Sed
3704207619Srdivacky  // Try to convert to the first composite pointer type.
3705207619Srdivacky  InitializedEntity Entity1
3706207619Srdivacky    = InitializedEntity::InitializeTemporary(Composite1);
3707207619Srdivacky  InitializationKind Kind
3708207619Srdivacky    = InitializationKind::CreateCopy(Loc, SourceLocation());
3709207619Srdivacky  InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
3710207619Srdivacky  InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
3711198092Srdivacky
3712207619Srdivacky  if (E1ToC1 && E2ToC1) {
3713207619Srdivacky    // Conversion to Composite1 is viable.
3714207619Srdivacky    if (!Context.hasSameType(Composite1, Composite2)) {
3715207619Srdivacky      // Composite2 is a different type from Composite1. Check whether
3716207619Srdivacky      // Composite2 is also viable.
3717207619Srdivacky      InitializedEntity Entity2
3718207619Srdivacky        = InitializedEntity::InitializeTemporary(Composite2);
3719207619Srdivacky      InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3720207619Srdivacky      InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3721207619Srdivacky      if (E1ToC2 && E2ToC2) {
3722207619Srdivacky        // Both Composite1 and Composite2 are viable and are different;
3723207619Srdivacky        // this is an ambiguity.
3724207619Srdivacky        return QualType();
3725207619Srdivacky      }
3726207619Srdivacky    }
3727207619Srdivacky
3728207619Srdivacky    // Convert E1 to Composite1
3729212904Sdim    ExprResult E1Result
3730212904Sdim      = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
3731207619Srdivacky    if (E1Result.isInvalid())
3732207619Srdivacky      return QualType();
3733207619Srdivacky    E1 = E1Result.takeAs<Expr>();
3734207619Srdivacky
3735207619Srdivacky    // Convert E2 to Composite1
3736212904Sdim    ExprResult E2Result
3737212904Sdim      = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
3738207619Srdivacky    if (E2Result.isInvalid())
3739207619Srdivacky      return QualType();
3740207619Srdivacky    E2 = E2Result.takeAs<Expr>();
3741218893Sdim
3742207619Srdivacky    return Composite1;
3743193326Sed  }
3744193326Sed
3745207619Srdivacky  // Check whether Composite2 is viable.
3746207619Srdivacky  InitializedEntity Entity2
3747207619Srdivacky    = InitializedEntity::InitializeTemporary(Composite2);
3748207619Srdivacky  InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
3749207619Srdivacky  InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
3750207619Srdivacky  if (!E1ToC2 || !E2ToC2)
3751207619Srdivacky    return QualType();
3752218893Sdim
3753207619Srdivacky  // Convert E1 to Composite2
3754212904Sdim  ExprResult E1Result
3755212904Sdim    = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
3756207619Srdivacky  if (E1Result.isInvalid())
3757207619Srdivacky    return QualType();
3758207619Srdivacky  E1 = E1Result.takeAs<Expr>();
3759218893Sdim
3760207619Srdivacky  // Convert E2 to Composite2
3761212904Sdim  ExprResult E2Result
3762212904Sdim    = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
3763207619Srdivacky  if (E2Result.isInvalid())
3764207619Srdivacky    return QualType();
3765207619Srdivacky  E2 = E2Result.takeAs<Expr>();
3766218893Sdim
3767207619Srdivacky  return Composite2;
3768193326Sed}
3769193326Sed
3770212904SdimExprResult Sema::MaybeBindToTemporary(Expr *E) {
3771218893Sdim  if (!E)
3772218893Sdim    return ExprError();
3773218893Sdim
3774198092Srdivacky  if (!Context.getLangOptions().CPlusPlus)
3775198092Srdivacky    return Owned(E);
3776198092Srdivacky
3777201361Srdivacky  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
3778201361Srdivacky
3779198092Srdivacky  const RecordType *RT = E->getType()->getAs<RecordType>();
3780193326Sed  if (!RT)
3781193326Sed    return Owned(E);
3782198092Srdivacky
3783218893Sdim  // If the result is a glvalue, we shouldn't bind it.
3784218893Sdim  if (E->Classify(Context).isGLValue())
3785218893Sdim    return Owned(E);
3786203955Srdivacky
3787203955Srdivacky  // That should be enough to guarantee that this type is complete.
3788203955Srdivacky  // If it has a trivial destructor, we can avoid the extra copy.
3789203955Srdivacky  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3790212904Sdim  if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
3791203955Srdivacky    return Owned(E);
3792203955Srdivacky
3793210299Sed  CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD));
3794193326Sed  ExprTemporaries.push_back(Temp);
3795210299Sed  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
3796198092Srdivacky    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
3797207619Srdivacky    CheckDestructorAccess(E->getExprLoc(), Destructor,
3798207619Srdivacky                          PDiag(diag::err_access_dtor_temp)
3799207619Srdivacky                            << E->getType());
3800207619Srdivacky  }
3801193326Sed  // FIXME: Add the temporary to the temporaries vector.
3802193326Sed  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
3803193326Sed}
3804193326Sed
3805218893SdimExpr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
3806193576Sed  assert(SubExpr && "sub expression can't be null!");
3807198092Srdivacky
3808200583Srdivacky  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3809200583Srdivacky  assert(ExprTemporaries.size() >= FirstTemporary);
3810200583Srdivacky  if (ExprTemporaries.size() == FirstTemporary)
3811193576Sed    return SubExpr;
3812198092Srdivacky
3813218893Sdim  Expr *E = ExprWithCleanups::Create(Context, SubExpr,
3814218893Sdim                                     &ExprTemporaries[FirstTemporary],
3815218893Sdim                                     ExprTemporaries.size() - FirstTemporary);
3816200583Srdivacky  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
3817200583Srdivacky                        ExprTemporaries.end());
3818198092Srdivacky
3819193576Sed  return E;
3820193576Sed}
3821193576Sed
3822218893SdimExprResult
3823218893SdimSema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
3824201361Srdivacky  if (SubExpr.isInvalid())
3825201361Srdivacky    return ExprError();
3826218893Sdim
3827218893Sdim  return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
3828201361Srdivacky}
3829201361Srdivacky
3830218893SdimStmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
3831218893Sdim  assert(SubStmt && "sub statement can't be null!");
3832218893Sdim
3833201361Srdivacky  unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
3834201361Srdivacky  assert(ExprTemporaries.size() >= FirstTemporary);
3835218893Sdim  if (ExprTemporaries.size() == FirstTemporary)
3836218893Sdim    return SubStmt;
3837201361Srdivacky
3838218893Sdim  // FIXME: In order to attach the temporaries, wrap the statement into
3839218893Sdim  // a StmtExpr; currently this is only used for asm statements.
3840218893Sdim  // This is hacky, either create a new CXXStmtWithTemporaries statement or
3841218893Sdim  // a new AsmStmtWithTemporaries.
3842218893Sdim  CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
3843218893Sdim                                                      SourceLocation(),
3844218893Sdim                                                      SourceLocation());
3845218893Sdim  Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
3846218893Sdim                                   SourceLocation());
3847218893Sdim  return MaybeCreateExprWithCleanups(E);
3848201361Srdivacky}
3849201361Srdivacky
3850212904SdimExprResult
3851212904SdimSema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
3852212904Sdim                                   tok::TokenKind OpKind, ParsedType &ObjectType,
3853204643Srdivacky                                   bool &MayBePseudoDestructor) {
3854198092Srdivacky  // Since this might be a postfix expression, get rid of ParenListExprs.
3855212904Sdim  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3856212904Sdim  if (Result.isInvalid()) return ExprError();
3857212904Sdim  Base = Result.get();
3858198092Srdivacky
3859212904Sdim  QualType BaseType = Base->getType();
3860204643Srdivacky  MayBePseudoDestructor = false;
3861198092Srdivacky  if (BaseType->isDependentType()) {
3862198954Srdivacky    // If we have a pointer to a dependent type and are using the -> operator,
3863198954Srdivacky    // the object type is the type that the pointer points to. We might still
3864198954Srdivacky    // have enough information about that type to do something useful.
3865198954Srdivacky    if (OpKind == tok::arrow)
3866198954Srdivacky      if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3867198954Srdivacky        BaseType = Ptr->getPointeeType();
3868218893Sdim
3869212904Sdim    ObjectType = ParsedType::make(BaseType);
3870204643Srdivacky    MayBePseudoDestructor = true;
3871212904Sdim    return Owned(Base);
3872198092Srdivacky  }
3873198092Srdivacky
3874198092Srdivacky  // C++ [over.match.oper]p8:
3875198092Srdivacky  //   [...] When operator->returns, the operator-> is applied  to the value
3876198092Srdivacky  //   returned, with the original second operand.
3877198092Srdivacky  if (OpKind == tok::arrow) {
3878198092Srdivacky    // The set of types we've considered so far.
3879198092Srdivacky    llvm::SmallPtrSet<CanQualType,8> CTypes;
3880198092Srdivacky    llvm::SmallVector<SourceLocation, 8> Locations;
3881198092Srdivacky    CTypes.insert(Context.getCanonicalType(BaseType));
3882218893Sdim
3883198092Srdivacky    while (BaseType->isRecordType()) {
3884212904Sdim      Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
3885212904Sdim      if (Result.isInvalid())
3886198092Srdivacky        return ExprError();
3887212904Sdim      Base = Result.get();
3888212904Sdim      if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
3889198092Srdivacky        Locations.push_back(OpCall->getDirectCallee()->getLocation());
3890212904Sdim      BaseType = Base->getType();
3891198092Srdivacky      CanQualType CBaseType = Context.getCanonicalType(BaseType);
3892198092Srdivacky      if (!CTypes.insert(CBaseType)) {
3893198092Srdivacky        Diag(OpLoc, diag::err_operator_arrow_circular);
3894198092Srdivacky        for (unsigned i = 0; i < Locations.size(); i++)
3895198092Srdivacky          Diag(Locations[i], diag::note_declared_at);
3896198092Srdivacky        return ExprError();
3897198092Srdivacky      }
3898198092Srdivacky    }
3899199990Srdivacky
3900199990Srdivacky    if (BaseType->isPointerType())
3901199990Srdivacky      BaseType = BaseType->getPointeeType();
3902198092Srdivacky  }
3903198092Srdivacky
3904198092Srdivacky  // We could end up with various non-record types here, such as extended
3905198092Srdivacky  // vector types or Objective-C interfaces. Just return early and let
3906198092Srdivacky  // ActOnMemberReferenceExpr do the work.
3907198092Srdivacky  if (!BaseType->isRecordType()) {
3908198092Srdivacky    // C++ [basic.lookup.classref]p2:
3909198092Srdivacky    //   [...] If the type of the object expression is of pointer to scalar
3910198092Srdivacky    //   type, the unqualified-id is looked up in the context of the complete
3911198092Srdivacky    //   postfix-expression.
3912204643Srdivacky    //
3913204643Srdivacky    // This also indicates that we should be parsing a
3914204643Srdivacky    // pseudo-destructor-name.
3915212904Sdim    ObjectType = ParsedType();
3916204643Srdivacky    MayBePseudoDestructor = true;
3917212904Sdim    return Owned(Base);
3918198092Srdivacky  }
3919198092Srdivacky
3920199482Srdivacky  // The object type must be complete (or dependent).
3921199482Srdivacky  if (!BaseType->isDependentType() &&
3922218893Sdim      RequireCompleteType(OpLoc, BaseType,
3923199482Srdivacky                          PDiag(diag::err_incomplete_member_access)))
3924199482Srdivacky    return ExprError();
3925218893Sdim
3926198092Srdivacky  // C++ [basic.lookup.classref]p2:
3927198092Srdivacky  //   If the id-expression in a class member access (5.2.5) is an
3928199482Srdivacky  //   unqualified-id, and the type of the object expression is of a class
3929198092Srdivacky  //   type C (or of pointer to a class type C), the unqualified-id is looked
3930198092Srdivacky  //   up in the scope of class C. [...]
3931212904Sdim  ObjectType = ParsedType::make(BaseType);
3932198092Srdivacky  return move(Base);
3933198092Srdivacky}
3934198092Srdivacky
3935212904SdimExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
3936212904Sdim                                                   Expr *MemExpr) {
3937204643Srdivacky  SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
3938212904Sdim  Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
3939212904Sdim    << isa<CXXPseudoDestructorExpr>(MemExpr)
3940206084Srdivacky    << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
3941218893Sdim
3942204643Srdivacky  return ActOnCallExpr(/*Scope*/ 0,
3943212904Sdim                       MemExpr,
3944204643Srdivacky                       /*LPLoc*/ ExpectedLParenLoc,
3945212904Sdim                       MultiExprArg(),
3946204643Srdivacky                       /*RPLoc*/ ExpectedLParenLoc);
3947204643Srdivacky}
3948204643Srdivacky
3949212904SdimExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
3950219077Sdim                                           SourceLocation OpLoc,
3951219077Sdim                                           tok::TokenKind OpKind,
3952219077Sdim                                           const CXXScopeSpec &SS,
3953219077Sdim                                           TypeSourceInfo *ScopeTypeInfo,
3954219077Sdim                                           SourceLocation CCLoc,
3955219077Sdim                                           SourceLocation TildeLoc,
3956204643Srdivacky                                         PseudoDestructorTypeStorage Destructed,
3957219077Sdim                                           bool HasTrailingLParen) {
3958204643Srdivacky  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
3959218893Sdim
3960204643Srdivacky  // C++ [expr.pseudo]p2:
3961218893Sdim  //   The left-hand side of the dot operator shall be of scalar type. The
3962204643Srdivacky  //   left-hand side of the arrow operator shall be of pointer to scalar type.
3963218893Sdim  //   This scalar type is the object type.
3964212904Sdim  QualType ObjectType = Base->getType();
3965204643Srdivacky  if (OpKind == tok::arrow) {
3966204643Srdivacky    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
3967204643Srdivacky      ObjectType = Ptr->getPointeeType();
3968212904Sdim    } else if (!Base->isTypeDependent()) {
3969204643Srdivacky      // The user wrote "p->" when she probably meant "p."; fix it.
3970204643Srdivacky      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3971204643Srdivacky        << ObjectType << true
3972206084Srdivacky        << FixItHint::CreateReplacement(OpLoc, ".");
3973204643Srdivacky      if (isSFINAEContext())
3974204643Srdivacky        return ExprError();
3975218893Sdim
3976204643Srdivacky      OpKind = tok::period;
3977204643Srdivacky    }
3978204643Srdivacky  }
3979218893Sdim
3980204643Srdivacky  if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
3981204643Srdivacky    Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
3982212904Sdim      << ObjectType << Base->getSourceRange();
3983204643Srdivacky    return ExprError();
3984204643Srdivacky  }
3985204643Srdivacky
3986204643Srdivacky  // C++ [expr.pseudo]p2:
3987218893Sdim  //   [...] The cv-unqualified versions of the object type and of the type
3988204643Srdivacky  //   designated by the pseudo-destructor-name shall be the same type.
3989204643Srdivacky  if (DestructedTypeInfo) {
3990204643Srdivacky    QualType DestructedType = DestructedTypeInfo->getType();
3991204643Srdivacky    SourceLocation DestructedTypeStart
3992208600Srdivacky      = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
3993204643Srdivacky    if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
3994204643Srdivacky        !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
3995204643Srdivacky      Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
3996212904Sdim        << ObjectType << DestructedType << Base->getSourceRange()
3997208600Srdivacky        << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
3998218893Sdim
3999204643Srdivacky      // Recover by setting the destructed type to the object type.
4000204643Srdivacky      DestructedType = ObjectType;
4001204643Srdivacky      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4002204643Srdivacky                                                           DestructedTypeStart);
4003204643Srdivacky      Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4004204643Srdivacky    }
4005204643Srdivacky  }
4006218893Sdim
4007204643Srdivacky  // C++ [expr.pseudo]p2:
4008204643Srdivacky  //   [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4009204643Srdivacky  //   form
4010204643Srdivacky  //
4011218893Sdim  //     ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
4012204643Srdivacky  //
4013204643Srdivacky  //   shall designate the same scalar type.
4014204643Srdivacky  if (ScopeTypeInfo) {
4015204643Srdivacky    QualType ScopeType = ScopeTypeInfo->getType();
4016204643Srdivacky    if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
4017210299Sed        !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
4018218893Sdim
4019208600Srdivacky      Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
4020204643Srdivacky           diag::err_pseudo_dtor_type_mismatch)
4021212904Sdim        << ObjectType << ScopeType << Base->getSourceRange()
4022208600Srdivacky        << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
4023218893Sdim
4024204643Srdivacky      ScopeType = QualType();
4025204643Srdivacky      ScopeTypeInfo = 0;
4026204643Srdivacky    }
4027204643Srdivacky  }
4028218893Sdim
4029212904Sdim  Expr *Result
4030212904Sdim    = new (Context) CXXPseudoDestructorExpr(Context, Base,
4031212904Sdim                                            OpKind == tok::arrow, OpLoc,
4032219077Sdim                                            SS.getWithLocInContext(Context),
4033212904Sdim                                            ScopeTypeInfo,
4034212904Sdim                                            CCLoc,
4035212904Sdim                                            TildeLoc,
4036212904Sdim                                            Destructed);
4037218893Sdim
4038204643Srdivacky  if (HasTrailingLParen)
4039212904Sdim    return Owned(Result);
4040218893Sdim
4041212904Sdim  return DiagnoseDtorReference(Destructed.getLocation(), Result);
4042204643Srdivacky}
4043204643Srdivacky
4044212904SdimExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
4045219077Sdim                                           SourceLocation OpLoc,
4046219077Sdim                                           tok::TokenKind OpKind,
4047219077Sdim                                           CXXScopeSpec &SS,
4048219077Sdim                                           UnqualifiedId &FirstTypeName,
4049219077Sdim                                           SourceLocation CCLoc,
4050219077Sdim                                           SourceLocation TildeLoc,
4051219077Sdim                                           UnqualifiedId &SecondTypeName,
4052219077Sdim                                           bool HasTrailingLParen) {
4053204643Srdivacky  assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4054204643Srdivacky          FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4055204643Srdivacky         "Invalid first type name in pseudo-destructor");
4056204643Srdivacky  assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4057204643Srdivacky          SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
4058204643Srdivacky         "Invalid second type name in pseudo-destructor");
4059204643Srdivacky
4060204643Srdivacky  // C++ [expr.pseudo]p2:
4061218893Sdim  //   The left-hand side of the dot operator shall be of scalar type. The
4062204643Srdivacky  //   left-hand side of the arrow operator shall be of pointer to scalar type.
4063218893Sdim  //   This scalar type is the object type.
4064212904Sdim  QualType ObjectType = Base->getType();
4065204643Srdivacky  if (OpKind == tok::arrow) {
4066204643Srdivacky    if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4067204643Srdivacky      ObjectType = Ptr->getPointeeType();
4068204643Srdivacky    } else if (!ObjectType->isDependentType()) {
4069204643Srdivacky      // The user wrote "p->" when she probably meant "p."; fix it.
4070204643Srdivacky      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4071204643Srdivacky        << ObjectType << true
4072206084Srdivacky        << FixItHint::CreateReplacement(OpLoc, ".");
4073204643Srdivacky      if (isSFINAEContext())
4074204643Srdivacky        return ExprError();
4075218893Sdim
4076204643Srdivacky      OpKind = tok::period;
4077204643Srdivacky    }
4078204643Srdivacky  }
4079204643Srdivacky
4080204643Srdivacky  // Compute the object type that we should use for name lookup purposes. Only
4081204643Srdivacky  // record types and dependent types matter.
4082212904Sdim  ParsedType ObjectTypePtrForLookup;
4083204643Srdivacky  if (!SS.isSet()) {
4084219077Sdim    if (ObjectType->isRecordType())
4085219077Sdim      ObjectTypePtrForLookup = ParsedType::make(ObjectType);
4086212904Sdim    else if (ObjectType->isDependentType())
4087212904Sdim      ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
4088204643Srdivacky  }
4089218893Sdim
4090218893Sdim  // Convert the name of the type being destructed (following the ~) into a
4091204643Srdivacky  // type (with source-location information).
4092204643Srdivacky  QualType DestructedType;
4093204643Srdivacky  TypeSourceInfo *DestructedTypeInfo = 0;
4094204643Srdivacky  PseudoDestructorTypeStorage Destructed;
4095204643Srdivacky  if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
4096218893Sdim    ParsedType T = getTypeName(*SecondTypeName.Identifier,
4097212904Sdim                               SecondTypeName.StartLocation,
4098218893Sdim                               S, &SS, true, false, ObjectTypePtrForLookup);
4099218893Sdim    if (!T &&
4100204643Srdivacky        ((SS.isSet() && !computeDeclContext(SS, false)) ||
4101204643Srdivacky         (!SS.isSet() && ObjectType->isDependentType()))) {
4102218893Sdim      // The name of the type being destroyed is a dependent name, and we
4103204643Srdivacky      // couldn't find anything useful in scope. Just store the identifier and
4104204643Srdivacky      // it's location, and we'll perform (qualified) name lookup again at
4105204643Srdivacky      // template instantiation time.
4106204643Srdivacky      Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
4107204643Srdivacky                                               SecondTypeName.StartLocation);
4108204643Srdivacky    } else if (!T) {
4109218893Sdim      Diag(SecondTypeName.StartLocation,
4110204643Srdivacky           diag::err_pseudo_dtor_destructor_non_type)
4111204643Srdivacky        << SecondTypeName.Identifier << ObjectType;
4112204643Srdivacky      if (isSFINAEContext())
4113204643Srdivacky        return ExprError();
4114218893Sdim
4115204643Srdivacky      // Recover by assuming we had the right type all along.
4116204643Srdivacky      DestructedType = ObjectType;
4117204643Srdivacky    } else
4118204643Srdivacky      DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
4119204643Srdivacky  } else {
4120204643Srdivacky    // Resolve the template-id to a type.
4121204643Srdivacky    TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
4122204643Srdivacky    ASTTemplateArgsPtr TemplateArgsPtr(*this,
4123204643Srdivacky                                       TemplateId->getTemplateArgs(),
4124204643Srdivacky                                       TemplateId->NumArgs);
4125221345Sdim    TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4126221345Sdim                                       TemplateId->Template,
4127204643Srdivacky                                       TemplateId->TemplateNameLoc,
4128204643Srdivacky                                       TemplateId->LAngleLoc,
4129204643Srdivacky                                       TemplateArgsPtr,
4130204643Srdivacky                                       TemplateId->RAngleLoc);
4131204643Srdivacky    if (T.isInvalid() || !T.get()) {
4132204643Srdivacky      // Recover by assuming we had the right type all along.
4133204643Srdivacky      DestructedType = ObjectType;
4134204643Srdivacky    } else
4135204643Srdivacky      DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
4136204643Srdivacky  }
4137218893Sdim
4138218893Sdim  // If we've performed some kind of recovery, (re-)build the type source
4139204643Srdivacky  // information.
4140204643Srdivacky  if (!DestructedType.isNull()) {
4141204643Srdivacky    if (!DestructedTypeInfo)
4142204643Srdivacky      DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
4143204643Srdivacky                                                  SecondTypeName.StartLocation);
4144204643Srdivacky    Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4145204643Srdivacky  }
4146218893Sdim
4147204643Srdivacky  // Convert the name of the scope type (the type prior to '::') into a type.
4148204643Srdivacky  TypeSourceInfo *ScopeTypeInfo = 0;
4149204643Srdivacky  QualType ScopeType;
4150218893Sdim  if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
4151204643Srdivacky      FirstTypeName.Identifier) {
4152204643Srdivacky    if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
4153218893Sdim      ParsedType T = getTypeName(*FirstTypeName.Identifier,
4154212904Sdim                                 FirstTypeName.StartLocation,
4155219077Sdim                                 S, &SS, true, false, ObjectTypePtrForLookup);
4156204643Srdivacky      if (!T) {
4157218893Sdim        Diag(FirstTypeName.StartLocation,
4158204643Srdivacky             diag::err_pseudo_dtor_destructor_non_type)
4159204643Srdivacky          << FirstTypeName.Identifier << ObjectType;
4160218893Sdim
4161204643Srdivacky        if (isSFINAEContext())
4162204643Srdivacky          return ExprError();
4163218893Sdim
4164204643Srdivacky        // Just drop this type. It's unnecessary anyway.
4165204643Srdivacky        ScopeType = QualType();
4166204643Srdivacky      } else
4167204643Srdivacky        ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
4168204643Srdivacky    } else {
4169204643Srdivacky      // Resolve the template-id to a type.
4170204643Srdivacky      TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
4171204643Srdivacky      ASTTemplateArgsPtr TemplateArgsPtr(*this,
4172204643Srdivacky                                         TemplateId->getTemplateArgs(),
4173204643Srdivacky                                         TemplateId->NumArgs);
4174221345Sdim      TypeResult T = ActOnTemplateIdType(TemplateId->SS,
4175221345Sdim                                         TemplateId->Template,
4176204643Srdivacky                                         TemplateId->TemplateNameLoc,
4177204643Srdivacky                                         TemplateId->LAngleLoc,
4178204643Srdivacky                                         TemplateArgsPtr,
4179204643Srdivacky                                         TemplateId->RAngleLoc);
4180204643Srdivacky      if (T.isInvalid() || !T.get()) {
4181204643Srdivacky        // Recover by dropping this type.
4182204643Srdivacky        ScopeType = QualType();
4183204643Srdivacky      } else
4184218893Sdim        ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
4185204643Srdivacky    }
4186204643Srdivacky  }
4187218893Sdim
4188204643Srdivacky  if (!ScopeType.isNull() && !ScopeTypeInfo)
4189204643Srdivacky    ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
4190204643Srdivacky                                                  FirstTypeName.StartLocation);
4191204643Srdivacky
4192218893Sdim
4193212904Sdim  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
4194204643Srdivacky                                   ScopeTypeInfo, CCLoc, TildeLoc,
4195204643Srdivacky                                   Destructed, HasTrailingLParen);
4196204643Srdivacky}
4197204643Srdivacky
4198221345SdimExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
4199218893Sdim                                        CXXMethodDecl *Method) {
4200221345Sdim  ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
4201221345Sdim                                          FoundDecl, Method);
4202221345Sdim  if (Exp.isInvalid())
4203218893Sdim    return true;
4204200583Srdivacky
4205218893Sdim  MemberExpr *ME =
4206221345Sdim      new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
4207218893Sdim                               SourceLocation(), Method->getType(),
4208218893Sdim                               VK_RValue, OK_Ordinary);
4209218893Sdim  QualType ResultType = Method->getResultType();
4210218893Sdim  ExprValueKind VK = Expr::getValueKindForType(ResultType);
4211218893Sdim  ResultType = ResultType.getNonLValueExprType(Context);
4212218893Sdim
4213221345Sdim  MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
4214199990Srdivacky  CXXMemberCallExpr *CE =
4215218893Sdim    new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
4216221345Sdim                                    Exp.get()->getLocEnd());
4217198092Srdivacky  return CE;
4218198092Srdivacky}
4219198092Srdivacky
4220218893SdimExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4221218893Sdim                                      SourceLocation RParen) {
4222218893Sdim  return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
4223218893Sdim                                             Operand->CanThrow(Context),
4224218893Sdim                                             KeyLoc, RParen));
4225218893Sdim}
4226218893Sdim
4227218893SdimExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
4228218893Sdim                                   Expr *Operand, SourceLocation RParen) {
4229218893Sdim  return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
4230218893Sdim}
4231218893Sdim
4232218893Sdim/// Perform the conversions required for an expression used in a
4233218893Sdim/// context that ignores the result.
4234221345SdimExprResult Sema::IgnoredValueConversions(Expr *E) {
4235218893Sdim  // C99 6.3.2.1:
4236218893Sdim  //   [Except in specific positions,] an lvalue that does not have
4237218893Sdim  //   array type is converted to the value stored in the
4238218893Sdim  //   designated object (and is no longer an lvalue).
4239221345Sdim  if (E->isRValue()) return Owned(E);
4240218893Sdim
4241218893Sdim  // We always want to do this on ObjC property references.
4242218893Sdim  if (E->getObjectKind() == OK_ObjCProperty) {
4243221345Sdim    ExprResult Res = ConvertPropertyForRValue(E);
4244221345Sdim    if (Res.isInvalid()) return Owned(E);
4245221345Sdim    E = Res.take();
4246221345Sdim    if (E->isRValue()) return Owned(E);
4247218893Sdim  }
4248218893Sdim
4249218893Sdim  // Otherwise, this rule does not apply in C++, at least not for the moment.
4250221345Sdim  if (getLangOptions().CPlusPlus) return Owned(E);
4251218893Sdim
4252218893Sdim  // GCC seems to also exclude expressions of incomplete enum type.
4253218893Sdim  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
4254218893Sdim    if (!T->getDecl()->isComplete()) {
4255218893Sdim      // FIXME: stupid workaround for a codegen bug!
4256221345Sdim      E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
4257221345Sdim      return Owned(E);
4258218893Sdim    }
4259218893Sdim  }
4260218893Sdim
4261221345Sdim  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
4262221345Sdim  if (Res.isInvalid())
4263221345Sdim    return Owned(E);
4264221345Sdim  E = Res.take();
4265221345Sdim
4266218893Sdim  if (!E->getType()->isVoidType())
4267218893Sdim    RequireCompleteType(E->getExprLoc(), E->getType(),
4268218893Sdim                        diag::err_incomplete_type);
4269221345Sdim  return Owned(E);
4270218893Sdim}
4271218893Sdim
4272221345SdimExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
4273221345Sdim  ExprResult FullExpr = Owned(FE);
4274221345Sdim
4275221345Sdim  if (!FullExpr.get())
4276218893Sdim    return ExprError();
4277218893Sdim
4278221345Sdim  if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
4279218893Sdim    return ExprError();
4280218893Sdim
4281221345Sdim  FullExpr = CheckPlaceholderExpr(FullExpr.take());
4282221345Sdim  if (FullExpr.isInvalid())
4283221345Sdim    return ExprError();
4284221345Sdim
4285221345Sdim  FullExpr = IgnoredValueConversions(FullExpr.take());
4286221345Sdim  if (FullExpr.isInvalid())
4287221345Sdim    return ExprError();
4288221345Sdim
4289221345Sdim  CheckImplicitConversions(FullExpr.get());
4290218893Sdim  return MaybeCreateExprWithCleanups(FullExpr);
4291193326Sed}
4292218893Sdim
4293218893SdimStmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
4294218893Sdim  if (!FullStmt) return StmtError();
4295218893Sdim
4296218893Sdim  return MaybeCreateStmtWithCleanups(FullStmt);
4297218893Sdim}
4298