blob: 4cb58d8d19c9657b8135b2e1601782e60a63a818 [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);
Chandler Carruth5e895a82010-02-21 10:19:54 +000088 isDependent = LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +000089 }
90
91 LookInScope = false;
92 } else if (ObjectTypePtr) {
93 // C++ [basic.lookup.classref]p3:
94 // If the unqualified-id is ~type-name, the type-name is looked up
95 // in the context of the entire postfix-expression. If the type T
96 // of the object expression is of a class type C, the type-name is
97 // also looked up in the scope of class C. At least one of the
98 // lookups shall find a name that refers to (possibly
99 // cv-qualified) T.
100 LookupCtx = computeDeclContext(SearchType);
101 isDependent = SearchType->isDependentType();
102 assert((isDependent || !SearchType->isIncompleteType()) &&
103 "Caller should have completed object type");
104
105 LookInScope = true;
106 } else {
107 // Perform lookup into the current scope (only).
108 LookInScope = true;
109 }
110
111 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
112 for (unsigned Step = 0; Step != 2; ++Step) {
113 // Look for the name first in the computed lookup context (if we
114 // have one) and, if that fails to find a match, in the sope (if
115 // we're allowed to look there).
116 Found.clear();
117 if (Step == 0 && LookupCtx)
118 LookupQualifiedName(Found, LookupCtx);
119 else if (Step == 1 && LookInScope)
120 LookupName(Found, S);
121 else
122 continue;
123
124 // FIXME: Should we be suppressing ambiguities here?
125 if (Found.isAmbiguous())
126 return 0;
127
128 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
129 QualType T = Context.getTypeDeclType(Type);
130 // If we found the injected-class-name of a class template, retrieve the
131 // type of that template.
132 // FIXME: We really shouldn't need to do this.
133 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Type))
134 if (Record->isInjectedClassName())
135 if (Record->getDescribedClassTemplate())
136 T = Record->getDescribedClassTemplate()
137 ->getInjectedClassNameType(Context);
138
139 if (SearchType.isNull() || SearchType->isDependentType() ||
140 Context.hasSameUnqualifiedType(T, SearchType)) {
141 // We found our type!
142
143 return T.getAsOpaquePtr();
144 }
145 }
146
147 // If the name that we found is a class template name, and it is
148 // the same name as the template name in the last part of the
149 // nested-name-specifier (if present) or the object type, then
150 // this is the destructor for that class.
151 // FIXME: This is a workaround until we get real drafting for core
152 // issue 399, for which there isn't even an obvious direction.
153 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
154 QualType MemberOfType;
155 if (SS.isSet()) {
156 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
157 // Figure out the type of the context, if it has one.
158 if (ClassTemplateSpecializationDecl *Spec
159 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx))
160 MemberOfType = Context.getTypeDeclType(Spec);
161 else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
162 if (Record->getDescribedClassTemplate())
163 MemberOfType = Record->getDescribedClassTemplate()
164 ->getInjectedClassNameType(Context);
165 else
166 MemberOfType = Context.getTypeDeclType(Record);
167 }
168 }
169 }
170 if (MemberOfType.isNull())
171 MemberOfType = SearchType;
172
173 if (MemberOfType.isNull())
174 continue;
175
176 // We're referring into a class template specialization. If the
177 // class template we found is the same as the template being
178 // specialized, we found what we are looking for.
179 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
180 if (ClassTemplateSpecializationDecl *Spec
181 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
182 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
183 Template->getCanonicalDecl())
184 return MemberOfType.getAsOpaquePtr();
185 }
186
187 continue;
188 }
189
190 // We're referring to an unresolved class template
191 // specialization. Determine whether we class template we found
192 // is the same as the template being specialized or, if we don't
193 // know which template is being specialized, that it at least
194 // has the same name.
195 if (const TemplateSpecializationType *SpecType
196 = MemberOfType->getAs<TemplateSpecializationType>()) {
197 TemplateName SpecName = SpecType->getTemplateName();
198
199 // The class template we found is the same template being
200 // specialized.
201 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
202 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
203 return MemberOfType.getAsOpaquePtr();
204
205 continue;
206 }
207
208 // The class template we found has the same name as the
209 // (dependent) template name being specialized.
210 if (DependentTemplateName *DepTemplate
211 = SpecName.getAsDependentTemplateName()) {
212 if (DepTemplate->isIdentifier() &&
213 DepTemplate->getIdentifier() == Template->getIdentifier())
214 return MemberOfType.getAsOpaquePtr();
215
216 continue;
217 }
218 }
219 }
220 }
221
222 if (isDependent) {
223 // We didn't find our type, but that's okay: it's dependent
224 // anyway.
225 NestedNameSpecifier *NNS = 0;
226 SourceRange Range;
227 if (SS.isSet()) {
228 NNS = (NestedNameSpecifier *)SS.getScopeRep();
229 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
230 } else {
231 NNS = NestedNameSpecifier::Create(Context, &II);
232 Range = SourceRange(NameLoc);
233 }
234
235 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
236 }
237
238 if (ObjectTypePtr)
239 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
240 << &II;
241 else
242 Diag(NameLoc, diag::err_destructor_class_name);
243
244 return 0;
245}
246
Sebastian Redlc42e1182008-11-11 11:37:55 +0000247/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +0000248Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000249Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
250 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000251 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000252 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000253
Douglas Gregorf57f2072009-12-23 20:51:04 +0000254 if (isType) {
255 // C++ [expr.typeid]p4:
256 // The top-level cv-qualifiers of the lvalue expression or the type-id
257 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000258 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +0000259 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +0000260 QualType T = GetTypeFromParser(TyOrExpr);
261 if (T.isNull())
262 return ExprError();
263
264 // C++ [expr.typeid]p4:
265 // If the type of the type-id is a class type or a reference to a class
266 // type, the class shall be completely-defined.
267 QualType CheckT = T;
268 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
269 CheckT = RefType->getPointeeType();
270
271 if (CheckT->getAs<RecordType>() &&
272 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
273 return ExprError();
274
275 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +0000276 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000277
Chris Lattner572af492008-11-20 05:51:55 +0000278 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000279 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
280 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000281 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000282 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000283 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000284
285 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
286
Douglas Gregorac7610d2009-06-22 20:57:11 +0000287 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000288 bool isUnevaluatedOperand = true;
289 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +0000290 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000291 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000292 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000293 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +0000294 // C++ [expr.typeid]p3:
John McCall86ff3082010-02-04 22:26:26 +0000295 // [...] If the type of the expression is a class type, the class
296 // shall be completely-defined.
297 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
298 return ExprError();
299
300 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +0000301 // When typeid is applied to an expression other than an lvalue of a
302 // polymorphic class type [...] [the] expression is an unevaluated
303 // operand. [...]
304 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +0000305 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +0000306 }
307
308 // C++ [expr.typeid]p4:
309 // [...] If the type of the type-id is a reference to a possibly
310 // cv-qualified type, the result of the typeid expression refers to a
311 // std::type_info object representing the cv-unqualified referenced
312 // type.
313 if (T.hasQualifiers()) {
314 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
315 E->isLvalue(Context));
316 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000317 }
318 }
Mike Stump1eb44332009-09-09 15:08:12 +0000319
Douglas Gregor2afce722009-11-26 00:44:06 +0000320 // If this is an unevaluated operand, clear out the set of
321 // declaration references we have been computing and eliminate any
322 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000323 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000324 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000325 }
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Sebastian Redlf53597f2009-03-15 17:47:39 +0000327 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
328 TypeInfoType.withConst(),
329 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000330}
331
Steve Naroff1b273c42007-09-16 14:56:35 +0000332/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000333Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000334Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000335 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000337 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
338 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000339}
Chris Lattner50dd2892008-02-26 00:51:44 +0000340
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000341/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
342Action::OwningExprResult
343Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
344 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
345}
346
Chris Lattner50dd2892008-02-26 00:51:44 +0000347/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000348Action::OwningExprResult
349Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000350 Expr *Ex = E.takeAs<Expr>();
351 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
352 return ExprError();
353 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
354}
355
356/// CheckCXXThrowOperand - Validate the operand of a throw.
357bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
358 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000359 // A throw-expression initializes a temporary object, called the exception
360 // object, the type of which is determined by removing any top-level
361 // cv-qualifiers from the static type of the operand of throw and adjusting
362 // the type from "array of T" or "function returning T" to "pointer to T"
363 // or "pointer to function returning T", [...]
364 if (E->getType().hasQualifiers())
365 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
366 E->isLvalue(Context) == Expr::LV_Valid);
367
Sebastian Redl972041f2009-04-27 20:27:31 +0000368 DefaultFunctionArrayConversion(E);
369
370 // If the type of the exception would be an incomplete type or a pointer
371 // to an incomplete type other than (cv) void the program is ill-formed.
372 QualType Ty = E->getType();
373 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000374 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000375 Ty = Ptr->getPointeeType();
376 isPointer = 1;
377 }
378 if (!isPointer || !Ty->isVoidType()) {
379 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000380 PDiag(isPointer ? diag::err_throw_incomplete_ptr
381 : diag::err_throw_incomplete)
382 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000383 return true;
384 }
385
386 // FIXME: Construct a temporary here.
387 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000388}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000389
Sebastian Redlf53597f2009-03-15 17:47:39 +0000390Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000391 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
392 /// is a non-lvalue expression whose value is the address of the object for
393 /// which the function is called.
394
Sebastian Redlf53597f2009-03-15 17:47:39 +0000395 if (!isa<FunctionDecl>(CurContext))
396 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000397
398 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
399 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000400 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000401 MD->getThisType(Context),
402 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000403
Sebastian Redlf53597f2009-03-15 17:47:39 +0000404 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000405}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000406
407/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
408/// Can be interpreted either as function-style casting ("int(x)")
409/// or class type construction ("ClassType(x,y,z)")
410/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000411Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000412Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
413 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000414 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000415 SourceLocation *CommaLocs,
416 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000417 if (!TypeRep)
418 return ExprError();
419
John McCall9d125032010-01-15 18:39:57 +0000420 TypeSourceInfo *TInfo;
421 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
422 if (!TInfo)
423 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000424 unsigned NumExprs = exprs.size();
425 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000426 SourceLocation TyBeginLoc = TypeRange.getBegin();
427 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
428
Sebastian Redlf53597f2009-03-15 17:47:39 +0000429 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000430 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000431 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000432
433 return Owned(CXXUnresolvedConstructExpr::Create(Context,
434 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000435 LParenLoc,
436 Exprs, NumExprs,
437 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000438 }
439
Anders Carlssonbb60a502009-08-27 03:53:50 +0000440 if (Ty->isArrayType())
441 return ExprError(Diag(TyBeginLoc,
442 diag::err_value_init_for_array_type) << FullRange);
443 if (!Ty->isVoidType() &&
444 RequireCompleteType(TyBeginLoc, Ty,
445 PDiag(diag::err_invalid_incomplete_type_use)
446 << FullRange))
447 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000448
Anders Carlssonbb60a502009-08-27 03:53:50 +0000449 if (RequireNonAbstractType(TyBeginLoc, Ty,
450 diag::err_allocation_of_abstract_type))
451 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000452
453
Douglas Gregor506ae412009-01-16 18:33:17 +0000454 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000455 // If the expression list is a single expression, the type conversion
456 // expression is equivalent (in definedness, and if defined in meaning) to the
457 // corresponding cast expression.
458 //
459 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000460 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000461 CXXMethodDecl *Method = 0;
462 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
463 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000464 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000465
466 exprs.release();
467 if (Method) {
468 OwningExprResult CastArg
469 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
470 Kind, Method, Owned(Exprs[0]));
471 if (CastArg.isInvalid())
472 return ExprError();
473
474 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000475 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000476
477 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000478 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000479 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000480 }
481
Ted Kremenek6217b802009-07-29 21:53:49 +0000482 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000483 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000484
Mike Stump1eb44332009-09-09 15:08:12 +0000485 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000486 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000487 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
488 InitializationKind Kind
489 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
490 LParenLoc, RParenLoc)
491 : InitializationKind::CreateValue(TypeRange.getBegin(),
492 LParenLoc, RParenLoc);
493 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
494 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
495 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000496
Eli Friedman6997aae2010-01-31 20:58:15 +0000497 // FIXME: Improve AST representation?
498 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000499 }
500
501 // Fall through to value-initialize an object of class type that
502 // doesn't have a user-declared default constructor.
503 }
504
505 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000506 // If the expression list specifies more than a single value, the type shall
507 // be a class with a suitably declared constructor.
508 //
509 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000510 return ExprError(Diag(CommaLocs[0],
511 diag::err_builtin_func_cast_more_than_one_arg)
512 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000513
514 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000515 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000516 // The expression T(), where T is a simple-type-specifier for a non-array
517 // complete object type or the (possibly cv-qualified) void type, creates an
518 // rvalue of the specified type, which is value-initialized.
519 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000520 exprs.release();
521 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000522}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000523
524
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000525/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
526/// @code new (memory) int[size][4] @endcode
527/// or
528/// @code ::new Foo(23, "hello") @endcode
529/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000530Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000531Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000532 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000533 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000534 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000535 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000536 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000537 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000538 // If the specified type is an array, unwrap it and save the expression.
539 if (D.getNumTypeObjects() > 0 &&
540 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
541 DeclaratorChunk &Chunk = D.getTypeObject(0);
542 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000543 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
544 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000545 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000546 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
547 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000548
549 if (ParenTypeId) {
550 // Can't have dynamic array size when the type-id is in parentheses.
551 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
552 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
553 !NumElts->isIntegerConstantExpr(Context)) {
554 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
555 << NumElts->getSourceRange();
556 return ExprError();
557 }
558 }
559
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000560 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000561 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000562 }
563
Douglas Gregor043cad22009-09-11 00:18:58 +0000564 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000565 if (ArraySize) {
566 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000567 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
568 break;
569
570 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
571 if (Expr *NumElts = (Expr *)Array.NumElts) {
572 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
573 !NumElts->isIntegerConstantExpr(Context)) {
574 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
575 << NumElts->getSourceRange();
576 return ExprError();
577 }
578 }
579 }
580 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000581
John McCalla93c9342009-12-07 02:54:59 +0000582 //FIXME: Store TypeSourceInfo in CXXNew expression.
583 TypeSourceInfo *TInfo = 0;
584 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000585 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000586 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000587
Mike Stump1eb44332009-09-09 15:08:12 +0000588 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000589 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000590 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000591 PlacementRParen,
592 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000593 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000594 D.getSourceRange().getBegin(),
595 D.getSourceRange(),
596 Owned(ArraySize),
597 ConstructorLParen,
598 move(ConstructorArgs),
599 ConstructorRParen);
600}
601
Mike Stump1eb44332009-09-09 15:08:12 +0000602Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000603Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
604 SourceLocation PlacementLParen,
605 MultiExprArg PlacementArgs,
606 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000607 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000608 QualType AllocType,
609 SourceLocation TypeLoc,
610 SourceRange TypeRange,
611 ExprArg ArraySizeE,
612 SourceLocation ConstructorLParen,
613 MultiExprArg ConstructorArgs,
614 SourceLocation ConstructorRParen) {
615 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000616 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000617
Douglas Gregor3433cf72009-05-21 00:00:09 +0000618 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000619
620 // That every array dimension except the first is constant was already
621 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000622
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000623 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
624 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000625 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000626 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000627 QualType SizeType = ArraySize->getType();
628 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000629 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
630 diag::err_array_size_not_integral)
631 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000632 // Let's see if this is a constant < 0. If so, we reject it out of hand.
633 // We don't care about special rules, so we tell the machinery it's not
634 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000635 if (!ArraySize->isValueDependent()) {
636 llvm::APSInt Value;
637 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
638 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000639 llvm::APInt::getNullValue(Value.getBitWidth()),
640 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000641 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
642 diag::err_typecheck_negative_array_size)
643 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000644 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000645 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000646
Eli Friedman73c39ab2009-10-20 08:27:19 +0000647 ImpCastExprToType(ArraySize, Context.getSizeType(),
648 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000649 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000650
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000651 FunctionDecl *OperatorNew = 0;
652 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000653 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
654 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000655
Sebastian Redl28507842009-02-26 14:39:58 +0000656 if (!AllocType->isDependentType() &&
657 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
658 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000659 SourceRange(PlacementLParen, PlacementRParen),
660 UseGlobal, AllocType, ArraySize, PlaceArgs,
661 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000662 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000663 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000664 if (OperatorNew) {
665 // Add default arguments, if any.
666 const FunctionProtoType *Proto =
667 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000668 VariadicCallType CallType =
669 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000670 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
671 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000672 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000673 if (Invalid)
674 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000675
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000676 NumPlaceArgs = AllPlaceArgs.size();
677 if (NumPlaceArgs > 0)
678 PlaceArgs = &AllPlaceArgs[0];
679 }
680
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000681 bool Init = ConstructorLParen.isValid();
682 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000683 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000684 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
685 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000686 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
687
Douglas Gregor99a2e602009-12-16 01:38:02 +0000688 if (!AllocType->isDependentType() &&
689 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
690 // C++0x [expr.new]p15:
691 // A new-expression that creates an object of type T initializes that
692 // object as follows:
693 InitializationKind Kind
694 // - If the new-initializer is omitted, the object is default-
695 // initialized (8.5); if no initialization is performed,
696 // the object has indeterminate value
697 = !Init? InitializationKind::CreateDefault(TypeLoc)
698 // - Otherwise, the new-initializer is interpreted according to the
699 // initialization rules of 8.5 for direct-initialization.
700 : InitializationKind::CreateDirect(TypeLoc,
701 ConstructorLParen,
702 ConstructorRParen);
703
Douglas Gregor99a2e602009-12-16 01:38:02 +0000704 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000705 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000706 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000707 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
708 move(ConstructorArgs));
709 if (FullInit.isInvalid())
710 return ExprError();
711
712 // FullInit is our initializer; walk through it to determine if it's a
713 // constructor call, which CXXNewExpr handles directly.
714 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
715 if (CXXBindTemporaryExpr *Binder
716 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
717 FullInitExpr = Binder->getSubExpr();
718 if (CXXConstructExpr *Construct
719 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
720 Constructor = Construct->getConstructor();
721 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
722 AEnd = Construct->arg_end();
723 A != AEnd; ++A)
724 ConvertedConstructorArgs.push_back(A->Retain());
725 } else {
726 // Take the converted initializer.
727 ConvertedConstructorArgs.push_back(FullInit.release());
728 }
729 } else {
730 // No initialization required.
731 }
732
733 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000734 NumConsArgs = ConvertedConstructorArgs.size();
735 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000736 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000737
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000738 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000739
Sebastian Redlf53597f2009-03-15 17:47:39 +0000740 PlacementArgs.release();
741 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000742 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000743 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
744 PlaceArgs, NumPlaceArgs, ParenTypeId,
745 ArraySize, Constructor, Init,
746 ConsArgs, NumConsArgs, OperatorDelete,
747 ResultType, StartLoc,
748 Init ? ConstructorRParen :
749 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000750}
751
752/// CheckAllocatedType - Checks that a type is suitable as the allocated type
753/// in a new-expression.
754/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000755bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000756 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000757 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
758 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000759 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000760 return Diag(Loc, diag::err_bad_new_type)
761 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000762 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000763 return Diag(Loc, diag::err_bad_new_type)
764 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000765 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000766 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000767 PDiag(diag::err_new_incomplete_type)
768 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000769 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000770 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000771 diag::err_allocation_of_abstract_type))
772 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000773
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000774 return false;
775}
776
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000777/// FindAllocationFunctions - Finds the overloads of operator new and delete
778/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000779bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
780 bool UseGlobal, QualType AllocType,
781 bool IsArray, Expr **PlaceArgs,
782 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000783 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000784 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000785 // --- Choosing an allocation function ---
786 // C++ 5.3.4p8 - 14 & 18
787 // 1) If UseGlobal is true, only look in the global scope. Else, also look
788 // in the scope of the allocated class.
789 // 2) If an array size is given, look for operator new[], else look for
790 // operator new.
791 // 3) The first argument is always size_t. Append the arguments from the
792 // placement form.
793 // FIXME: Also find the appropriate delete operator.
794
795 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
796 // We don't care about the actual value of this argument.
797 // FIXME: Should the Sema create the expression and embed it in the syntax
798 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000799 IntegerLiteral Size(llvm::APInt::getNullValue(
800 Context.Target.getPointerWidth(0)),
801 Context.getSizeType(),
802 SourceLocation());
803 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000804 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
805
806 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
807 IsArray ? OO_Array_New : OO_New);
808 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000809 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000810 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000811 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000812 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000813 AllocArgs.size(), Record, /*AllowMissing=*/true,
814 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000815 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000816 }
817 if (!OperatorNew) {
818 // Didn't find a member overload. Look for a global one.
819 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000820 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000821 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000822 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
823 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000824 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000825 }
826
Anders Carlssond9583892009-05-31 20:26:12 +0000827 // FindAllocationOverload can change the passed in arguments, so we need to
828 // copy them back.
829 if (NumPlaceArgs > 0)
830 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000832 return false;
833}
834
Sebastian Redl7f662392008-12-04 22:20:51 +0000835/// FindAllocationOverload - Find an fitting overload for the allocation
836/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000837bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
838 DeclarationName Name, Expr** Args,
839 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000840 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000841 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
842 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000843 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000844 if (AllowMissing)
845 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000846 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000847 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000848 }
849
John McCallf36e02d2009-10-09 21:13:30 +0000850 // FIXME: handle ambiguity
851
John McCall5769d612010-02-08 23:07:23 +0000852 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000853 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
854 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000855 // Even member operator new/delete are implicitly treated as
856 // static, so don't use AddMemberCandidate.
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000857
858 if (FunctionTemplateDecl *FnTemplate =
859 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
860 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
861 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
862 Candidates,
863 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000864 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000865 }
866
867 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
868 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
869 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000870 }
871
872 // Do the resolution.
873 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000874 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000875 case OR_Success: {
876 // Got one!
877 FunctionDecl *FnDecl = Best->Function;
878 // The first argument is size_t, and the first parameter must be size_t,
879 // too. This is checked on declaration and can be assumed. (It can't be
880 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000881 // Whatch out for variadic allocator function.
882 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
883 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000884 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000885 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000886 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000887 return true;
888 }
889 Operator = FnDecl;
890 return false;
891 }
892
893 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000894 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000895 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000896 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000897 return true;
898
899 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000900 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000901 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000902 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000903 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000904
905 case OR_Deleted:
906 Diag(StartLoc, diag::err_ovl_deleted_call)
907 << Best->Function->isDeleted()
908 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000909 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000910 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000911 }
912 assert(false && "Unreachable, bad result from BestViableFunction");
913 return true;
914}
915
916
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000917/// DeclareGlobalNewDelete - Declare the global forms of operator new and
918/// delete. These are:
919/// @code
920/// void* operator new(std::size_t) throw(std::bad_alloc);
921/// void* operator new[](std::size_t) throw(std::bad_alloc);
922/// void operator delete(void *) throw();
923/// void operator delete[](void *) throw();
924/// @endcode
925/// Note that the placement and nothrow forms of new are *not* implicitly
926/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000927void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000928 if (GlobalNewDeleteDeclared)
929 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000930
931 // C++ [basic.std.dynamic]p2:
932 // [...] The following allocation and deallocation functions (18.4) are
933 // implicitly declared in global scope in each translation unit of a
934 // program
935 //
936 // void* operator new(std::size_t) throw(std::bad_alloc);
937 // void* operator new[](std::size_t) throw(std::bad_alloc);
938 // void operator delete(void*) throw();
939 // void operator delete[](void*) throw();
940 //
941 // These implicit declarations introduce only the function names operator
942 // new, operator new[], operator delete, operator delete[].
943 //
944 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
945 // "std" or "bad_alloc" as necessary to form the exception specification.
946 // However, we do not make these implicit declarations visible to name
947 // lookup.
948 if (!StdNamespace) {
949 // The "std" namespace has not yet been defined, so build one implicitly.
950 StdNamespace = NamespaceDecl::Create(Context,
951 Context.getTranslationUnitDecl(),
952 SourceLocation(),
953 &PP.getIdentifierTable().get("std"));
954 StdNamespace->setImplicit(true);
955 }
956
957 if (!StdBadAlloc) {
958 // The "std::bad_alloc" class has not yet been declared, so build it
959 // implicitly.
960 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
961 StdNamespace,
962 SourceLocation(),
963 &PP.getIdentifierTable().get("bad_alloc"),
964 SourceLocation(), 0);
965 StdBadAlloc->setImplicit(true);
966 }
967
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000968 GlobalNewDeleteDeclared = true;
969
970 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
971 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +0000972 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000973
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000974 DeclareGlobalAllocationFunction(
975 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000976 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000977 DeclareGlobalAllocationFunction(
978 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000979 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000980 DeclareGlobalAllocationFunction(
981 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
982 Context.VoidTy, VoidPtr);
983 DeclareGlobalAllocationFunction(
984 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
985 Context.VoidTy, VoidPtr);
986}
987
988/// DeclareGlobalAllocationFunction - Declares a single implicit global
989/// allocation function if it doesn't already exist.
990void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +0000991 QualType Return, QualType Argument,
992 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000993 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
994
995 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000996 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000997 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000998 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000999 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001000 // Only look at non-template functions, as it is the predefined,
1001 // non-templated allocation function we are trying to declare here.
1002 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1003 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001004 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001005 Func->getParamDecl(0)->getType().getUnqualifiedType());
1006 // FIXME: Do we need to check for default arguments here?
1007 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1008 return;
1009 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001010 }
1011 }
1012
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001013 QualType BadAllocType;
1014 bool HasBadAllocExceptionSpec
1015 = (Name.getCXXOverloadedOperator() == OO_New ||
1016 Name.getCXXOverloadedOperator() == OO_Array_New);
1017 if (HasBadAllocExceptionSpec) {
1018 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1019 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1020 }
1021
1022 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1023 true, false,
1024 HasBadAllocExceptionSpec? 1 : 0,
1025 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001026 FunctionDecl *Alloc =
1027 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +00001028 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001029 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001030
1031 if (AddMallocAttr)
1032 Alloc->addAttr(::new (Context) MallocAttr());
1033
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001034 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001035 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001036 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001037 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001038
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001039 // FIXME: Also add this declaration to the IdentifierResolver, but
1040 // make sure it is at the end of the chain to coincide with the
1041 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001042 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001043}
1044
Anders Carlsson78f74552009-11-15 18:45:20 +00001045bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1046 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001047 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001048 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001049 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001050 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001051
John McCalla24dc2e2009-11-17 02:14:36 +00001052 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001053 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001054
1055 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1056 F != FEnd; ++F) {
1057 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1058 if (Delete->isUsualDeallocationFunction()) {
1059 Operator = Delete;
1060 return false;
1061 }
1062 }
1063
1064 // We did find operator delete/operator delete[] declarations, but
1065 // none of them were suitable.
1066 if (!Found.empty()) {
1067 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1068 << Name << RD;
1069
1070 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1071 F != FEnd; ++F) {
1072 Diag((*F)->getLocation(),
1073 diag::note_delete_member_function_declared_here)
1074 << Name;
1075 }
1076
1077 return true;
1078 }
1079
1080 // Look for a global declaration.
1081 DeclareGlobalNewDelete();
1082 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1083
1084 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1085 Expr* DeallocArgs[1];
1086 DeallocArgs[0] = &Null;
1087 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1088 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1089 Operator))
1090 return true;
1091
1092 assert(Operator && "Did not find a deallocation function!");
1093 return false;
1094}
1095
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001096/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1097/// @code ::delete ptr; @endcode
1098/// or
1099/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001100Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001101Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001102 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001103 // C++ [expr.delete]p1:
1104 // The operand shall have a pointer type, or a class type having a single
1105 // conversion function to a pointer type. The result has type void.
1106 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001107 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1108
Anders Carlssond67c4c32009-08-16 20:29:29 +00001109 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Sebastian Redlf53597f2009-03-15 17:47:39 +00001111 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001112 if (!Ex->isTypeDependent()) {
1113 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001114
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001115 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001116 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +00001117 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00001118 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001119
John McCalleec51cf2010-01-20 00:46:10 +00001120 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001121 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001122 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +00001123 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001124 continue;
1125
John McCallba135432009-11-21 08:51:07 +00001126 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001127
1128 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1129 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1130 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001131 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001132 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001133 if (ObjectPtrConversions.size() == 1) {
1134 // We have a single conversion to a pointer-to-object type. Perform
1135 // that conversion.
1136 Operand.release();
1137 if (!PerformImplicitConversion(Ex,
1138 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001139 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001140 Operand = Owned(Ex);
1141 Type = Ex->getType();
1142 }
1143 }
1144 else if (ObjectPtrConversions.size() > 1) {
1145 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1146 << Type << Ex->getSourceRange();
1147 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
1148 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +00001149 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001150 }
1151 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001152 }
Sebastian Redl28507842009-02-26 14:39:58 +00001153 }
1154
Sebastian Redlf53597f2009-03-15 17:47:39 +00001155 if (!Type->isPointerType())
1156 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1157 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001158
Ted Kremenek6217b802009-07-29 21:53:49 +00001159 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001160 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001161 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1162 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001163 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001164 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001165 PDiag(diag::warn_delete_incomplete)
1166 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001167 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001168
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001169 // C++ [expr.delete]p2:
1170 // [Note: a pointer to a const type can be the operand of a
1171 // delete-expression; it is not necessary to cast away the constness
1172 // (5.2.11) of the pointer expression before it is used as the operand
1173 // of the delete-expression. ]
1174 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1175 CastExpr::CK_NoOp);
1176
1177 // Update the operand.
1178 Operand.take();
1179 Operand = ExprArg(*this, Ex);
1180
Anders Carlssond67c4c32009-08-16 20:29:29 +00001181 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1182 ArrayForm ? OO_Array_Delete : OO_Delete);
1183
Anders Carlsson78f74552009-11-15 18:45:20 +00001184 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1185 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1186
1187 if (!UseGlobal &&
1188 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001189 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001190
Anders Carlsson78f74552009-11-15 18:45:20 +00001191 if (!RD->hasTrivialDestructor())
1192 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001193 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001194 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001195 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001196
Anders Carlssond67c4c32009-08-16 20:29:29 +00001197 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001198 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001199 DeclareGlobalNewDelete();
1200 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001201 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001202 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001203 OperatorDelete))
1204 return ExprError();
1205 }
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Sebastian Redl28507842009-02-26 14:39:58 +00001207 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001208 }
1209
Sebastian Redlf53597f2009-03-15 17:47:39 +00001210 Operand.release();
1211 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001212 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001213}
1214
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001215/// \brief Check the use of the given variable as a C++ condition in an if,
1216/// while, do-while, or switch statement.
1217Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1218 QualType T = ConditionVar->getType();
1219
1220 // C++ [stmt.select]p2:
1221 // The declarator shall not specify a function or an array.
1222 if (T->isFunctionType())
1223 return ExprError(Diag(ConditionVar->getLocation(),
1224 diag::err_invalid_use_of_function_type)
1225 << ConditionVar->getSourceRange());
1226 else if (T->isArrayType())
1227 return ExprError(Diag(ConditionVar->getLocation(),
1228 diag::err_invalid_use_of_array_type)
1229 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001230
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001231 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1232 ConditionVar->getLocation(),
1233 ConditionVar->getType().getNonReferenceType()));
1234}
1235
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001236/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1237bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1238 // C++ 6.4p4:
1239 // The value of a condition that is an initialized declaration in a statement
1240 // other than a switch statement is the value of the declared variable
1241 // implicitly converted to type bool. If that conversion is ill-formed, the
1242 // program is ill-formed.
1243 // The value of a condition that is an expression is the value of the
1244 // expression, implicitly converted to bool.
1245 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001246 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001247}
Douglas Gregor77a52232008-09-12 00:47:35 +00001248
1249/// Helper function to determine whether this is the (deprecated) C++
1250/// conversion from a string literal to a pointer to non-const char or
1251/// non-const wchar_t (for narrow and wide string literals,
1252/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001253bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001254Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1255 // Look inside the implicit cast, if it exists.
1256 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1257 From = Cast->getSubExpr();
1258
1259 // A string literal (2.13.4) that is not a wide string literal can
1260 // be converted to an rvalue of type "pointer to char"; a wide
1261 // string literal can be converted to an rvalue of type "pointer
1262 // to wchar_t" (C++ 4.2p2).
1263 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001264 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001265 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001266 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001267 // This conversion is considered only when there is an
1268 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001269 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001270 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1271 (!StrLit->isWide() &&
1272 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1273 ToPointeeType->getKind() == BuiltinType::Char_S))))
1274 return true;
1275 }
1276
1277 return false;
1278}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001279
1280/// PerformImplicitConversion - Perform an implicit conversion of the
1281/// expression From to the type ToType. Returns true if there was an
1282/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001283/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001284/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001285/// explicit user-defined conversions are permitted. @p Elidable should be true
1286/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1287/// resolution works differently in that case.
1288bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001289Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001290 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001291 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001292 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001293 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001294 Elidable, ICS);
1295}
1296
1297bool
1298Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001299 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001300 bool Elidable,
1301 ImplicitConversionSequence& ICS) {
John McCall1d318332010-01-12 00:44:57 +00001302 ICS.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001303 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001304 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001305 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001306 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001307 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001308 /*ForceRValue=*/true,
1309 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001310 }
John McCall1d318332010-01-12 00:44:57 +00001311 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001312 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001313 /*SuppressUserConversions=*/false,
1314 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001315 /*ForceRValue=*/false,
1316 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001317 }
Douglas Gregor68647482009-12-16 03:45:30 +00001318 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001319}
1320
1321/// PerformImplicitConversion - Perform an implicit conversion of the
1322/// expression From to the type ToType using the pre-computed implicit
1323/// conversion sequence ICS. Returns true if there was an error, false
1324/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001325/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001326/// used in the error message.
1327bool
1328Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1329 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001330 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001331 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001332 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001333 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001334 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001335 return true;
1336 break;
1337
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001338 case ImplicitConversionSequence::UserDefinedConversion: {
1339
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001340 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1341 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001342 QualType BeforeToType;
1343 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001344 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001345
1346 // If the user-defined conversion is specified by a conversion function,
1347 // the initial standard conversion sequence converts the source type to
1348 // the implicit object parameter of the conversion function.
1349 BeforeToType = Context.getTagDeclType(Conv->getParent());
1350 } else if (const CXXConstructorDecl *Ctor =
1351 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001352 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001353 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001354 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001355 // If the user-defined conversion is specified by a constructor, the
1356 // initial standard conversion sequence converts the source type to the
1357 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001358 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1359 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001360 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001361 else
1362 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001363 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001364 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001365 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001366 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001367 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001368 return true;
1369 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001370
Anders Carlsson0aebc812009-09-09 21:33:21 +00001371 OwningExprResult CastArg
1372 = BuildCXXCastArgument(From->getLocStart(),
1373 ToType.getNonReferenceType(),
1374 CastKind, cast<CXXMethodDecl>(FD),
1375 Owned(From));
1376
1377 if (CastArg.isInvalid())
1378 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001379
1380 From = CastArg.takeAs<Expr>();
1381
Eli Friedmand8889622009-11-27 04:41:50 +00001382 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001383 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001384 }
John McCall1d318332010-01-12 00:44:57 +00001385
1386 case ImplicitConversionSequence::AmbiguousConversion:
1387 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1388 PDiag(diag::err_typecheck_ambiguous_condition)
1389 << From->getSourceRange());
1390 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001391
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001392 case ImplicitConversionSequence::EllipsisConversion:
1393 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001394 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001395
1396 case ImplicitConversionSequence::BadConversion:
1397 return true;
1398 }
1399
1400 // Everything went well.
1401 return false;
1402}
1403
1404/// PerformImplicitConversion - Perform an implicit conversion of the
1405/// expression From to the type ToType by following the standard
1406/// conversion sequence SCS. Returns true if there was an error, false
1407/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001408/// expression. Flavor is the context in which we're performing this
1409/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001410bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001411Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001412 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001413 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001414 // Overall FIXME: we are recomputing too many types here and doing far too
1415 // much extra work. What this means is that we need to keep track of more
1416 // information that is computed when we try the implicit conversion initially,
1417 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001418 QualType FromType = From->getType();
1419
Douglas Gregor225c41e2008-11-03 19:09:14 +00001420 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001421 // FIXME: When can ToType be a reference type?
1422 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001423 if (SCS.Second == ICK_Derived_To_Base) {
1424 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1425 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1426 MultiExprArg(*this, (void **)&From, 1),
1427 /*FIXME:ConstructLoc*/SourceLocation(),
1428 ConstructorArgs))
1429 return true;
1430 OwningExprResult FromResult =
1431 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1432 ToType, SCS.CopyConstructor,
1433 move_arg(ConstructorArgs));
1434 if (FromResult.isInvalid())
1435 return true;
1436 From = FromResult.takeAs<Expr>();
1437 return false;
1438 }
Mike Stump1eb44332009-09-09 15:08:12 +00001439 OwningExprResult FromResult =
1440 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1441 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001442 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001444 if (FromResult.isInvalid())
1445 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001447 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001448 return false;
1449 }
1450
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001451 // Perform the first implicit conversion.
1452 switch (SCS.First) {
1453 case ICK_Identity:
1454 case ICK_Lvalue_To_Rvalue:
1455 // Nothing to do.
1456 break;
1457
1458 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001459 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001460 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001461 break;
1462
1463 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001464 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001465 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1466 if (!Fn)
1467 return true;
1468
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001469 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1470 return true;
1471
Anders Carlsson96ad5332009-10-21 17:16:23 +00001472 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001473 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001474
Sebastian Redl759986e2009-10-17 20:50:27 +00001475 // If there's already an address-of operator in the expression, we have
1476 // the right type already, and the code below would just introduce an
1477 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001478 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001479 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001480 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001481 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001482 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001483 break;
1484
1485 default:
1486 assert(false && "Improper first standard conversion");
1487 break;
1488 }
1489
1490 // Perform the second implicit conversion
1491 switch (SCS.Second) {
1492 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001493 // If both sides are functions (or pointers/references to them), there could
1494 // be incompatible exception declarations.
1495 if (CheckExceptionSpecCompatibility(From, ToType))
1496 return true;
1497 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001498 break;
1499
Douglas Gregor43c79c22009-12-09 00:47:37 +00001500 case ICK_NoReturn_Adjustment:
1501 // If both sides are functions (or pointers/references to them), there could
1502 // be incompatible exception declarations.
1503 if (CheckExceptionSpecCompatibility(From, ToType))
1504 return true;
1505
1506 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1507 CastExpr::CK_NoOp);
1508 break;
1509
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001510 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001511 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001512 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1513 break;
1514
1515 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001516 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001517 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1518 break;
1519
1520 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001521 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001522 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1523 break;
1524
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001525 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001526 if (ToType->isFloatingType())
1527 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1528 else
1529 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1530 break;
1531
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001532 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001533 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1534 break;
1535
Douglas Gregorf9201e02009-02-11 23:02:49 +00001536 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001537 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001538 break;
1539
Anders Carlsson61faec12009-09-12 04:46:44 +00001540 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001541 if (SCS.IncompatibleObjC) {
1542 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001543 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001544 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001545 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001546 << From->getSourceRange();
1547 }
1548
Anders Carlsson61faec12009-09-12 04:46:44 +00001549
1550 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001551 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001552 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001553 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001554 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001555 }
1556
1557 case ICK_Pointer_Member: {
1558 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001559 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001560 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001561 if (CheckExceptionSpecCompatibility(From, ToType))
1562 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001563 ImpCastExprToType(From, ToType, Kind);
1564 break;
1565 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001566 case ICK_Boolean_Conversion: {
1567 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1568 if (FromType->isMemberPointerType())
1569 Kind = CastExpr::CK_MemberPointerToBoolean;
1570
1571 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001572 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001573 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001574
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001575 case ICK_Derived_To_Base:
1576 if (CheckDerivedToBaseConversion(From->getType(),
1577 ToType.getNonReferenceType(),
1578 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001579 From->getSourceRange(),
1580 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001581 return true;
1582 ImpCastExprToType(From, ToType.getNonReferenceType(),
1583 CastExpr::CK_DerivedToBase);
1584 break;
1585
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001586 default:
1587 assert(false && "Improper second standard conversion");
1588 break;
1589 }
1590
1591 switch (SCS.Third) {
1592 case ICK_Identity:
1593 // Nothing to do.
1594 break;
1595
1596 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001597 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1598 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001599 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001600 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001601 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001602 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001603
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001604 default:
1605 assert(false && "Improper second standard conversion");
1606 break;
1607 }
1608
1609 return false;
1610}
1611
Sebastian Redl64b45f72009-01-05 20:52:13 +00001612Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1613 SourceLocation KWLoc,
1614 SourceLocation LParen,
1615 TypeTy *Ty,
1616 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001617 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001619 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1620 // all traits except __is_class, __is_enum and __is_union require a the type
1621 // to be complete.
1622 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001623 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001624 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001625 return ExprError();
1626 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001627
1628 // There is no point in eagerly computing the value. The traits are designed
1629 // to be used from type trait templates, so Ty will be a template parameter
1630 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001631 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1632 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001633}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001634
1635QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001636 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001637 const char *OpSpelling = isIndirect ? "->*" : ".*";
1638 // C++ 5.5p2
1639 // The binary operator .* [p3: ->*] binds its second operand, which shall
1640 // be of type "pointer to member of T" (where T is a completely-defined
1641 // class type) [...]
1642 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001643 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001644 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001645 Diag(Loc, diag::err_bad_memptr_rhs)
1646 << OpSpelling << RType << rex->getSourceRange();
1647 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001648 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001649
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001650 QualType Class(MemPtr->getClass(), 0);
1651
1652 // C++ 5.5p2
1653 // [...] to its first operand, which shall be of class T or of a class of
1654 // which T is an unambiguous and accessible base class. [p3: a pointer to
1655 // such a class]
1656 QualType LType = lex->getType();
1657 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001658 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001659 LType = Ptr->getPointeeType().getNonReferenceType();
1660 else {
1661 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001662 << OpSpelling << 1 << LType
1663 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001664 return QualType();
1665 }
1666 }
1667
Douglas Gregora4923eb2009-11-16 21:35:15 +00001668 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001669 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1670 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001671 // FIXME: Would it be useful to print full ambiguity paths, or is that
1672 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001673 if (!IsDerivedFrom(LType, Class, Paths) ||
1674 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1675 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001676 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001677 return QualType();
1678 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001679 // Cast LHS to type of use.
1680 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1681 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1682 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001683 }
1684
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001685 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001686 // Diagnose use of pointer-to-member type which when used as
1687 // the functional cast in a pointer-to-member expression.
1688 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1689 return QualType();
1690 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001691 // C++ 5.5p2
1692 // The result is an object or a function of the type specified by the
1693 // second operand.
1694 // The cv qualifiers are the union of those in the pointer and the left side,
1695 // in accordance with 5.5p5 and 5.2.5.
1696 // FIXME: This returns a dereferenced member function pointer as a normal
1697 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001698 // calling them. There's also a GCC extension to get a function pointer to the
1699 // thing, which is another complication, because this type - unlike the type
1700 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001701 // argument.
1702 // We probably need a "MemberFunctionClosureType" or something like that.
1703 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001704 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001705 return Result;
1706}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001707
1708/// \brief Get the target type of a standard or user-defined conversion.
1709static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001710 switch (ICS.getKind()) {
1711 case ImplicitConversionSequence::StandardConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001712 return ICS.Standard.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001713 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001714 return ICS.UserDefined.After.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001715 case ImplicitConversionSequence::AmbiguousConversion:
1716 return ICS.Ambiguous.getToType();
1717 case ImplicitConversionSequence::EllipsisConversion:
1718 case ImplicitConversionSequence::BadConversion:
1719 llvm_unreachable("function not valid for ellipsis or bad conversions");
1720 }
1721 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001722}
1723
1724/// \brief Try to convert a type to another according to C++0x 5.16p3.
1725///
1726/// This is part of the parameter validation for the ? operator. If either
1727/// value operand is a class type, the two operands are attempted to be
1728/// converted to each other. This function does the conversion in one direction.
1729/// It emits a diagnostic and returns true only if it finds an ambiguous
1730/// conversion.
1731static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1732 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001733 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001734 // C++0x 5.16p3
1735 // The process for determining whether an operand expression E1 of type T1
1736 // can be converted to match an operand expression E2 of type T2 is defined
1737 // as follows:
1738 // -- If E2 is an lvalue:
1739 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1740 // E1 can be converted to match E2 if E1 can be implicitly converted to
1741 // type "lvalue reference to T2", subject to the constraint that in the
1742 // conversion the reference must bind directly to E1.
1743 if (!Self.CheckReferenceInit(From,
1744 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001745 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001746 /*SuppressUserConversions=*/false,
1747 /*AllowExplicit=*/false,
1748 /*ForceRValue=*/false,
1749 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001750 {
John McCall1d318332010-01-12 00:44:57 +00001751 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001752 "expected a definite conversion");
1753 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001754 ICS.isStandard() ? ICS.Standard.DirectBinding
1755 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001756 if (DirectBinding)
1757 return false;
1758 }
1759 }
John McCall1d318332010-01-12 00:44:57 +00001760 ICS.setBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001761 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1762 // -- if E1 and E2 have class type, and the underlying class types are
1763 // the same or one is a base class of the other:
1764 QualType FTy = From->getType();
1765 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001766 const RecordType *FRec = FTy->getAs<RecordType>();
1767 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001768 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1769 if (FRec && TRec && (FRec == TRec ||
1770 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1771 // E1 can be converted to match E2 if the class of T2 is the
1772 // same type as, or a base class of, the class of T1, and
1773 // [cv2 > cv1].
1774 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1775 // Could still fail if there's no copy constructor.
1776 // FIXME: Is this a hard error then, or just a conversion failure? The
1777 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001778 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001779 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001780 /*ForceRValue=*/false,
1781 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001782 }
1783 } else {
1784 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1785 // implicitly converted to the type that expression E2 would have
1786 // if E2 were converted to an rvalue.
1787 // First find the decayed type.
1788 if (TTy->isFunctionType())
1789 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001790 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001791 TTy = Self.Context.getArrayDecayedType(TTy);
1792
1793 // Now try the implicit conversion.
1794 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001795 ICS = Self.TryImplicitConversion(From, TTy,
1796 /*SuppressUserConversions=*/false,
1797 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001798 /*ForceRValue=*/false,
1799 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001800 }
1801 return false;
1802}
1803
1804/// \brief Try to find a common type for two according to C++0x 5.16p5.
1805///
1806/// This is part of the parameter validation for the ? operator. If either
1807/// value operand is a class type, overload resolution is used to find a
1808/// conversion to a common type.
1809static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1810 SourceLocation Loc) {
1811 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00001812 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00001813 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001814
1815 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001816 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001817 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001818 // We found a match. Perform the conversions on the arguments and move on.
1819 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001820 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001821 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001822 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001823 break;
1824 return false;
1825
Douglas Gregor20093b42009-12-09 23:02:17 +00001826 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001827 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1828 << LHS->getType() << RHS->getType()
1829 << LHS->getSourceRange() << RHS->getSourceRange();
1830 return true;
1831
Douglas Gregor20093b42009-12-09 23:02:17 +00001832 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001833 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1834 << LHS->getType() << RHS->getType()
1835 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001836 // FIXME: Print the possible common types by printing the return types of
1837 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001838 break;
1839
Douglas Gregor20093b42009-12-09 23:02:17 +00001840 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001841 assert(false && "Conditional operator has only built-in overloads");
1842 break;
1843 }
1844 return true;
1845}
1846
Sebastian Redl76458502009-04-17 16:30:52 +00001847/// \brief Perform an "extended" implicit conversion as returned by
1848/// TryClassUnification.
1849///
1850/// TryClassUnification generates ICSs that include reference bindings.
1851/// PerformImplicitConversion is not suitable for this; it chokes if the
1852/// second part of a standard conversion is ICK_DerivedToBase. This function
1853/// handles the reference binding specially.
1854static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001855 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001856 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001857 assert(ICS.Standard.DirectBinding &&
1858 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001859 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1860 // redoing all the work.
1861 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001862 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001863 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001864 /*SuppressUserConversions=*/false,
1865 /*AllowExplicit=*/false,
1866 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001867 }
John McCall1d318332010-01-12 00:44:57 +00001868 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001869 assert(ICS.UserDefined.After.DirectBinding &&
1870 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001871 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001872 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001873 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001874 /*SuppressUserConversions=*/false,
1875 /*AllowExplicit=*/false,
1876 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001877 }
Douglas Gregor68647482009-12-16 03:45:30 +00001878 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001879 return true;
1880 return false;
1881}
1882
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001883/// \brief Check the operands of ?: under C++ semantics.
1884///
1885/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1886/// extension. In this case, LHS == Cond. (But they're not aliases.)
1887QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1888 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001889 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1890 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001891
1892 // C++0x 5.16p1
1893 // The first expression is contextually converted to bool.
1894 if (!Cond->isTypeDependent()) {
1895 if (CheckCXXBooleanCondition(Cond))
1896 return QualType();
1897 }
1898
1899 // Either of the arguments dependent?
1900 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1901 return Context.DependentTy;
1902
John McCallb13c87f2009-11-05 09:23:39 +00001903 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1904
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001905 // C++0x 5.16p2
1906 // If either the second or the third operand has type (cv) void, ...
1907 QualType LTy = LHS->getType();
1908 QualType RTy = RHS->getType();
1909 bool LVoid = LTy->isVoidType();
1910 bool RVoid = RTy->isVoidType();
1911 if (LVoid || RVoid) {
1912 // ... then the [l2r] conversions are performed on the second and third
1913 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00001914 DefaultFunctionArrayLvalueConversion(LHS);
1915 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001916 LTy = LHS->getType();
1917 RTy = RHS->getType();
1918
1919 // ... and one of the following shall hold:
1920 // -- The second or the third operand (but not both) is a throw-
1921 // expression; the result is of the type of the other and is an rvalue.
1922 bool LThrow = isa<CXXThrowExpr>(LHS);
1923 bool RThrow = isa<CXXThrowExpr>(RHS);
1924 if (LThrow && !RThrow)
1925 return RTy;
1926 if (RThrow && !LThrow)
1927 return LTy;
1928
1929 // -- Both the second and third operands have type void; the result is of
1930 // type void and is an rvalue.
1931 if (LVoid && RVoid)
1932 return Context.VoidTy;
1933
1934 // Neither holds, error.
1935 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1936 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1937 << LHS->getSourceRange() << RHS->getSourceRange();
1938 return QualType();
1939 }
1940
1941 // Neither is void.
1942
1943 // C++0x 5.16p3
1944 // Otherwise, if the second and third operand have different types, and
1945 // either has (cv) class type, and attempt is made to convert each of those
1946 // operands to the other.
1947 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1948 (LTy->isRecordType() || RTy->isRecordType())) {
1949 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1950 // These return true if a single direction is already ambiguous.
1951 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1952 return QualType();
1953 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1954 return QualType();
1955
John McCall1d318332010-01-12 00:44:57 +00001956 bool HaveL2R = !ICSLeftToRight.isBad();
1957 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001958 // If both can be converted, [...] the program is ill-formed.
1959 if (HaveL2R && HaveR2L) {
1960 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1961 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1962 return QualType();
1963 }
1964
1965 // If exactly one conversion is possible, that conversion is applied to
1966 // the chosen operand and the converted operands are used in place of the
1967 // original operands for the remainder of this section.
1968 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001969 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001970 return QualType();
1971 LTy = LHS->getType();
1972 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001973 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001974 return QualType();
1975 RTy = RHS->getType();
1976 }
1977 }
1978
1979 // C++0x 5.16p4
1980 // If the second and third operands are lvalues and have the same type,
1981 // the result is of that type [...]
1982 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1983 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1984 RHS->isLvalue(Context) == Expr::LV_Valid)
1985 return LTy;
1986
1987 // C++0x 5.16p5
1988 // Otherwise, the result is an rvalue. If the second and third operands
1989 // do not have the same type, and either has (cv) class type, ...
1990 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1991 // ... overload resolution is used to determine the conversions (if any)
1992 // to be applied to the operands. If the overload resolution fails, the
1993 // program is ill-formed.
1994 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1995 return QualType();
1996 }
1997
1998 // C++0x 5.16p6
1999 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2000 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002001 DefaultFunctionArrayLvalueConversion(LHS);
2002 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002003 LTy = LHS->getType();
2004 RTy = RHS->getType();
2005
2006 // After those conversions, one of the following shall hold:
2007 // -- The second and third operands have the same type; the result
2008 // is of that type.
2009 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2010 return LTy;
2011
2012 // -- The second and third operands have arithmetic or enumeration type;
2013 // the usual arithmetic conversions are performed to bring them to a
2014 // common type, and the result is of that type.
2015 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2016 UsualArithmeticConversions(LHS, RHS);
2017 return LHS->getType();
2018 }
2019
2020 // -- The second and third operands have pointer type, or one has pointer
2021 // type and the other is a null pointer constant; pointer conversions
2022 // and qualification conversions are performed to bring them to their
2023 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002024 // -- The second and third operands have pointer to member type, or one has
2025 // pointer to member type and the other is a null pointer constant;
2026 // pointer to member conversions and qualification conversions are
2027 // performed to bring them to a common type, whose cv-qualification
2028 // shall match the cv-qualification of either the second or the third
2029 // operand. The result is of the common type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002030 QualType Composite = FindCompositePointerType(LHS, RHS);
2031 if (!Composite.isNull())
2032 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00002033
2034 // Similarly, attempt to find composite type of twp objective-c pointers.
2035 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2036 if (!Composite.isNull())
2037 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002038
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002039 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2040 << LHS->getType() << RHS->getType()
2041 << LHS->getSourceRange() << RHS->getSourceRange();
2042 return QualType();
2043}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002044
2045/// \brief Find a merged pointer type and convert the two expressions to it.
2046///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002047/// This finds the composite pointer type (or member pointer type) for @p E1
2048/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2049/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002050/// It does not emit diagnostics.
2051QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
2052 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2053 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002055 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2056 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002057 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002058
2059 // C++0x 5.9p2
2060 // Pointer conversions and qualification conversions are performed on
2061 // pointer operands to bring them to their composite pointer type. If
2062 // one operand is a null pointer constant, the composite pointer type is
2063 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002064 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002065 if (T2->isMemberPointerType())
2066 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2067 else
2068 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002069 return T2;
2070 }
Douglas Gregorce940492009-09-25 04:25:58 +00002071 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002072 if (T1->isMemberPointerType())
2073 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2074 else
2075 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002076 return T1;
2077 }
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Douglas Gregor20b3e992009-08-24 17:42:35 +00002079 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002080 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2081 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002082 return QualType();
2083
2084 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2085 // the other has type "pointer to cv2 T" and the composite pointer type is
2086 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2087 // Otherwise, the composite pointer type is a pointer type similar to the
2088 // type of one of the operands, with a cv-qualification signature that is
2089 // the union of the cv-qualification signatures of the operand types.
2090 // In practice, the first part here is redundant; it's subsumed by the second.
2091 // What we do here is, we build the two possible composite types, and try the
2092 // conversions in both directions. If only one works, or if the two composite
2093 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002094 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002095 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2096 QualifierVector QualifierUnion;
2097 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2098 ContainingClassVector;
2099 ContainingClassVector MemberOfClass;
2100 QualType Composite1 = Context.getCanonicalType(T1),
2101 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002102 do {
2103 const PointerType *Ptr1, *Ptr2;
2104 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2105 (Ptr2 = Composite2->getAs<PointerType>())) {
2106 Composite1 = Ptr1->getPointeeType();
2107 Composite2 = Ptr2->getPointeeType();
2108 QualifierUnion.push_back(
2109 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2110 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2111 continue;
2112 }
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Douglas Gregor20b3e992009-08-24 17:42:35 +00002114 const MemberPointerType *MemPtr1, *MemPtr2;
2115 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2116 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2117 Composite1 = MemPtr1->getPointeeType();
2118 Composite2 = MemPtr2->getPointeeType();
2119 QualifierUnion.push_back(
2120 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2121 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2122 MemPtr2->getClass()));
2123 continue;
2124 }
Mike Stump1eb44332009-09-09 15:08:12 +00002125
Douglas Gregor20b3e992009-08-24 17:42:35 +00002126 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Douglas Gregor20b3e992009-08-24 17:42:35 +00002128 // Cannot unwrap any more types.
2129 break;
2130 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Douglas Gregor20b3e992009-08-24 17:42:35 +00002132 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002133 ContainingClassVector::reverse_iterator MOC
2134 = MemberOfClass.rbegin();
2135 for (QualifierVector::reverse_iterator
2136 I = QualifierUnion.rbegin(),
2137 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002138 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002139 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002140 if (MOC->first && MOC->second) {
2141 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002142 Composite1 = Context.getMemberPointerType(
2143 Context.getQualifiedType(Composite1, Quals),
2144 MOC->first);
2145 Composite2 = Context.getMemberPointerType(
2146 Context.getQualifiedType(Composite2, Quals),
2147 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002148 } else {
2149 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002150 Composite1
2151 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2152 Composite2
2153 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002154 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002155 }
2156
Mike Stump1eb44332009-09-09 15:08:12 +00002157 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002158 TryImplicitConversion(E1, Composite1,
2159 /*SuppressUserConversions=*/false,
2160 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002161 /*ForceRValue=*/false,
2162 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002163 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002164 TryImplicitConversion(E2, Composite1,
2165 /*SuppressUserConversions=*/false,
2166 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002167 /*ForceRValue=*/false,
2168 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002170 ImplicitConversionSequence E1ToC2, E2ToC2;
John McCall1d318332010-01-12 00:44:57 +00002171 E1ToC2.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00002172 E2ToC2.setBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002173 if (Context.getCanonicalType(Composite1) !=
2174 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002175 E1ToC2 = TryImplicitConversion(E1, Composite2,
2176 /*SuppressUserConversions=*/false,
2177 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002178 /*ForceRValue=*/false,
2179 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002180 E2ToC2 = TryImplicitConversion(E2, Composite2,
2181 /*SuppressUserConversions=*/false,
2182 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002183 /*ForceRValue=*/false,
2184 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002185 }
2186
John McCall1d318332010-01-12 00:44:57 +00002187 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
2188 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002189 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002190 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2191 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002192 return Composite1;
2193 }
2194 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002195 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2196 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002197 return Composite2;
2198 }
2199 return QualType();
2200}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002201
Anders Carlssondef11992009-05-30 20:36:53 +00002202Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002203 if (!Context.getLangOptions().CPlusPlus)
2204 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Douglas Gregor51326552009-12-24 18:51:59 +00002206 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2207
Ted Kremenek6217b802009-07-29 21:53:49 +00002208 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002209 if (!RT)
2210 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002211
John McCall86ff3082010-02-04 22:26:26 +00002212 // If this is the result of a call expression, our source might
2213 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002214 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2215 QualType Ty = CE->getCallee()->getType();
2216 if (const PointerType *PT = Ty->getAs<PointerType>())
2217 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002218 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2219 Ty = BPT->getPointeeType();
2220
John McCall183700f2009-09-21 23:43:11 +00002221 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002222 if (FTy->getResultType()->isReferenceType())
2223 return Owned(E);
2224 }
John McCall86ff3082010-02-04 22:26:26 +00002225
2226 // That should be enough to guarantee that this type is complete.
2227 // If it has a trivial destructor, we can avoid the extra copy.
2228 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2229 if (RD->hasTrivialDestructor())
2230 return Owned(E);
2231
Mike Stump1eb44332009-09-09 15:08:12 +00002232 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002233 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002234 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002235 if (CXXDestructorDecl *Destructor =
2236 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2237 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002238 // FIXME: Add the temporary to the temporaries vector.
2239 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2240}
2241
Anders Carlsson0ece4912009-12-15 20:51:39 +00002242Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002243 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002244
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002245 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2246 assert(ExprTemporaries.size() >= FirstTemporary);
2247 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002248 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002250 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002251 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002252 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002253 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2254 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002255
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002256 return E;
2257}
2258
Douglas Gregor90f93822009-12-22 22:17:25 +00002259Sema::OwningExprResult
2260Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2261 if (SubExpr.isInvalid())
2262 return ExprError();
2263
2264 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2265}
2266
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002267FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2268 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2269 assert(ExprTemporaries.size() >= FirstTemporary);
2270
2271 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2272 CXXTemporary **Temporaries =
2273 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2274
2275 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2276
2277 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2278 ExprTemporaries.end());
2279
2280 return E;
2281}
2282
Mike Stump1eb44332009-09-09 15:08:12 +00002283Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002284Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2285 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2286 // Since this might be a postfix expression, get rid of ParenListExprs.
2287 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002288
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002289 Expr *BaseExpr = (Expr*)Base.get();
2290 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002292 QualType BaseType = BaseExpr->getType();
2293 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002294 // If we have a pointer to a dependent type and are using the -> operator,
2295 // the object type is the type that the pointer points to. We might still
2296 // have enough information about that type to do something useful.
2297 if (OpKind == tok::arrow)
2298 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2299 BaseType = Ptr->getPointeeType();
2300
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002301 ObjectType = BaseType.getAsOpaquePtr();
2302 return move(Base);
2303 }
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002305 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002306 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002307 // returned, with the original second operand.
2308 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002309 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002310 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002311 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002312 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002313
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002314 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002315 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002316 BaseExpr = (Expr*)Base.get();
2317 if (BaseExpr == NULL)
2318 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002319 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002320 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002321 BaseType = BaseExpr->getType();
2322 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002323 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002324 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002325 for (unsigned i = 0; i < Locations.size(); i++)
2326 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002327 return ExprError();
2328 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002329 }
Mike Stump1eb44332009-09-09 15:08:12 +00002330
Douglas Gregor31658df2009-11-20 19:58:21 +00002331 if (BaseType->isPointerType())
2332 BaseType = BaseType->getPointeeType();
2333 }
Mike Stump1eb44332009-09-09 15:08:12 +00002334
2335 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002336 // vector types or Objective-C interfaces. Just return early and let
2337 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002338 if (!BaseType->isRecordType()) {
2339 // C++ [basic.lookup.classref]p2:
2340 // [...] If the type of the object expression is of pointer to scalar
2341 // type, the unqualified-id is looked up in the context of the complete
2342 // postfix-expression.
2343 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002344 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002345 }
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Douglas Gregor03c57052009-11-17 05:17:33 +00002347 // The object type must be complete (or dependent).
2348 if (!BaseType->isDependentType() &&
2349 RequireCompleteType(OpLoc, BaseType,
2350 PDiag(diag::err_incomplete_member_access)))
2351 return ExprError();
2352
Douglas Gregorc68afe22009-09-03 21:38:09 +00002353 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002354 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002355 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002356 // type C (or of pointer to a class type C), the unqualified-id is looked
2357 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002358 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002359
Mike Stump1eb44332009-09-09 15:08:12 +00002360 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002361}
2362
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002363CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2364 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002365 if (PerformObjectArgumentInitialization(Exp, Method))
2366 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2367
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002368 MemberExpr *ME =
2369 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2370 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002371 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002372 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2373 CXXMemberCallExpr *CE =
2374 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2375 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002376 return CE;
2377}
2378
Anders Carlsson0aebc812009-09-09 21:33:21 +00002379Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2380 QualType Ty,
2381 CastExpr::CastKind Kind,
2382 CXXMethodDecl *Method,
2383 ExprArg Arg) {
2384 Expr *From = Arg.takeAs<Expr>();
2385
2386 switch (Kind) {
2387 default: assert(0 && "Unhandled cast kind!");
2388 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002389 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2390
2391 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2392 MultiExprArg(*this, (void **)&From, 1),
2393 CastLoc, ConstructorArgs))
2394 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002395
2396 OwningExprResult Result =
2397 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2398 move_arg(ConstructorArgs));
2399 if (Result.isInvalid())
2400 return ExprError();
2401
2402 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002403 }
2404
2405 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002406 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002407
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002408 // Create an implicit call expr that calls it.
2409 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002410 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002411 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002412 }
2413}
2414
Anders Carlsson165a0a02009-05-17 18:41:29 +00002415Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2416 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002417 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002418 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002419
Anders Carlsson165a0a02009-05-17 18:41:29 +00002420 return Owned(FullExpr);
2421}