blob: 08a1b2a8e9c5031d9f0c15995c9dbfbb6ff26fa7 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000019#include "clang/AST/ExprCXX.h"
20#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Douglas Gregor124b8782010-02-16 19:09:40 +000027Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
28 IdentifierInfo &II,
29 SourceLocation NameLoc,
30 Scope *S, const CXXScopeSpec &SS,
31 TypeTy *ObjectTypePtr,
32 bool EnteringContext) {
33 // Determine where to perform name lookup.
34
35 // FIXME: This area of the standard is very messy, and the current
36 // wording is rather unclear about which scopes we search for the
37 // destructor name; see core issues 399 and 555. Issue 399 in
38 // particular shows where the current description of destructor name
39 // lookup is completely out of line with existing practice, e.g.,
40 // this appears to be ill-formed:
41 //
42 // namespace N {
43 // template <typename T> struct S {
44 // ~S();
45 // };
46 // }
47 //
48 // void f(N::S<int>* s) {
49 // s->N::S<int>::~S();
50 // }
51 //
52 //
53 QualType SearchType;
54 DeclContext *LookupCtx = 0;
55 bool isDependent = false;
56 bool LookInScope = false;
57
58 // If we have an object type, it's because we are in a
59 // pseudo-destructor-expression or a member access expression, and
60 // we know what type we're looking for.
61 if (ObjectTypePtr)
62 SearchType = GetTypeFromParser(ObjectTypePtr);
63
64 if (SS.isSet()) {
65 // C++ [basic.lookup.qual]p6:
66 // If a pseudo-destructor-name (5.2.4) contains a
67 // nested-name-specifier, the type-names are looked up as types
68 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth5e895a82010-02-21 10:19:54 +000069 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000070 //
71 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
72 //
73 // the second class-name is looked up in the same scope as the first.
74 //
Chandler Carruth5e895a82010-02-21 10:19:54 +000075 // FIXME: We don't implement this, because it breaks lots of
76 // perfectly reasonable code that no other compilers diagnose. The
77 // issue is that the first class-name is looked up as a
78 // nested-name-specifier, so we ignore value declarations, but the
79 // second lookup is presumably an ordinary name lookup. Hence, we
80 // end up finding values (say, a function) and complain. See PRs
81 // 6358 and 6359 for examples of such code. DPG to investigate
82 // further.
83 if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +000084 LookupCtx = computeDeclContext(SearchType);
85 isDependent = SearchType->isDependentType();
86 } else {
87 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregorb10cd042010-02-21 18:36:56 +000088 if (LookupCtx)
89 isDependent = LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +000090 }
91
Douglas Gregorb10cd042010-02-21 18:36:56 +000092 LookInScope = (LookupCtx == 0) && !isDependent;
Douglas Gregor124b8782010-02-16 19:09:40 +000093 } else if (ObjectTypePtr) {
94 // C++ [basic.lookup.classref]p3:
95 // If the unqualified-id is ~type-name, the type-name is looked up
96 // in the context of the entire postfix-expression. If the type T
97 // of the object expression is of a class type C, the type-name is
98 // also looked up in the scope of class C. At least one of the
99 // lookups shall find a name that refers to (possibly
100 // cv-qualified) T.
101 LookupCtx = computeDeclContext(SearchType);
102 isDependent = SearchType->isDependentType();
103 assert((isDependent || !SearchType->isIncompleteType()) &&
104 "Caller should have completed object type");
105
106 LookInScope = true;
107 } else {
108 // Perform lookup into the current scope (only).
109 LookInScope = true;
110 }
111
112 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
113 for (unsigned Step = 0; Step != 2; ++Step) {
114 // Look for the name first in the computed lookup context (if we
115 // have one) and, if that fails to find a match, in the sope (if
116 // we're allowed to look there).
117 Found.clear();
118 if (Step == 0 && LookupCtx)
119 LookupQualifiedName(Found, LookupCtx);
120 else if (Step == 1 && LookInScope)
121 LookupName(Found, S);
122 else
123 continue;
124
125 // FIXME: Should we be suppressing ambiguities here?
126 if (Found.isAmbiguous())
127 return 0;
128
129 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
130 QualType T = Context.getTypeDeclType(Type);
131 // If we found the injected-class-name of a class template, retrieve the
132 // type of that template.
133 // FIXME: We really shouldn't need to do this.
134 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Type))
135 if (Record->isInjectedClassName())
136 if (Record->getDescribedClassTemplate())
137 T = Record->getDescribedClassTemplate()
138 ->getInjectedClassNameType(Context);
139
140 if (SearchType.isNull() || SearchType->isDependentType() ||
141 Context.hasSameUnqualifiedType(T, SearchType)) {
142 // We found our type!
143
144 return T.getAsOpaquePtr();
145 }
146 }
147
148 // If the name that we found is a class template name, and it is
149 // the same name as the template name in the last part of the
150 // nested-name-specifier (if present) or the object type, then
151 // this is the destructor for that class.
152 // FIXME: This is a workaround until we get real drafting for core
153 // issue 399, for which there isn't even an obvious direction.
154 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
155 QualType MemberOfType;
156 if (SS.isSet()) {
157 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
158 // Figure out the type of the context, if it has one.
159 if (ClassTemplateSpecializationDecl *Spec
160 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx))
161 MemberOfType = Context.getTypeDeclType(Spec);
162 else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
163 if (Record->getDescribedClassTemplate())
164 MemberOfType = Record->getDescribedClassTemplate()
165 ->getInjectedClassNameType(Context);
166 else
167 MemberOfType = Context.getTypeDeclType(Record);
168 }
169 }
170 }
171 if (MemberOfType.isNull())
172 MemberOfType = SearchType;
173
174 if (MemberOfType.isNull())
175 continue;
176
177 // We're referring into a class template specialization. If the
178 // class template we found is the same as the template being
179 // specialized, we found what we are looking for.
180 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
181 if (ClassTemplateSpecializationDecl *Spec
182 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
183 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
184 Template->getCanonicalDecl())
185 return MemberOfType.getAsOpaquePtr();
186 }
187
188 continue;
189 }
190
191 // We're referring to an unresolved class template
192 // specialization. Determine whether we class template we found
193 // is the same as the template being specialized or, if we don't
194 // know which template is being specialized, that it at least
195 // has the same name.
196 if (const TemplateSpecializationType *SpecType
197 = MemberOfType->getAs<TemplateSpecializationType>()) {
198 TemplateName SpecName = SpecType->getTemplateName();
199
200 // The class template we found is the same template being
201 // specialized.
202 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
203 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
204 return MemberOfType.getAsOpaquePtr();
205
206 continue;
207 }
208
209 // The class template we found has the same name as the
210 // (dependent) template name being specialized.
211 if (DependentTemplateName *DepTemplate
212 = SpecName.getAsDependentTemplateName()) {
213 if (DepTemplate->isIdentifier() &&
214 DepTemplate->getIdentifier() == Template->getIdentifier())
215 return MemberOfType.getAsOpaquePtr();
216
217 continue;
218 }
219 }
220 }
221 }
222
223 if (isDependent) {
224 // We didn't find our type, but that's okay: it's dependent
225 // anyway.
226 NestedNameSpecifier *NNS = 0;
227 SourceRange Range;
228 if (SS.isSet()) {
229 NNS = (NestedNameSpecifier *)SS.getScopeRep();
230 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
231 } else {
232 NNS = NestedNameSpecifier::Create(Context, &II);
233 Range = SourceRange(NameLoc);
234 }
235
236 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
237 }
238
239 if (ObjectTypePtr)
240 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
241 << &II;
242 else
243 Diag(NameLoc, diag::err_destructor_class_name);
244
245 return 0;
246}
247
Sebastian Redlc42e1182008-11-11 11:37:55 +0000248/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +0000249Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000250Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
251 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000252 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000253 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000254
Douglas Gregorf57f2072009-12-23 20:51:04 +0000255 if (isType) {
256 // C++ [expr.typeid]p4:
257 // The top-level cv-qualifiers of the lvalue expression or the type-id
258 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000259 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +0000260 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +0000261 QualType T = GetTypeFromParser(TyOrExpr);
262 if (T.isNull())
263 return ExprError();
264
265 // C++ [expr.typeid]p4:
266 // If the type of the type-id is a class type or a reference to a class
267 // type, the class shall be completely-defined.
268 QualType CheckT = T;
269 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
270 CheckT = RefType->getPointeeType();
271
272 if (CheckT->getAs<RecordType>() &&
273 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
274 return ExprError();
275
276 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +0000277 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000278
Chris Lattner572af492008-11-20 05:51:55 +0000279 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000280 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
281 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000282 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000283 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000284 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000285
286 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
287
Douglas Gregorac7610d2009-06-22 20:57:11 +0000288 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000289 bool isUnevaluatedOperand = true;
290 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +0000291 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000292 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000293 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000294 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +0000295 // C++ [expr.typeid]p3:
John McCall86ff3082010-02-04 22:26:26 +0000296 // [...] If the type of the expression is a class type, the class
297 // shall be completely-defined.
298 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
299 return ExprError();
300
301 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +0000302 // When typeid is applied to an expression other than an lvalue of a
303 // polymorphic class type [...] [the] expression is an unevaluated
304 // operand. [...]
305 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +0000306 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +0000307 }
308
309 // C++ [expr.typeid]p4:
310 // [...] If the type of the type-id is a reference to a possibly
311 // cv-qualified type, the result of the typeid expression refers to a
312 // std::type_info object representing the cv-unqualified referenced
313 // type.
314 if (T.hasQualifiers()) {
315 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
316 E->isLvalue(Context));
317 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000318 }
319 }
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Douglas Gregor2afce722009-11-26 00:44:06 +0000321 // If this is an unevaluated operand, clear out the set of
322 // declaration references we have been computing and eliminate any
323 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000324 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000325 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Sebastian Redlf53597f2009-03-15 17:47:39 +0000328 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
329 TypeInfoType.withConst(),
330 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000331}
332
Steve Naroff1b273c42007-09-16 14:56:35 +0000333/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000334Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000335Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000336 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000338 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
339 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000340}
Chris Lattner50dd2892008-02-26 00:51:44 +0000341
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000342/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
343Action::OwningExprResult
344Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
345 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
346}
347
Chris Lattner50dd2892008-02-26 00:51:44 +0000348/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000349Action::OwningExprResult
350Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000351 Expr *Ex = E.takeAs<Expr>();
352 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
353 return ExprError();
354 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
355}
356
357/// CheckCXXThrowOperand - Validate the operand of a throw.
358bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
359 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000360 // A throw-expression initializes a temporary object, called the exception
361 // object, the type of which is determined by removing any top-level
362 // cv-qualifiers from the static type of the operand of throw and adjusting
363 // the type from "array of T" or "function returning T" to "pointer to T"
364 // or "pointer to function returning T", [...]
365 if (E->getType().hasQualifiers())
366 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
367 E->isLvalue(Context) == Expr::LV_Valid);
368
Sebastian Redl972041f2009-04-27 20:27:31 +0000369 DefaultFunctionArrayConversion(E);
370
371 // If the type of the exception would be an incomplete type or a pointer
372 // to an incomplete type other than (cv) void the program is ill-formed.
373 QualType Ty = E->getType();
374 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000375 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000376 Ty = Ptr->getPointeeType();
377 isPointer = 1;
378 }
379 if (!isPointer || !Ty->isVoidType()) {
380 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000381 PDiag(isPointer ? diag::err_throw_incomplete_ptr
382 : diag::err_throw_incomplete)
383 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000384 return true;
385 }
386
387 // FIXME: Construct a temporary here.
388 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000389}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000390
Sebastian Redlf53597f2009-03-15 17:47:39 +0000391Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000392 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
393 /// is a non-lvalue expression whose value is the address of the object for
394 /// which the function is called.
395
Sebastian Redlf53597f2009-03-15 17:47:39 +0000396 if (!isa<FunctionDecl>(CurContext))
397 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000398
399 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
400 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000401 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000402 MD->getThisType(Context),
403 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000404
Sebastian Redlf53597f2009-03-15 17:47:39 +0000405 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000406}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000407
408/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
409/// Can be interpreted either as function-style casting ("int(x)")
410/// or class type construction ("ClassType(x,y,z)")
411/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000412Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000413Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
414 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000415 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000416 SourceLocation *CommaLocs,
417 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000418 if (!TypeRep)
419 return ExprError();
420
John McCall9d125032010-01-15 18:39:57 +0000421 TypeSourceInfo *TInfo;
422 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
423 if (!TInfo)
424 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000425 unsigned NumExprs = exprs.size();
426 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000427 SourceLocation TyBeginLoc = TypeRange.getBegin();
428 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
429
Sebastian Redlf53597f2009-03-15 17:47:39 +0000430 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000431 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000432 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
434 return Owned(CXXUnresolvedConstructExpr::Create(Context,
435 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000436 LParenLoc,
437 Exprs, NumExprs,
438 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000439 }
440
Anders Carlssonbb60a502009-08-27 03:53:50 +0000441 if (Ty->isArrayType())
442 return ExprError(Diag(TyBeginLoc,
443 diag::err_value_init_for_array_type) << FullRange);
444 if (!Ty->isVoidType() &&
445 RequireCompleteType(TyBeginLoc, Ty,
446 PDiag(diag::err_invalid_incomplete_type_use)
447 << FullRange))
448 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000449
Anders Carlssonbb60a502009-08-27 03:53:50 +0000450 if (RequireNonAbstractType(TyBeginLoc, Ty,
451 diag::err_allocation_of_abstract_type))
452 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000453
454
Douglas Gregor506ae412009-01-16 18:33:17 +0000455 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000456 // If the expression list is a single expression, the type conversion
457 // expression is equivalent (in definedness, and if defined in meaning) to the
458 // corresponding cast expression.
459 //
460 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000461 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000462 CXXMethodDecl *Method = 0;
463 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
464 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000465 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000466
467 exprs.release();
468 if (Method) {
469 OwningExprResult CastArg
470 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
471 Kind, Method, Owned(Exprs[0]));
472 if (CastArg.isInvalid())
473 return ExprError();
474
475 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000476 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000477
478 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000479 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000480 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000481 }
482
Ted Kremenek6217b802009-07-29 21:53:49 +0000483 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000484 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000485
Mike Stump1eb44332009-09-09 15:08:12 +0000486 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000487 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000488 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
489 InitializationKind Kind
490 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
491 LParenLoc, RParenLoc)
492 : InitializationKind::CreateValue(TypeRange.getBegin(),
493 LParenLoc, RParenLoc);
494 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
495 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
496 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000497
Eli Friedman6997aae2010-01-31 20:58:15 +0000498 // FIXME: Improve AST representation?
499 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000500 }
501
502 // Fall through to value-initialize an object of class type that
503 // doesn't have a user-declared default constructor.
504 }
505
506 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000507 // If the expression list specifies more than a single value, the type shall
508 // be a class with a suitably declared constructor.
509 //
510 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000511 return ExprError(Diag(CommaLocs[0],
512 diag::err_builtin_func_cast_more_than_one_arg)
513 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000514
515 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000516 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000517 // The expression T(), where T is a simple-type-specifier for a non-array
518 // complete object type or the (possibly cv-qualified) void type, creates an
519 // rvalue of the specified type, which is value-initialized.
520 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000521 exprs.release();
522 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000523}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000524
525
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000526/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
527/// @code new (memory) int[size][4] @endcode
528/// or
529/// @code ::new Foo(23, "hello") @endcode
530/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000531Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000532Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000533 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000534 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000535 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000536 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000537 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000538 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000539 // If the specified type is an array, unwrap it and save the expression.
540 if (D.getNumTypeObjects() > 0 &&
541 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
542 DeclaratorChunk &Chunk = D.getTypeObject(0);
543 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000544 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
545 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000546 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000547 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
548 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000549
550 if (ParenTypeId) {
551 // Can't have dynamic array size when the type-id is in parentheses.
552 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
553 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
554 !NumElts->isIntegerConstantExpr(Context)) {
555 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
556 << NumElts->getSourceRange();
557 return ExprError();
558 }
559 }
560
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000561 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000562 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000563 }
564
Douglas Gregor043cad22009-09-11 00:18:58 +0000565 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000566 if (ArraySize) {
567 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000568 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
569 break;
570
571 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
572 if (Expr *NumElts = (Expr *)Array.NumElts) {
573 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
574 !NumElts->isIntegerConstantExpr(Context)) {
575 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
576 << NumElts->getSourceRange();
577 return ExprError();
578 }
579 }
580 }
581 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000582
John McCalla93c9342009-12-07 02:54:59 +0000583 //FIXME: Store TypeSourceInfo in CXXNew expression.
584 TypeSourceInfo *TInfo = 0;
585 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000586 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000587 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000588
Mike Stump1eb44332009-09-09 15:08:12 +0000589 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000590 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000591 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000592 PlacementRParen,
593 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000594 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000595 D.getSourceRange().getBegin(),
596 D.getSourceRange(),
597 Owned(ArraySize),
598 ConstructorLParen,
599 move(ConstructorArgs),
600 ConstructorRParen);
601}
602
Mike Stump1eb44332009-09-09 15:08:12 +0000603Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000604Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
605 SourceLocation PlacementLParen,
606 MultiExprArg PlacementArgs,
607 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000608 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000609 QualType AllocType,
610 SourceLocation TypeLoc,
611 SourceRange TypeRange,
612 ExprArg ArraySizeE,
613 SourceLocation ConstructorLParen,
614 MultiExprArg ConstructorArgs,
615 SourceLocation ConstructorRParen) {
616 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000617 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000618
Douglas Gregor3433cf72009-05-21 00:00:09 +0000619 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000620
621 // That every array dimension except the first is constant was already
622 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000623
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000624 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
625 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000626 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000627 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000628 QualType SizeType = ArraySize->getType();
629 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000630 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
631 diag::err_array_size_not_integral)
632 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000633 // Let's see if this is a constant < 0. If so, we reject it out of hand.
634 // We don't care about special rules, so we tell the machinery it's not
635 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000636 if (!ArraySize->isValueDependent()) {
637 llvm::APSInt Value;
638 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
639 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000640 llvm::APInt::getNullValue(Value.getBitWidth()),
641 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000642 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
643 diag::err_typecheck_negative_array_size)
644 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000645 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000646 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000647
Eli Friedman73c39ab2009-10-20 08:27:19 +0000648 ImpCastExprToType(ArraySize, Context.getSizeType(),
649 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000650 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000651
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000652 FunctionDecl *OperatorNew = 0;
653 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000654 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
655 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000656
Sebastian Redl28507842009-02-26 14:39:58 +0000657 if (!AllocType->isDependentType() &&
658 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
659 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000660 SourceRange(PlacementLParen, PlacementRParen),
661 UseGlobal, AllocType, ArraySize, PlaceArgs,
662 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000663 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000664 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000665 if (OperatorNew) {
666 // Add default arguments, if any.
667 const FunctionProtoType *Proto =
668 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000669 VariadicCallType CallType =
670 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000671 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
672 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000673 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000674 if (Invalid)
675 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000676
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000677 NumPlaceArgs = AllPlaceArgs.size();
678 if (NumPlaceArgs > 0)
679 PlaceArgs = &AllPlaceArgs[0];
680 }
681
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000682 bool Init = ConstructorLParen.isValid();
683 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000684 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000685 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
686 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000687 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
688
Douglas Gregor99a2e602009-12-16 01:38:02 +0000689 if (!AllocType->isDependentType() &&
690 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
691 // C++0x [expr.new]p15:
692 // A new-expression that creates an object of type T initializes that
693 // object as follows:
694 InitializationKind Kind
695 // - If the new-initializer is omitted, the object is default-
696 // initialized (8.5); if no initialization is performed,
697 // the object has indeterminate value
698 = !Init? InitializationKind::CreateDefault(TypeLoc)
699 // - Otherwise, the new-initializer is interpreted according to the
700 // initialization rules of 8.5 for direct-initialization.
701 : InitializationKind::CreateDirect(TypeLoc,
702 ConstructorLParen,
703 ConstructorRParen);
704
Douglas Gregor99a2e602009-12-16 01:38:02 +0000705 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000706 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000707 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000708 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
709 move(ConstructorArgs));
710 if (FullInit.isInvalid())
711 return ExprError();
712
713 // FullInit is our initializer; walk through it to determine if it's a
714 // constructor call, which CXXNewExpr handles directly.
715 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
716 if (CXXBindTemporaryExpr *Binder
717 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
718 FullInitExpr = Binder->getSubExpr();
719 if (CXXConstructExpr *Construct
720 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
721 Constructor = Construct->getConstructor();
722 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
723 AEnd = Construct->arg_end();
724 A != AEnd; ++A)
725 ConvertedConstructorArgs.push_back(A->Retain());
726 } else {
727 // Take the converted initializer.
728 ConvertedConstructorArgs.push_back(FullInit.release());
729 }
730 } else {
731 // No initialization required.
732 }
733
734 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000735 NumConsArgs = ConvertedConstructorArgs.size();
736 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000737 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000738
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000739 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000740
Sebastian Redlf53597f2009-03-15 17:47:39 +0000741 PlacementArgs.release();
742 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000743 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000744 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
745 PlaceArgs, NumPlaceArgs, ParenTypeId,
746 ArraySize, Constructor, Init,
747 ConsArgs, NumConsArgs, OperatorDelete,
748 ResultType, StartLoc,
749 Init ? ConstructorRParen :
750 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000751}
752
753/// CheckAllocatedType - Checks that a type is suitable as the allocated type
754/// in a new-expression.
755/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000756bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000757 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000758 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
759 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000760 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000761 return Diag(Loc, diag::err_bad_new_type)
762 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000763 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000764 return Diag(Loc, diag::err_bad_new_type)
765 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000766 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000767 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000768 PDiag(diag::err_new_incomplete_type)
769 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000770 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000771 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000772 diag::err_allocation_of_abstract_type))
773 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000774
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000775 return false;
776}
777
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000778/// FindAllocationFunctions - Finds the overloads of operator new and delete
779/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000780bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
781 bool UseGlobal, QualType AllocType,
782 bool IsArray, Expr **PlaceArgs,
783 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000784 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000785 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000786 // --- Choosing an allocation function ---
787 // C++ 5.3.4p8 - 14 & 18
788 // 1) If UseGlobal is true, only look in the global scope. Else, also look
789 // in the scope of the allocated class.
790 // 2) If an array size is given, look for operator new[], else look for
791 // operator new.
792 // 3) The first argument is always size_t. Append the arguments from the
793 // placement form.
794 // FIXME: Also find the appropriate delete operator.
795
796 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
797 // We don't care about the actual value of this argument.
798 // FIXME: Should the Sema create the expression and embed it in the syntax
799 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000800 IntegerLiteral Size(llvm::APInt::getNullValue(
801 Context.Target.getPointerWidth(0)),
802 Context.getSizeType(),
803 SourceLocation());
804 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000805 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
806
807 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
808 IsArray ? OO_Array_New : OO_New);
809 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000810 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000811 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000812 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000813 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000814 AllocArgs.size(), Record, /*AllowMissing=*/true,
815 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000816 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000817 }
818 if (!OperatorNew) {
819 // Didn't find a member overload. Look for a global one.
820 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000821 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000822 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000823 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
824 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000825 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000826 }
827
Anders Carlssond9583892009-05-31 20:26:12 +0000828 // FindAllocationOverload can change the passed in arguments, so we need to
829 // copy them back.
830 if (NumPlaceArgs > 0)
831 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000833 return false;
834}
835
Sebastian Redl7f662392008-12-04 22:20:51 +0000836/// FindAllocationOverload - Find an fitting overload for the allocation
837/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000838bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
839 DeclarationName Name, Expr** Args,
840 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000841 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000842 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
843 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000844 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000845 if (AllowMissing)
846 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000847 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000848 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000849 }
850
John McCallf36e02d2009-10-09 21:13:30 +0000851 // FIXME: handle ambiguity
852
John McCall5769d612010-02-08 23:07:23 +0000853 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000854 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
855 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000856 // Even member operator new/delete are implicitly treated as
857 // static, so don't use AddMemberCandidate.
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000858
859 if (FunctionTemplateDecl *FnTemplate =
860 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
861 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
862 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
863 Candidates,
864 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000865 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000866 }
867
868 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
869 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
870 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000871 }
872
873 // Do the resolution.
874 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000875 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000876 case OR_Success: {
877 // Got one!
878 FunctionDecl *FnDecl = Best->Function;
879 // The first argument is size_t, and the first parameter must be size_t,
880 // too. This is checked on declaration and can be assumed. (It can't be
881 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000882 // Whatch out for variadic allocator function.
883 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
884 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000885 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000886 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000887 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000888 return true;
889 }
890 Operator = FnDecl;
891 return false;
892 }
893
894 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000895 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000896 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000897 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000898 return true;
899
900 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000901 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000902 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000903 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000904 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000905
906 case OR_Deleted:
907 Diag(StartLoc, diag::err_ovl_deleted_call)
908 << Best->Function->isDeleted()
909 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000910 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000911 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000912 }
913 assert(false && "Unreachable, bad result from BestViableFunction");
914 return true;
915}
916
917
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000918/// DeclareGlobalNewDelete - Declare the global forms of operator new and
919/// delete. These are:
920/// @code
921/// void* operator new(std::size_t) throw(std::bad_alloc);
922/// void* operator new[](std::size_t) throw(std::bad_alloc);
923/// void operator delete(void *) throw();
924/// void operator delete[](void *) throw();
925/// @endcode
926/// Note that the placement and nothrow forms of new are *not* implicitly
927/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000928void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000929 if (GlobalNewDeleteDeclared)
930 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000931
932 // C++ [basic.std.dynamic]p2:
933 // [...] The following allocation and deallocation functions (18.4) are
934 // implicitly declared in global scope in each translation unit of a
935 // program
936 //
937 // void* operator new(std::size_t) throw(std::bad_alloc);
938 // void* operator new[](std::size_t) throw(std::bad_alloc);
939 // void operator delete(void*) throw();
940 // void operator delete[](void*) throw();
941 //
942 // These implicit declarations introduce only the function names operator
943 // new, operator new[], operator delete, operator delete[].
944 //
945 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
946 // "std" or "bad_alloc" as necessary to form the exception specification.
947 // However, we do not make these implicit declarations visible to name
948 // lookup.
949 if (!StdNamespace) {
950 // The "std" namespace has not yet been defined, so build one implicitly.
951 StdNamespace = NamespaceDecl::Create(Context,
952 Context.getTranslationUnitDecl(),
953 SourceLocation(),
954 &PP.getIdentifierTable().get("std"));
955 StdNamespace->setImplicit(true);
956 }
957
958 if (!StdBadAlloc) {
959 // The "std::bad_alloc" class has not yet been declared, so build it
960 // implicitly.
961 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
962 StdNamespace,
963 SourceLocation(),
964 &PP.getIdentifierTable().get("bad_alloc"),
965 SourceLocation(), 0);
966 StdBadAlloc->setImplicit(true);
967 }
968
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000969 GlobalNewDeleteDeclared = true;
970
971 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
972 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +0000973 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000974
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000975 DeclareGlobalAllocationFunction(
976 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000977 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000978 DeclareGlobalAllocationFunction(
979 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000980 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000981 DeclareGlobalAllocationFunction(
982 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
983 Context.VoidTy, VoidPtr);
984 DeclareGlobalAllocationFunction(
985 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
986 Context.VoidTy, VoidPtr);
987}
988
989/// DeclareGlobalAllocationFunction - Declares a single implicit global
990/// allocation function if it doesn't already exist.
991void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +0000992 QualType Return, QualType Argument,
993 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000994 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
995
996 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000997 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000998 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000999 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001000 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001001 // Only look at non-template functions, as it is the predefined,
1002 // non-templated allocation function we are trying to declare here.
1003 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1004 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001005 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001006 Func->getParamDecl(0)->getType().getUnqualifiedType());
1007 // FIXME: Do we need to check for default arguments here?
1008 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1009 return;
1010 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001011 }
1012 }
1013
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001014 QualType BadAllocType;
1015 bool HasBadAllocExceptionSpec
1016 = (Name.getCXXOverloadedOperator() == OO_New ||
1017 Name.getCXXOverloadedOperator() == OO_Array_New);
1018 if (HasBadAllocExceptionSpec) {
1019 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1020 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1021 }
1022
1023 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1024 true, false,
1025 HasBadAllocExceptionSpec? 1 : 0,
Douglas Gregorce056bc2010-02-21 22:15:06 +00001026 &BadAllocType, false, CC_Default);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001027 FunctionDecl *Alloc =
1028 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +00001029 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001030 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001031
1032 if (AddMallocAttr)
1033 Alloc->addAttr(::new (Context) MallocAttr());
1034
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001035 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001036 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001037 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001038 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001039
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001040 // FIXME: Also add this declaration to the IdentifierResolver, but
1041 // make sure it is at the end of the chain to coincide with the
1042 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001043 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001044}
1045
Anders Carlsson78f74552009-11-15 18:45:20 +00001046bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1047 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001048 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001049 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001050 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001051 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001052
John McCalla24dc2e2009-11-17 02:14:36 +00001053 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001054 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001055
1056 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1057 F != FEnd; ++F) {
1058 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1059 if (Delete->isUsualDeallocationFunction()) {
1060 Operator = Delete;
1061 return false;
1062 }
1063 }
1064
1065 // We did find operator delete/operator delete[] declarations, but
1066 // none of them were suitable.
1067 if (!Found.empty()) {
1068 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1069 << Name << RD;
1070
1071 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1072 F != FEnd; ++F) {
1073 Diag((*F)->getLocation(),
1074 diag::note_delete_member_function_declared_here)
1075 << Name;
1076 }
1077
1078 return true;
1079 }
1080
1081 // Look for a global declaration.
1082 DeclareGlobalNewDelete();
1083 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1084
1085 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1086 Expr* DeallocArgs[1];
1087 DeallocArgs[0] = &Null;
1088 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1089 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1090 Operator))
1091 return true;
1092
1093 assert(Operator && "Did not find a deallocation function!");
1094 return false;
1095}
1096
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001097/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1098/// @code ::delete ptr; @endcode
1099/// or
1100/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001101Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001102Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001103 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001104 // C++ [expr.delete]p1:
1105 // The operand shall have a pointer type, or a class type having a single
1106 // conversion function to a pointer type. The result has type void.
1107 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001108 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1109
Anders Carlssond67c4c32009-08-16 20:29:29 +00001110 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Sebastian Redlf53597f2009-03-15 17:47:39 +00001112 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001113 if (!Ex->isTypeDependent()) {
1114 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001115
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001116 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001117 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +00001118 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00001119 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001120
John McCalleec51cf2010-01-20 00:46:10 +00001121 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001122 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001123 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +00001124 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001125 continue;
1126
John McCallba135432009-11-21 08:51:07 +00001127 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001128
1129 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1130 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1131 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001132 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001133 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001134 if (ObjectPtrConversions.size() == 1) {
1135 // We have a single conversion to a pointer-to-object type. Perform
1136 // that conversion.
1137 Operand.release();
1138 if (!PerformImplicitConversion(Ex,
1139 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001140 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001141 Operand = Owned(Ex);
1142 Type = Ex->getType();
1143 }
1144 }
1145 else if (ObjectPtrConversions.size() > 1) {
1146 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1147 << Type << Ex->getSourceRange();
1148 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
1149 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +00001150 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001151 }
1152 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001153 }
Sebastian Redl28507842009-02-26 14:39:58 +00001154 }
1155
Sebastian Redlf53597f2009-03-15 17:47:39 +00001156 if (!Type->isPointerType())
1157 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1158 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001159
Ted Kremenek6217b802009-07-29 21:53:49 +00001160 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001161 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001162 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1163 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001164 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001165 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001166 PDiag(diag::warn_delete_incomplete)
1167 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001168 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001169
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001170 // C++ [expr.delete]p2:
1171 // [Note: a pointer to a const type can be the operand of a
1172 // delete-expression; it is not necessary to cast away the constness
1173 // (5.2.11) of the pointer expression before it is used as the operand
1174 // of the delete-expression. ]
1175 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1176 CastExpr::CK_NoOp);
1177
1178 // Update the operand.
1179 Operand.take();
1180 Operand = ExprArg(*this, Ex);
1181
Anders Carlssond67c4c32009-08-16 20:29:29 +00001182 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1183 ArrayForm ? OO_Array_Delete : OO_Delete);
1184
Anders Carlsson78f74552009-11-15 18:45:20 +00001185 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1186 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1187
1188 if (!UseGlobal &&
1189 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001190 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001191
Anders Carlsson78f74552009-11-15 18:45:20 +00001192 if (!RD->hasTrivialDestructor())
1193 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001194 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001195 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001196 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001197
Anders Carlssond67c4c32009-08-16 20:29:29 +00001198 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001199 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001200 DeclareGlobalNewDelete();
1201 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001202 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001203 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001204 OperatorDelete))
1205 return ExprError();
1206 }
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Sebastian Redl28507842009-02-26 14:39:58 +00001208 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001209 }
1210
Sebastian Redlf53597f2009-03-15 17:47:39 +00001211 Operand.release();
1212 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001213 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001214}
1215
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001216/// \brief Check the use of the given variable as a C++ condition in an if,
1217/// while, do-while, or switch statement.
1218Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1219 QualType T = ConditionVar->getType();
1220
1221 // C++ [stmt.select]p2:
1222 // The declarator shall not specify a function or an array.
1223 if (T->isFunctionType())
1224 return ExprError(Diag(ConditionVar->getLocation(),
1225 diag::err_invalid_use_of_function_type)
1226 << ConditionVar->getSourceRange());
1227 else if (T->isArrayType())
1228 return ExprError(Diag(ConditionVar->getLocation(),
1229 diag::err_invalid_use_of_array_type)
1230 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001231
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001232 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1233 ConditionVar->getLocation(),
1234 ConditionVar->getType().getNonReferenceType()));
1235}
1236
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001237/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1238bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1239 // C++ 6.4p4:
1240 // The value of a condition that is an initialized declaration in a statement
1241 // other than a switch statement is the value of the declared variable
1242 // implicitly converted to type bool. If that conversion is ill-formed, the
1243 // program is ill-formed.
1244 // The value of a condition that is an expression is the value of the
1245 // expression, implicitly converted to bool.
1246 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001247 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001248}
Douglas Gregor77a52232008-09-12 00:47:35 +00001249
1250/// Helper function to determine whether this is the (deprecated) C++
1251/// conversion from a string literal to a pointer to non-const char or
1252/// non-const wchar_t (for narrow and wide string literals,
1253/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001254bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001255Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1256 // Look inside the implicit cast, if it exists.
1257 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1258 From = Cast->getSubExpr();
1259
1260 // A string literal (2.13.4) that is not a wide string literal can
1261 // be converted to an rvalue of type "pointer to char"; a wide
1262 // string literal can be converted to an rvalue of type "pointer
1263 // to wchar_t" (C++ 4.2p2).
1264 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001265 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001266 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001267 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001268 // This conversion is considered only when there is an
1269 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001270 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001271 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1272 (!StrLit->isWide() &&
1273 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1274 ToPointeeType->getKind() == BuiltinType::Char_S))))
1275 return true;
1276 }
1277
1278 return false;
1279}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001280
1281/// PerformImplicitConversion - Perform an implicit conversion of the
1282/// expression From to the type ToType. Returns true if there was an
1283/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001284/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001285/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001286/// explicit user-defined conversions are permitted. @p Elidable should be true
1287/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1288/// resolution works differently in that case.
1289bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001290Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001291 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001292 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001293 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001294 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001295 Elidable, ICS);
1296}
1297
1298bool
1299Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001300 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001301 bool Elidable,
1302 ImplicitConversionSequence& ICS) {
John McCall1d318332010-01-12 00:44:57 +00001303 ICS.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001304 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001305 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001306 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001307 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001308 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001309 /*ForceRValue=*/true,
1310 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001311 }
John McCall1d318332010-01-12 00:44:57 +00001312 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001313 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001314 /*SuppressUserConversions=*/false,
1315 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001316 /*ForceRValue=*/false,
1317 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001318 }
Douglas Gregor68647482009-12-16 03:45:30 +00001319 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001320}
1321
1322/// PerformImplicitConversion - Perform an implicit conversion of the
1323/// expression From to the type ToType using the pre-computed implicit
1324/// conversion sequence ICS. Returns true if there was an error, false
1325/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001326/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001327/// used in the error message.
1328bool
1329Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1330 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001331 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001332 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001333 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001334 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001335 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001336 return true;
1337 break;
1338
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001339 case ImplicitConversionSequence::UserDefinedConversion: {
1340
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001341 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1342 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001343 QualType BeforeToType;
1344 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001345 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001346
1347 // If the user-defined conversion is specified by a conversion function,
1348 // the initial standard conversion sequence converts the source type to
1349 // the implicit object parameter of the conversion function.
1350 BeforeToType = Context.getTagDeclType(Conv->getParent());
1351 } else if (const CXXConstructorDecl *Ctor =
1352 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001353 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001354 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001355 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001356 // If the user-defined conversion is specified by a constructor, the
1357 // initial standard conversion sequence converts the source type to the
1358 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001359 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1360 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001361 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001362 else
1363 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001364 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001365 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001366 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001367 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001368 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001369 return true;
1370 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001371
Anders Carlsson0aebc812009-09-09 21:33:21 +00001372 OwningExprResult CastArg
1373 = BuildCXXCastArgument(From->getLocStart(),
1374 ToType.getNonReferenceType(),
1375 CastKind, cast<CXXMethodDecl>(FD),
1376 Owned(From));
1377
1378 if (CastArg.isInvalid())
1379 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001380
1381 From = CastArg.takeAs<Expr>();
1382
Eli Friedmand8889622009-11-27 04:41:50 +00001383 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001384 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001385 }
John McCall1d318332010-01-12 00:44:57 +00001386
1387 case ImplicitConversionSequence::AmbiguousConversion:
1388 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1389 PDiag(diag::err_typecheck_ambiguous_condition)
1390 << From->getSourceRange());
1391 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001392
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001393 case ImplicitConversionSequence::EllipsisConversion:
1394 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001395 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001396
1397 case ImplicitConversionSequence::BadConversion:
1398 return true;
1399 }
1400
1401 // Everything went well.
1402 return false;
1403}
1404
1405/// PerformImplicitConversion - Perform an implicit conversion of the
1406/// expression From to the type ToType by following the standard
1407/// conversion sequence SCS. Returns true if there was an error, false
1408/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001409/// expression. Flavor is the context in which we're performing this
1410/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001411bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001412Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001413 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001414 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001415 // Overall FIXME: we are recomputing too many types here and doing far too
1416 // much extra work. What this means is that we need to keep track of more
1417 // information that is computed when we try the implicit conversion initially,
1418 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001419 QualType FromType = From->getType();
1420
Douglas Gregor225c41e2008-11-03 19:09:14 +00001421 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001422 // FIXME: When can ToType be a reference type?
1423 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001424 if (SCS.Second == ICK_Derived_To_Base) {
1425 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1426 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1427 MultiExprArg(*this, (void **)&From, 1),
1428 /*FIXME:ConstructLoc*/SourceLocation(),
1429 ConstructorArgs))
1430 return true;
1431 OwningExprResult FromResult =
1432 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1433 ToType, SCS.CopyConstructor,
1434 move_arg(ConstructorArgs));
1435 if (FromResult.isInvalid())
1436 return true;
1437 From = FromResult.takeAs<Expr>();
1438 return false;
1439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440 OwningExprResult FromResult =
1441 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1442 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001443 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001445 if (FromResult.isInvalid())
1446 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001448 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001449 return false;
1450 }
1451
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001452 // Perform the first implicit conversion.
1453 switch (SCS.First) {
1454 case ICK_Identity:
1455 case ICK_Lvalue_To_Rvalue:
1456 // Nothing to do.
1457 break;
1458
1459 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001460 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001461 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001462 break;
1463
1464 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001465 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001466 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1467 if (!Fn)
1468 return true;
1469
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001470 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1471 return true;
1472
Anders Carlsson96ad5332009-10-21 17:16:23 +00001473 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001474 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001475
Sebastian Redl759986e2009-10-17 20:50:27 +00001476 // If there's already an address-of operator in the expression, we have
1477 // the right type already, and the code below would just introduce an
1478 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001479 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001480 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001481 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001482 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001483 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001484 break;
1485
1486 default:
1487 assert(false && "Improper first standard conversion");
1488 break;
1489 }
1490
1491 // Perform the second implicit conversion
1492 switch (SCS.Second) {
1493 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001494 // If both sides are functions (or pointers/references to them), there could
1495 // be incompatible exception declarations.
1496 if (CheckExceptionSpecCompatibility(From, ToType))
1497 return true;
1498 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001499 break;
1500
Douglas Gregor43c79c22009-12-09 00:47:37 +00001501 case ICK_NoReturn_Adjustment:
1502 // If both sides are functions (or pointers/references to them), there could
1503 // be incompatible exception declarations.
1504 if (CheckExceptionSpecCompatibility(From, ToType))
1505 return true;
1506
1507 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1508 CastExpr::CK_NoOp);
1509 break;
1510
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001511 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001512 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001513 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1514 break;
1515
1516 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001517 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001518 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1519 break;
1520
1521 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001522 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001523 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1524 break;
1525
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001526 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001527 if (ToType->isFloatingType())
1528 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1529 else
1530 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1531 break;
1532
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001533 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001534 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1535 break;
1536
Douglas Gregorf9201e02009-02-11 23:02:49 +00001537 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001538 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001539 break;
1540
Anders Carlsson61faec12009-09-12 04:46:44 +00001541 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001542 if (SCS.IncompatibleObjC) {
1543 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001544 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001545 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001546 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001547 << From->getSourceRange();
1548 }
1549
Anders Carlsson61faec12009-09-12 04:46:44 +00001550
1551 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001552 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001553 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001554 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001555 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001556 }
1557
1558 case ICK_Pointer_Member: {
1559 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001560 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001561 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001562 if (CheckExceptionSpecCompatibility(From, ToType))
1563 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001564 ImpCastExprToType(From, ToType, Kind);
1565 break;
1566 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001567 case ICK_Boolean_Conversion: {
1568 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1569 if (FromType->isMemberPointerType())
1570 Kind = CastExpr::CK_MemberPointerToBoolean;
1571
1572 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001573 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001574 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001575
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001576 case ICK_Derived_To_Base:
1577 if (CheckDerivedToBaseConversion(From->getType(),
1578 ToType.getNonReferenceType(),
1579 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001580 From->getSourceRange(),
1581 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001582 return true;
1583 ImpCastExprToType(From, ToType.getNonReferenceType(),
1584 CastExpr::CK_DerivedToBase);
1585 break;
1586
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001587 default:
1588 assert(false && "Improper second standard conversion");
1589 break;
1590 }
1591
1592 switch (SCS.Third) {
1593 case ICK_Identity:
1594 // Nothing to do.
1595 break;
1596
1597 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001598 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1599 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001600 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001601 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001602 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001603 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001604
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001605 default:
1606 assert(false && "Improper second standard conversion");
1607 break;
1608 }
1609
1610 return false;
1611}
1612
Sebastian Redl64b45f72009-01-05 20:52:13 +00001613Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1614 SourceLocation KWLoc,
1615 SourceLocation LParen,
1616 TypeTy *Ty,
1617 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001618 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001620 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1621 // all traits except __is_class, __is_enum and __is_union require a the type
1622 // to be complete.
1623 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001624 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001625 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001626 return ExprError();
1627 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001628
1629 // There is no point in eagerly computing the value. The traits are designed
1630 // to be used from type trait templates, so Ty will be a template parameter
1631 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001632 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1633 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001634}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001635
1636QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001637 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001638 const char *OpSpelling = isIndirect ? "->*" : ".*";
1639 // C++ 5.5p2
1640 // The binary operator .* [p3: ->*] binds its second operand, which shall
1641 // be of type "pointer to member of T" (where T is a completely-defined
1642 // class type) [...]
1643 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001644 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001645 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001646 Diag(Loc, diag::err_bad_memptr_rhs)
1647 << OpSpelling << RType << rex->getSourceRange();
1648 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001649 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001650
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001651 QualType Class(MemPtr->getClass(), 0);
1652
1653 // C++ 5.5p2
1654 // [...] to its first operand, which shall be of class T or of a class of
1655 // which T is an unambiguous and accessible base class. [p3: a pointer to
1656 // such a class]
1657 QualType LType = lex->getType();
1658 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001659 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001660 LType = Ptr->getPointeeType().getNonReferenceType();
1661 else {
1662 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001663 << OpSpelling << 1 << LType
1664 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001665 return QualType();
1666 }
1667 }
1668
Douglas Gregora4923eb2009-11-16 21:35:15 +00001669 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001670 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1671 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001672 // FIXME: Would it be useful to print full ambiguity paths, or is that
1673 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001674 if (!IsDerivedFrom(LType, Class, Paths) ||
1675 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1676 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001677 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001678 return QualType();
1679 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001680 // Cast LHS to type of use.
1681 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1682 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1683 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001684 }
1685
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001686 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001687 // Diagnose use of pointer-to-member type which when used as
1688 // the functional cast in a pointer-to-member expression.
1689 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1690 return QualType();
1691 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001692 // C++ 5.5p2
1693 // The result is an object or a function of the type specified by the
1694 // second operand.
1695 // The cv qualifiers are the union of those in the pointer and the left side,
1696 // in accordance with 5.5p5 and 5.2.5.
1697 // FIXME: This returns a dereferenced member function pointer as a normal
1698 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001699 // calling them. There's also a GCC extension to get a function pointer to the
1700 // thing, which is another complication, because this type - unlike the type
1701 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001702 // argument.
1703 // We probably need a "MemberFunctionClosureType" or something like that.
1704 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001705 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001706 return Result;
1707}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001708
1709/// \brief Get the target type of a standard or user-defined conversion.
1710static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001711 switch (ICS.getKind()) {
1712 case ImplicitConversionSequence::StandardConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001713 return ICS.Standard.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001714 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001715 return ICS.UserDefined.After.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001716 case ImplicitConversionSequence::AmbiguousConversion:
1717 return ICS.Ambiguous.getToType();
1718 case ImplicitConversionSequence::EllipsisConversion:
1719 case ImplicitConversionSequence::BadConversion:
1720 llvm_unreachable("function not valid for ellipsis or bad conversions");
1721 }
1722 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001723}
1724
1725/// \brief Try to convert a type to another according to C++0x 5.16p3.
1726///
1727/// This is part of the parameter validation for the ? operator. If either
1728/// value operand is a class type, the two operands are attempted to be
1729/// converted to each other. This function does the conversion in one direction.
1730/// It emits a diagnostic and returns true only if it finds an ambiguous
1731/// conversion.
1732static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1733 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001734 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001735 // C++0x 5.16p3
1736 // The process for determining whether an operand expression E1 of type T1
1737 // can be converted to match an operand expression E2 of type T2 is defined
1738 // as follows:
1739 // -- If E2 is an lvalue:
1740 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1741 // E1 can be converted to match E2 if E1 can be implicitly converted to
1742 // type "lvalue reference to T2", subject to the constraint that in the
1743 // conversion the reference must bind directly to E1.
1744 if (!Self.CheckReferenceInit(From,
1745 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001746 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001747 /*SuppressUserConversions=*/false,
1748 /*AllowExplicit=*/false,
1749 /*ForceRValue=*/false,
1750 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001751 {
John McCall1d318332010-01-12 00:44:57 +00001752 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001753 "expected a definite conversion");
1754 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001755 ICS.isStandard() ? ICS.Standard.DirectBinding
1756 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001757 if (DirectBinding)
1758 return false;
1759 }
1760 }
John McCall1d318332010-01-12 00:44:57 +00001761 ICS.setBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001762 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1763 // -- if E1 and E2 have class type, and the underlying class types are
1764 // the same or one is a base class of the other:
1765 QualType FTy = From->getType();
1766 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001767 const RecordType *FRec = FTy->getAs<RecordType>();
1768 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001769 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1770 if (FRec && TRec && (FRec == TRec ||
1771 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1772 // E1 can be converted to match E2 if the class of T2 is the
1773 // same type as, or a base class of, the class of T1, and
1774 // [cv2 > cv1].
1775 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1776 // Could still fail if there's no copy constructor.
1777 // FIXME: Is this a hard error then, or just a conversion failure? The
1778 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001779 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001780 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001781 /*ForceRValue=*/false,
1782 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001783 }
1784 } else {
1785 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1786 // implicitly converted to the type that expression E2 would have
1787 // if E2 were converted to an rvalue.
1788 // First find the decayed type.
1789 if (TTy->isFunctionType())
1790 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001791 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001792 TTy = Self.Context.getArrayDecayedType(TTy);
1793
1794 // Now try the implicit conversion.
1795 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001796 ICS = Self.TryImplicitConversion(From, TTy,
1797 /*SuppressUserConversions=*/false,
1798 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001799 /*ForceRValue=*/false,
1800 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001801 }
1802 return false;
1803}
1804
1805/// \brief Try to find a common type for two according to C++0x 5.16p5.
1806///
1807/// This is part of the parameter validation for the ? operator. If either
1808/// value operand is a class type, overload resolution is used to find a
1809/// conversion to a common type.
1810static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1811 SourceLocation Loc) {
1812 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00001813 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00001814 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001815
1816 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001817 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001818 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001819 // We found a match. Perform the conversions on the arguments and move on.
1820 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001821 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001822 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001823 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001824 break;
1825 return false;
1826
Douglas Gregor20093b42009-12-09 23:02:17 +00001827 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001828 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1829 << LHS->getType() << RHS->getType()
1830 << LHS->getSourceRange() << RHS->getSourceRange();
1831 return true;
1832
Douglas Gregor20093b42009-12-09 23:02:17 +00001833 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001834 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1835 << LHS->getType() << RHS->getType()
1836 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001837 // FIXME: Print the possible common types by printing the return types of
1838 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001839 break;
1840
Douglas Gregor20093b42009-12-09 23:02:17 +00001841 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001842 assert(false && "Conditional operator has only built-in overloads");
1843 break;
1844 }
1845 return true;
1846}
1847
Sebastian Redl76458502009-04-17 16:30:52 +00001848/// \brief Perform an "extended" implicit conversion as returned by
1849/// TryClassUnification.
1850///
1851/// TryClassUnification generates ICSs that include reference bindings.
1852/// PerformImplicitConversion is not suitable for this; it chokes if the
1853/// second part of a standard conversion is ICK_DerivedToBase. This function
1854/// handles the reference binding specially.
1855static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001856 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001857 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001858 assert(ICS.Standard.DirectBinding &&
1859 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001860 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1861 // redoing all the work.
1862 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001863 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001864 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001865 /*SuppressUserConversions=*/false,
1866 /*AllowExplicit=*/false,
1867 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001868 }
John McCall1d318332010-01-12 00:44:57 +00001869 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001870 assert(ICS.UserDefined.After.DirectBinding &&
1871 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001872 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001873 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001874 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001875 /*SuppressUserConversions=*/false,
1876 /*AllowExplicit=*/false,
1877 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001878 }
Douglas Gregor68647482009-12-16 03:45:30 +00001879 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001880 return true;
1881 return false;
1882}
1883
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001884/// \brief Check the operands of ?: under C++ semantics.
1885///
1886/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1887/// extension. In this case, LHS == Cond. (But they're not aliases.)
1888QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1889 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001890 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1891 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001892
1893 // C++0x 5.16p1
1894 // The first expression is contextually converted to bool.
1895 if (!Cond->isTypeDependent()) {
1896 if (CheckCXXBooleanCondition(Cond))
1897 return QualType();
1898 }
1899
1900 // Either of the arguments dependent?
1901 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1902 return Context.DependentTy;
1903
John McCallb13c87f2009-11-05 09:23:39 +00001904 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1905
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001906 // C++0x 5.16p2
1907 // If either the second or the third operand has type (cv) void, ...
1908 QualType LTy = LHS->getType();
1909 QualType RTy = RHS->getType();
1910 bool LVoid = LTy->isVoidType();
1911 bool RVoid = RTy->isVoidType();
1912 if (LVoid || RVoid) {
1913 // ... then the [l2r] conversions are performed on the second and third
1914 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00001915 DefaultFunctionArrayLvalueConversion(LHS);
1916 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001917 LTy = LHS->getType();
1918 RTy = RHS->getType();
1919
1920 // ... and one of the following shall hold:
1921 // -- The second or the third operand (but not both) is a throw-
1922 // expression; the result is of the type of the other and is an rvalue.
1923 bool LThrow = isa<CXXThrowExpr>(LHS);
1924 bool RThrow = isa<CXXThrowExpr>(RHS);
1925 if (LThrow && !RThrow)
1926 return RTy;
1927 if (RThrow && !LThrow)
1928 return LTy;
1929
1930 // -- Both the second and third operands have type void; the result is of
1931 // type void and is an rvalue.
1932 if (LVoid && RVoid)
1933 return Context.VoidTy;
1934
1935 // Neither holds, error.
1936 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1937 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1938 << LHS->getSourceRange() << RHS->getSourceRange();
1939 return QualType();
1940 }
1941
1942 // Neither is void.
1943
1944 // C++0x 5.16p3
1945 // Otherwise, if the second and third operand have different types, and
1946 // either has (cv) class type, and attempt is made to convert each of those
1947 // operands to the other.
1948 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1949 (LTy->isRecordType() || RTy->isRecordType())) {
1950 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1951 // These return true if a single direction is already ambiguous.
1952 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1953 return QualType();
1954 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1955 return QualType();
1956
John McCall1d318332010-01-12 00:44:57 +00001957 bool HaveL2R = !ICSLeftToRight.isBad();
1958 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001959 // If both can be converted, [...] the program is ill-formed.
1960 if (HaveL2R && HaveR2L) {
1961 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1962 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1963 return QualType();
1964 }
1965
1966 // If exactly one conversion is possible, that conversion is applied to
1967 // the chosen operand and the converted operands are used in place of the
1968 // original operands for the remainder of this section.
1969 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001970 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001971 return QualType();
1972 LTy = LHS->getType();
1973 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001974 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001975 return QualType();
1976 RTy = RHS->getType();
1977 }
1978 }
1979
1980 // C++0x 5.16p4
1981 // If the second and third operands are lvalues and have the same type,
1982 // the result is of that type [...]
1983 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1984 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1985 RHS->isLvalue(Context) == Expr::LV_Valid)
1986 return LTy;
1987
1988 // C++0x 5.16p5
1989 // Otherwise, the result is an rvalue. If the second and third operands
1990 // do not have the same type, and either has (cv) class type, ...
1991 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1992 // ... overload resolution is used to determine the conversions (if any)
1993 // to be applied to the operands. If the overload resolution fails, the
1994 // program is ill-formed.
1995 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1996 return QualType();
1997 }
1998
1999 // C++0x 5.16p6
2000 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2001 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002002 DefaultFunctionArrayLvalueConversion(LHS);
2003 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002004 LTy = LHS->getType();
2005 RTy = RHS->getType();
2006
2007 // After those conversions, one of the following shall hold:
2008 // -- The second and third operands have the same type; the result
2009 // is of that type.
2010 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2011 return LTy;
2012
2013 // -- The second and third operands have arithmetic or enumeration type;
2014 // the usual arithmetic conversions are performed to bring them to a
2015 // common type, and the result is of that type.
2016 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2017 UsualArithmeticConversions(LHS, RHS);
2018 return LHS->getType();
2019 }
2020
2021 // -- The second and third operands have pointer type, or one has pointer
2022 // type and the other is a null pointer constant; pointer conversions
2023 // and qualification conversions are performed to bring them to their
2024 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002025 // -- The second and third operands have pointer to member type, or one has
2026 // pointer to member type and the other is a null pointer constant;
2027 // pointer to member conversions and qualification conversions are
2028 // performed to bring them to a common type, whose cv-qualification
2029 // shall match the cv-qualification of either the second or the third
2030 // operand. The result is of the common type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002031 QualType Composite = FindCompositePointerType(LHS, RHS);
2032 if (!Composite.isNull())
2033 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00002034
2035 // Similarly, attempt to find composite type of twp objective-c pointers.
2036 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2037 if (!Composite.isNull())
2038 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002039
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002040 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2041 << LHS->getType() << RHS->getType()
2042 << LHS->getSourceRange() << RHS->getSourceRange();
2043 return QualType();
2044}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002045
2046/// \brief Find a merged pointer type and convert the two expressions to it.
2047///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002048/// This finds the composite pointer type (or member pointer type) for @p E1
2049/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2050/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002051/// It does not emit diagnostics.
2052QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
2053 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2054 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002056 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2057 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002058 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002059
2060 // C++0x 5.9p2
2061 // Pointer conversions and qualification conversions are performed on
2062 // pointer operands to bring them to their composite pointer type. If
2063 // one operand is a null pointer constant, the composite pointer type is
2064 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002065 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002066 if (T2->isMemberPointerType())
2067 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2068 else
2069 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002070 return T2;
2071 }
Douglas Gregorce940492009-09-25 04:25:58 +00002072 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002073 if (T1->isMemberPointerType())
2074 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2075 else
2076 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002077 return T1;
2078 }
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Douglas Gregor20b3e992009-08-24 17:42:35 +00002080 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002081 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2082 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002083 return QualType();
2084
2085 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2086 // the other has type "pointer to cv2 T" and the composite pointer type is
2087 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2088 // Otherwise, the composite pointer type is a pointer type similar to the
2089 // type of one of the operands, with a cv-qualification signature that is
2090 // the union of the cv-qualification signatures of the operand types.
2091 // In practice, the first part here is redundant; it's subsumed by the second.
2092 // What we do here is, we build the two possible composite types, and try the
2093 // conversions in both directions. If only one works, or if the two composite
2094 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002095 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002096 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2097 QualifierVector QualifierUnion;
2098 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2099 ContainingClassVector;
2100 ContainingClassVector MemberOfClass;
2101 QualType Composite1 = Context.getCanonicalType(T1),
2102 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002103 do {
2104 const PointerType *Ptr1, *Ptr2;
2105 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2106 (Ptr2 = Composite2->getAs<PointerType>())) {
2107 Composite1 = Ptr1->getPointeeType();
2108 Composite2 = Ptr2->getPointeeType();
2109 QualifierUnion.push_back(
2110 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2111 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2112 continue;
2113 }
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Douglas Gregor20b3e992009-08-24 17:42:35 +00002115 const MemberPointerType *MemPtr1, *MemPtr2;
2116 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2117 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2118 Composite1 = MemPtr1->getPointeeType();
2119 Composite2 = MemPtr2->getPointeeType();
2120 QualifierUnion.push_back(
2121 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2122 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2123 MemPtr2->getClass()));
2124 continue;
2125 }
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Douglas Gregor20b3e992009-08-24 17:42:35 +00002127 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Douglas Gregor20b3e992009-08-24 17:42:35 +00002129 // Cannot unwrap any more types.
2130 break;
2131 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Douglas Gregor20b3e992009-08-24 17:42:35 +00002133 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002134 ContainingClassVector::reverse_iterator MOC
2135 = MemberOfClass.rbegin();
2136 for (QualifierVector::reverse_iterator
2137 I = QualifierUnion.rbegin(),
2138 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002139 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002140 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002141 if (MOC->first && MOC->second) {
2142 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002143 Composite1 = Context.getMemberPointerType(
2144 Context.getQualifiedType(Composite1, Quals),
2145 MOC->first);
2146 Composite2 = Context.getMemberPointerType(
2147 Context.getQualifiedType(Composite2, Quals),
2148 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002149 } else {
2150 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002151 Composite1
2152 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2153 Composite2
2154 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002155 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002156 }
2157
Mike Stump1eb44332009-09-09 15:08:12 +00002158 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002159 TryImplicitConversion(E1, Composite1,
2160 /*SuppressUserConversions=*/false,
2161 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002162 /*ForceRValue=*/false,
2163 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002164 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002165 TryImplicitConversion(E2, Composite1,
2166 /*SuppressUserConversions=*/false,
2167 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002168 /*ForceRValue=*/false,
2169 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002171 ImplicitConversionSequence E1ToC2, E2ToC2;
John McCall1d318332010-01-12 00:44:57 +00002172 E1ToC2.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00002173 E2ToC2.setBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002174 if (Context.getCanonicalType(Composite1) !=
2175 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002176 E1ToC2 = TryImplicitConversion(E1, Composite2,
2177 /*SuppressUserConversions=*/false,
2178 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002179 /*ForceRValue=*/false,
2180 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002181 E2ToC2 = TryImplicitConversion(E2, Composite2,
2182 /*SuppressUserConversions=*/false,
2183 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002184 /*ForceRValue=*/false,
2185 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002186 }
2187
John McCall1d318332010-01-12 00:44:57 +00002188 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
2189 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002190 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002191 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2192 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002193 return Composite1;
2194 }
2195 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002196 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2197 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002198 return Composite2;
2199 }
2200 return QualType();
2201}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002202
Anders Carlssondef11992009-05-30 20:36:53 +00002203Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002204 if (!Context.getLangOptions().CPlusPlus)
2205 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Douglas Gregor51326552009-12-24 18:51:59 +00002207 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2208
Ted Kremenek6217b802009-07-29 21:53:49 +00002209 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002210 if (!RT)
2211 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002212
John McCall86ff3082010-02-04 22:26:26 +00002213 // If this is the result of a call expression, our source might
2214 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002215 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2216 QualType Ty = CE->getCallee()->getType();
2217 if (const PointerType *PT = Ty->getAs<PointerType>())
2218 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002219 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2220 Ty = BPT->getPointeeType();
2221
John McCall183700f2009-09-21 23:43:11 +00002222 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002223 if (FTy->getResultType()->isReferenceType())
2224 return Owned(E);
2225 }
John McCall86ff3082010-02-04 22:26:26 +00002226
2227 // That should be enough to guarantee that this type is complete.
2228 // If it has a trivial destructor, we can avoid the extra copy.
2229 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2230 if (RD->hasTrivialDestructor())
2231 return Owned(E);
2232
Mike Stump1eb44332009-09-09 15:08:12 +00002233 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002234 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002235 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002236 if (CXXDestructorDecl *Destructor =
2237 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2238 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002239 // FIXME: Add the temporary to the temporaries vector.
2240 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2241}
2242
Anders Carlsson0ece4912009-12-15 20:51:39 +00002243Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002244 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002246 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2247 assert(ExprTemporaries.size() >= FirstTemporary);
2248 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002249 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002251 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002252 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002253 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002254 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2255 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002257 return E;
2258}
2259
Douglas Gregor90f93822009-12-22 22:17:25 +00002260Sema::OwningExprResult
2261Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2262 if (SubExpr.isInvalid())
2263 return ExprError();
2264
2265 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2266}
2267
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002268FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2269 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2270 assert(ExprTemporaries.size() >= FirstTemporary);
2271
2272 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2273 CXXTemporary **Temporaries =
2274 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2275
2276 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2277
2278 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2279 ExprTemporaries.end());
2280
2281 return E;
2282}
2283
Mike Stump1eb44332009-09-09 15:08:12 +00002284Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002285Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2286 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2287 // Since this might be a postfix expression, get rid of ParenListExprs.
2288 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002290 Expr *BaseExpr = (Expr*)Base.get();
2291 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002293 QualType BaseType = BaseExpr->getType();
2294 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002295 // If we have a pointer to a dependent type and are using the -> operator,
2296 // the object type is the type that the pointer points to. We might still
2297 // have enough information about that type to do something useful.
2298 if (OpKind == tok::arrow)
2299 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2300 BaseType = Ptr->getPointeeType();
2301
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002302 ObjectType = BaseType.getAsOpaquePtr();
2303 return move(Base);
2304 }
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002306 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002307 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002308 // returned, with the original second operand.
2309 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002310 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002311 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002312 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002313 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002314
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002315 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002316 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002317 BaseExpr = (Expr*)Base.get();
2318 if (BaseExpr == NULL)
2319 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002320 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002321 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002322 BaseType = BaseExpr->getType();
2323 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002324 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002325 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002326 for (unsigned i = 0; i < Locations.size(); i++)
2327 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002328 return ExprError();
2329 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002330 }
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Douglas Gregor31658df2009-11-20 19:58:21 +00002332 if (BaseType->isPointerType())
2333 BaseType = BaseType->getPointeeType();
2334 }
Mike Stump1eb44332009-09-09 15:08:12 +00002335
2336 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002337 // vector types or Objective-C interfaces. Just return early and let
2338 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002339 if (!BaseType->isRecordType()) {
2340 // C++ [basic.lookup.classref]p2:
2341 // [...] If the type of the object expression is of pointer to scalar
2342 // type, the unqualified-id is looked up in the context of the complete
2343 // postfix-expression.
2344 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002345 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002346 }
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Douglas Gregor03c57052009-11-17 05:17:33 +00002348 // The object type must be complete (or dependent).
2349 if (!BaseType->isDependentType() &&
2350 RequireCompleteType(OpLoc, BaseType,
2351 PDiag(diag::err_incomplete_member_access)))
2352 return ExprError();
2353
Douglas Gregorc68afe22009-09-03 21:38:09 +00002354 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002355 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002356 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002357 // type C (or of pointer to a class type C), the unqualified-id is looked
2358 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002359 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002360
Mike Stump1eb44332009-09-09 15:08:12 +00002361 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002362}
2363
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002364CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2365 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002366 if (PerformObjectArgumentInitialization(Exp, Method))
2367 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2368
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002369 MemberExpr *ME =
2370 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2371 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002372 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002373 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2374 CXXMemberCallExpr *CE =
2375 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2376 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002377 return CE;
2378}
2379
Anders Carlsson0aebc812009-09-09 21:33:21 +00002380Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2381 QualType Ty,
2382 CastExpr::CastKind Kind,
2383 CXXMethodDecl *Method,
2384 ExprArg Arg) {
2385 Expr *From = Arg.takeAs<Expr>();
2386
2387 switch (Kind) {
2388 default: assert(0 && "Unhandled cast kind!");
2389 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002390 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2391
2392 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2393 MultiExprArg(*this, (void **)&From, 1),
2394 CastLoc, ConstructorArgs))
2395 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002396
2397 OwningExprResult Result =
2398 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2399 move_arg(ConstructorArgs));
2400 if (Result.isInvalid())
2401 return ExprError();
2402
2403 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002404 }
2405
2406 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002407 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002408
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002409 // Create an implicit call expr that calls it.
2410 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002411 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002412 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002413 }
2414}
2415
Anders Carlsson165a0a02009-05-17 18:41:29 +00002416Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2417 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002418 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002419 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002420
Anders Carlsson165a0a02009-05-17 18:41:29 +00002421 return Owned(FullExpr);
2422}