blob: 4098d0f2cf2df743c595eb61cc1c8c9c1211c548 [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
69 // a qualified-id of theform:
70 //
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 //
75 // To implement this, we look at the prefix of the
76 // nested-name-specifier we were given, and determine the lookup
77 // context from that.
78 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
79 if (NestedNameSpecifier *Prefix = NNS->getPrefix()) {
80 CXXScopeSpec PrefixSS;
81 PrefixSS.setScopeRep(Prefix);
82 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
83 isDependent = isDependentScopeSpecifier(PrefixSS);
84 } else if (ObjectTypePtr) {
85 LookupCtx = computeDeclContext(SearchType);
86 isDependent = SearchType->isDependentType();
87 } else {
88 LookupCtx = computeDeclContext(SS, EnteringContext);
89 if (LookupCtx && !LookupCtx->isTranslationUnit()) {
90 LookupCtx = LookupCtx->getParent();
91 isDependent = LookupCtx->isDependentContext();
92 } else {
93 isDependent = false;
94 }
95 }
96
97 LookInScope = false;
98 } else if (ObjectTypePtr) {
99 // C++ [basic.lookup.classref]p3:
100 // If the unqualified-id is ~type-name, the type-name is looked up
101 // in the context of the entire postfix-expression. If the type T
102 // of the object expression is of a class type C, the type-name is
103 // also looked up in the scope of class C. At least one of the
104 // lookups shall find a name that refers to (possibly
105 // cv-qualified) T.
106 LookupCtx = computeDeclContext(SearchType);
107 isDependent = SearchType->isDependentType();
108 assert((isDependent || !SearchType->isIncompleteType()) &&
109 "Caller should have completed object type");
110
111 LookInScope = true;
112 } else {
113 // Perform lookup into the current scope (only).
114 LookInScope = true;
115 }
116
117 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
118 for (unsigned Step = 0; Step != 2; ++Step) {
119 // Look for the name first in the computed lookup context (if we
120 // have one) and, if that fails to find a match, in the sope (if
121 // we're allowed to look there).
122 Found.clear();
123 if (Step == 0 && LookupCtx)
124 LookupQualifiedName(Found, LookupCtx);
125 else if (Step == 1 && LookInScope)
126 LookupName(Found, S);
127 else
128 continue;
129
130 // FIXME: Should we be suppressing ambiguities here?
131 if (Found.isAmbiguous())
132 return 0;
133
134 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
135 QualType T = Context.getTypeDeclType(Type);
136 // If we found the injected-class-name of a class template, retrieve the
137 // type of that template.
138 // FIXME: We really shouldn't need to do this.
139 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Type))
140 if (Record->isInjectedClassName())
141 if (Record->getDescribedClassTemplate())
142 T = Record->getDescribedClassTemplate()
143 ->getInjectedClassNameType(Context);
144
145 if (SearchType.isNull() || SearchType->isDependentType() ||
146 Context.hasSameUnqualifiedType(T, SearchType)) {
147 // We found our type!
148
149 return T.getAsOpaquePtr();
150 }
151 }
152
153 // If the name that we found is a class template name, and it is
154 // the same name as the template name in the last part of the
155 // nested-name-specifier (if present) or the object type, then
156 // this is the destructor for that class.
157 // FIXME: This is a workaround until we get real drafting for core
158 // issue 399, for which there isn't even an obvious direction.
159 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
160 QualType MemberOfType;
161 if (SS.isSet()) {
162 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
163 // Figure out the type of the context, if it has one.
164 if (ClassTemplateSpecializationDecl *Spec
165 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx))
166 MemberOfType = Context.getTypeDeclType(Spec);
167 else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
168 if (Record->getDescribedClassTemplate())
169 MemberOfType = Record->getDescribedClassTemplate()
170 ->getInjectedClassNameType(Context);
171 else
172 MemberOfType = Context.getTypeDeclType(Record);
173 }
174 }
175 }
176 if (MemberOfType.isNull())
177 MemberOfType = SearchType;
178
179 if (MemberOfType.isNull())
180 continue;
181
182 // We're referring into a class template specialization. If the
183 // class template we found is the same as the template being
184 // specialized, we found what we are looking for.
185 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
186 if (ClassTemplateSpecializationDecl *Spec
187 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
188 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
189 Template->getCanonicalDecl())
190 return MemberOfType.getAsOpaquePtr();
191 }
192
193 continue;
194 }
195
196 // We're referring to an unresolved class template
197 // specialization. Determine whether we class template we found
198 // is the same as the template being specialized or, if we don't
199 // know which template is being specialized, that it at least
200 // has the same name.
201 if (const TemplateSpecializationType *SpecType
202 = MemberOfType->getAs<TemplateSpecializationType>()) {
203 TemplateName SpecName = SpecType->getTemplateName();
204
205 // The class template we found is the same template being
206 // specialized.
207 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
208 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
209 return MemberOfType.getAsOpaquePtr();
210
211 continue;
212 }
213
214 // The class template we found has the same name as the
215 // (dependent) template name being specialized.
216 if (DependentTemplateName *DepTemplate
217 = SpecName.getAsDependentTemplateName()) {
218 if (DepTemplate->isIdentifier() &&
219 DepTemplate->getIdentifier() == Template->getIdentifier())
220 return MemberOfType.getAsOpaquePtr();
221
222 continue;
223 }
224 }
225 }
226 }
227
228 if (isDependent) {
229 // We didn't find our type, but that's okay: it's dependent
230 // anyway.
231 NestedNameSpecifier *NNS = 0;
232 SourceRange Range;
233 if (SS.isSet()) {
234 NNS = (NestedNameSpecifier *)SS.getScopeRep();
235 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
236 } else {
237 NNS = NestedNameSpecifier::Create(Context, &II);
238 Range = SourceRange(NameLoc);
239 }
240
241 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
242 }
243
244 if (ObjectTypePtr)
245 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
246 << &II;
247 else
248 Diag(NameLoc, diag::err_destructor_class_name);
249
250 return 0;
251}
252
Sebastian Redlc42e1182008-11-11 11:37:55 +0000253/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +0000254Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000255Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
256 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000257 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000258 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000259
Douglas Gregorf57f2072009-12-23 20:51:04 +0000260 if (isType) {
261 // C++ [expr.typeid]p4:
262 // The top-level cv-qualifiers of the lvalue expression or the type-id
263 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000264 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +0000265 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +0000266 QualType T = GetTypeFromParser(TyOrExpr);
267 if (T.isNull())
268 return ExprError();
269
270 // C++ [expr.typeid]p4:
271 // If the type of the type-id is a class type or a reference to a class
272 // type, the class shall be completely-defined.
273 QualType CheckT = T;
274 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
275 CheckT = RefType->getPointeeType();
276
277 if (CheckT->getAs<RecordType>() &&
278 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
279 return ExprError();
280
281 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +0000282 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000283
Chris Lattner572af492008-11-20 05:51:55 +0000284 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000285 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
286 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000287 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000288 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000289 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000290
291 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
292
Douglas Gregorac7610d2009-06-22 20:57:11 +0000293 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000294 bool isUnevaluatedOperand = true;
295 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +0000296 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000297 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000298 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000299 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +0000300 // C++ [expr.typeid]p3:
John McCall86ff3082010-02-04 22:26:26 +0000301 // [...] If the type of the expression is a class type, the class
302 // shall be completely-defined.
303 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
304 return ExprError();
305
306 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +0000307 // When typeid is applied to an expression other than an lvalue of a
308 // polymorphic class type [...] [the] expression is an unevaluated
309 // operand. [...]
310 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +0000311 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +0000312 }
313
314 // C++ [expr.typeid]p4:
315 // [...] If the type of the type-id is a reference to a possibly
316 // cv-qualified type, the result of the typeid expression refers to a
317 // std::type_info object representing the cv-unqualified referenced
318 // type.
319 if (T.hasQualifiers()) {
320 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
321 E->isLvalue(Context));
322 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000323 }
324 }
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Douglas Gregor2afce722009-11-26 00:44:06 +0000326 // If this is an unevaluated operand, clear out the set of
327 // declaration references we have been computing and eliminate any
328 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000329 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000330 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000331 }
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Sebastian Redlf53597f2009-03-15 17:47:39 +0000333 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
334 TypeInfoType.withConst(),
335 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000336}
337
Steve Naroff1b273c42007-09-16 14:56:35 +0000338/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000339Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000340Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000341 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000342 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000343 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
344 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000345}
Chris Lattner50dd2892008-02-26 00:51:44 +0000346
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000347/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
348Action::OwningExprResult
349Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
350 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
351}
352
Chris Lattner50dd2892008-02-26 00:51:44 +0000353/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000354Action::OwningExprResult
355Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000356 Expr *Ex = E.takeAs<Expr>();
357 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
358 return ExprError();
359 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
360}
361
362/// CheckCXXThrowOperand - Validate the operand of a throw.
363bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
364 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000365 // A throw-expression initializes a temporary object, called the exception
366 // object, the type of which is determined by removing any top-level
367 // cv-qualifiers from the static type of the operand of throw and adjusting
368 // the type from "array of T" or "function returning T" to "pointer to T"
369 // or "pointer to function returning T", [...]
370 if (E->getType().hasQualifiers())
371 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
372 E->isLvalue(Context) == Expr::LV_Valid);
373
Sebastian Redl972041f2009-04-27 20:27:31 +0000374 DefaultFunctionArrayConversion(E);
375
376 // If the type of the exception would be an incomplete type or a pointer
377 // to an incomplete type other than (cv) void the program is ill-formed.
378 QualType Ty = E->getType();
379 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000380 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000381 Ty = Ptr->getPointeeType();
382 isPointer = 1;
383 }
384 if (!isPointer || !Ty->isVoidType()) {
385 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000386 PDiag(isPointer ? diag::err_throw_incomplete_ptr
387 : diag::err_throw_incomplete)
388 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000389 return true;
390 }
391
392 // FIXME: Construct a temporary here.
393 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000394}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000395
Sebastian Redlf53597f2009-03-15 17:47:39 +0000396Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000397 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
398 /// is a non-lvalue expression whose value is the address of the object for
399 /// which the function is called.
400
Sebastian Redlf53597f2009-03-15 17:47:39 +0000401 if (!isa<FunctionDecl>(CurContext))
402 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000403
404 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
405 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000406 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000407 MD->getThisType(Context),
408 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000409
Sebastian Redlf53597f2009-03-15 17:47:39 +0000410 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000411}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000412
413/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
414/// Can be interpreted either as function-style casting ("int(x)")
415/// or class type construction ("ClassType(x,y,z)")
416/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000417Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000418Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
419 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000420 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000421 SourceLocation *CommaLocs,
422 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000423 if (!TypeRep)
424 return ExprError();
425
John McCall9d125032010-01-15 18:39:57 +0000426 TypeSourceInfo *TInfo;
427 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
428 if (!TInfo)
429 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000430 unsigned NumExprs = exprs.size();
431 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000432 SourceLocation TyBeginLoc = TypeRange.getBegin();
433 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
434
Sebastian Redlf53597f2009-03-15 17:47:39 +0000435 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000436 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000437 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000438
439 return Owned(CXXUnresolvedConstructExpr::Create(Context,
440 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000441 LParenLoc,
442 Exprs, NumExprs,
443 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000444 }
445
Anders Carlssonbb60a502009-08-27 03:53:50 +0000446 if (Ty->isArrayType())
447 return ExprError(Diag(TyBeginLoc,
448 diag::err_value_init_for_array_type) << FullRange);
449 if (!Ty->isVoidType() &&
450 RequireCompleteType(TyBeginLoc, Ty,
451 PDiag(diag::err_invalid_incomplete_type_use)
452 << FullRange))
453 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000454
Anders Carlssonbb60a502009-08-27 03:53:50 +0000455 if (RequireNonAbstractType(TyBeginLoc, Ty,
456 diag::err_allocation_of_abstract_type))
457 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000458
459
Douglas Gregor506ae412009-01-16 18:33:17 +0000460 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000461 // If the expression list is a single expression, the type conversion
462 // expression is equivalent (in definedness, and if defined in meaning) to the
463 // corresponding cast expression.
464 //
465 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000466 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000467 CXXMethodDecl *Method = 0;
468 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
469 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000470 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000471
472 exprs.release();
473 if (Method) {
474 OwningExprResult CastArg
475 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
476 Kind, Method, Owned(Exprs[0]));
477 if (CastArg.isInvalid())
478 return ExprError();
479
480 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000481 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000482
483 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000484 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000485 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000486 }
487
Ted Kremenek6217b802009-07-29 21:53:49 +0000488 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000489 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000490
Mike Stump1eb44332009-09-09 15:08:12 +0000491 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000492 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000493 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
494 InitializationKind Kind
495 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
496 LParenLoc, RParenLoc)
497 : InitializationKind::CreateValue(TypeRange.getBegin(),
498 LParenLoc, RParenLoc);
499 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
500 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
501 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000502
Eli Friedman6997aae2010-01-31 20:58:15 +0000503 // FIXME: Improve AST representation?
504 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000505 }
506
507 // Fall through to value-initialize an object of class type that
508 // doesn't have a user-declared default constructor.
509 }
510
511 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000512 // If the expression list specifies more than a single value, the type shall
513 // be a class with a suitably declared constructor.
514 //
515 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000516 return ExprError(Diag(CommaLocs[0],
517 diag::err_builtin_func_cast_more_than_one_arg)
518 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000519
520 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000521 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000522 // The expression T(), where T is a simple-type-specifier for a non-array
523 // complete object type or the (possibly cv-qualified) void type, creates an
524 // rvalue of the specified type, which is value-initialized.
525 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000526 exprs.release();
527 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000528}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000529
530
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000531/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
532/// @code new (memory) int[size][4] @endcode
533/// or
534/// @code ::new Foo(23, "hello") @endcode
535/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000536Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000537Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000538 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000539 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000540 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000541 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000542 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000543 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000544 // If the specified type is an array, unwrap it and save the expression.
545 if (D.getNumTypeObjects() > 0 &&
546 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
547 DeclaratorChunk &Chunk = D.getTypeObject(0);
548 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000549 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
550 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000551 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000552 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
553 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000554
555 if (ParenTypeId) {
556 // Can't have dynamic array size when the type-id is in parentheses.
557 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
558 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
559 !NumElts->isIntegerConstantExpr(Context)) {
560 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
561 << NumElts->getSourceRange();
562 return ExprError();
563 }
564 }
565
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000566 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000567 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000568 }
569
Douglas Gregor043cad22009-09-11 00:18:58 +0000570 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000571 if (ArraySize) {
572 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000573 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
574 break;
575
576 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
577 if (Expr *NumElts = (Expr *)Array.NumElts) {
578 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
579 !NumElts->isIntegerConstantExpr(Context)) {
580 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
581 << NumElts->getSourceRange();
582 return ExprError();
583 }
584 }
585 }
586 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000587
John McCalla93c9342009-12-07 02:54:59 +0000588 //FIXME: Store TypeSourceInfo in CXXNew expression.
589 TypeSourceInfo *TInfo = 0;
590 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000591 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000592 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000593
Mike Stump1eb44332009-09-09 15:08:12 +0000594 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000595 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000596 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000597 PlacementRParen,
598 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000599 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000600 D.getSourceRange().getBegin(),
601 D.getSourceRange(),
602 Owned(ArraySize),
603 ConstructorLParen,
604 move(ConstructorArgs),
605 ConstructorRParen);
606}
607
Mike Stump1eb44332009-09-09 15:08:12 +0000608Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000609Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
610 SourceLocation PlacementLParen,
611 MultiExprArg PlacementArgs,
612 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000613 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000614 QualType AllocType,
615 SourceLocation TypeLoc,
616 SourceRange TypeRange,
617 ExprArg ArraySizeE,
618 SourceLocation ConstructorLParen,
619 MultiExprArg ConstructorArgs,
620 SourceLocation ConstructorRParen) {
621 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000622 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000623
Douglas Gregor3433cf72009-05-21 00:00:09 +0000624 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000625
626 // That every array dimension except the first is constant was already
627 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000628
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000629 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
630 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000631 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000632 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000633 QualType SizeType = ArraySize->getType();
634 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000635 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
636 diag::err_array_size_not_integral)
637 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000638 // Let's see if this is a constant < 0. If so, we reject it out of hand.
639 // We don't care about special rules, so we tell the machinery it's not
640 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000641 if (!ArraySize->isValueDependent()) {
642 llvm::APSInt Value;
643 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
644 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000645 llvm::APInt::getNullValue(Value.getBitWidth()),
646 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000647 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
648 diag::err_typecheck_negative_array_size)
649 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000650 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000651 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000652
Eli Friedman73c39ab2009-10-20 08:27:19 +0000653 ImpCastExprToType(ArraySize, Context.getSizeType(),
654 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000655 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000656
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000657 FunctionDecl *OperatorNew = 0;
658 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000659 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
660 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000661
Sebastian Redl28507842009-02-26 14:39:58 +0000662 if (!AllocType->isDependentType() &&
663 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
664 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000665 SourceRange(PlacementLParen, PlacementRParen),
666 UseGlobal, AllocType, ArraySize, PlaceArgs,
667 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000668 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000669 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000670 if (OperatorNew) {
671 // Add default arguments, if any.
672 const FunctionProtoType *Proto =
673 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000674 VariadicCallType CallType =
675 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000676 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
677 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000678 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000679 if (Invalid)
680 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000681
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000682 NumPlaceArgs = AllPlaceArgs.size();
683 if (NumPlaceArgs > 0)
684 PlaceArgs = &AllPlaceArgs[0];
685 }
686
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000687 bool Init = ConstructorLParen.isValid();
688 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000689 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000690 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
691 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000692 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
693
Douglas Gregor99a2e602009-12-16 01:38:02 +0000694 if (!AllocType->isDependentType() &&
695 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
696 // C++0x [expr.new]p15:
697 // A new-expression that creates an object of type T initializes that
698 // object as follows:
699 InitializationKind Kind
700 // - If the new-initializer is omitted, the object is default-
701 // initialized (8.5); if no initialization is performed,
702 // the object has indeterminate value
703 = !Init? InitializationKind::CreateDefault(TypeLoc)
704 // - Otherwise, the new-initializer is interpreted according to the
705 // initialization rules of 8.5 for direct-initialization.
706 : InitializationKind::CreateDirect(TypeLoc,
707 ConstructorLParen,
708 ConstructorRParen);
709
Douglas Gregor99a2e602009-12-16 01:38:02 +0000710 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000711 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000712 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000713 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
714 move(ConstructorArgs));
715 if (FullInit.isInvalid())
716 return ExprError();
717
718 // FullInit is our initializer; walk through it to determine if it's a
719 // constructor call, which CXXNewExpr handles directly.
720 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
721 if (CXXBindTemporaryExpr *Binder
722 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
723 FullInitExpr = Binder->getSubExpr();
724 if (CXXConstructExpr *Construct
725 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
726 Constructor = Construct->getConstructor();
727 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
728 AEnd = Construct->arg_end();
729 A != AEnd; ++A)
730 ConvertedConstructorArgs.push_back(A->Retain());
731 } else {
732 // Take the converted initializer.
733 ConvertedConstructorArgs.push_back(FullInit.release());
734 }
735 } else {
736 // No initialization required.
737 }
738
739 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000740 NumConsArgs = ConvertedConstructorArgs.size();
741 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000742 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000743
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000744 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000745
Sebastian Redlf53597f2009-03-15 17:47:39 +0000746 PlacementArgs.release();
747 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000748 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000749 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
750 PlaceArgs, NumPlaceArgs, ParenTypeId,
751 ArraySize, Constructor, Init,
752 ConsArgs, NumConsArgs, OperatorDelete,
753 ResultType, StartLoc,
754 Init ? ConstructorRParen :
755 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000756}
757
758/// CheckAllocatedType - Checks that a type is suitable as the allocated type
759/// in a new-expression.
760/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000761bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000762 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000763 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
764 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000765 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000766 return Diag(Loc, diag::err_bad_new_type)
767 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000768 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000769 return Diag(Loc, diag::err_bad_new_type)
770 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000771 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000772 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000773 PDiag(diag::err_new_incomplete_type)
774 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000775 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000776 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000777 diag::err_allocation_of_abstract_type))
778 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000779
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000780 return false;
781}
782
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000783/// FindAllocationFunctions - Finds the overloads of operator new and delete
784/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000785bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
786 bool UseGlobal, QualType AllocType,
787 bool IsArray, Expr **PlaceArgs,
788 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000789 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000790 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000791 // --- Choosing an allocation function ---
792 // C++ 5.3.4p8 - 14 & 18
793 // 1) If UseGlobal is true, only look in the global scope. Else, also look
794 // in the scope of the allocated class.
795 // 2) If an array size is given, look for operator new[], else look for
796 // operator new.
797 // 3) The first argument is always size_t. Append the arguments from the
798 // placement form.
799 // FIXME: Also find the appropriate delete operator.
800
801 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
802 // We don't care about the actual value of this argument.
803 // FIXME: Should the Sema create the expression and embed it in the syntax
804 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000805 IntegerLiteral Size(llvm::APInt::getNullValue(
806 Context.Target.getPointerWidth(0)),
807 Context.getSizeType(),
808 SourceLocation());
809 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000810 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
811
812 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
813 IsArray ? OO_Array_New : OO_New);
814 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000815 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000816 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000817 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000818 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000819 AllocArgs.size(), Record, /*AllowMissing=*/true,
820 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000821 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000822 }
823 if (!OperatorNew) {
824 // Didn't find a member overload. Look for a global one.
825 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000826 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000827 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000828 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
829 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000830 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000831 }
832
Anders Carlssond9583892009-05-31 20:26:12 +0000833 // FindAllocationOverload can change the passed in arguments, so we need to
834 // copy them back.
835 if (NumPlaceArgs > 0)
836 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000838 return false;
839}
840
Sebastian Redl7f662392008-12-04 22:20:51 +0000841/// FindAllocationOverload - Find an fitting overload for the allocation
842/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000843bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
844 DeclarationName Name, Expr** Args,
845 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +0000846 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +0000847 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
848 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +0000849 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000850 if (AllowMissing)
851 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000852 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000853 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000854 }
855
John McCallf36e02d2009-10-09 21:13:30 +0000856 // FIXME: handle ambiguity
857
John McCall5769d612010-02-08 23:07:23 +0000858 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +0000859 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
860 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000861 // Even member operator new/delete are implicitly treated as
862 // static, so don't use AddMemberCandidate.
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000863
864 if (FunctionTemplateDecl *FnTemplate =
865 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) {
866 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(),
867 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
868 Candidates,
869 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +0000870 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +0000871 }
872
873 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl());
874 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates,
875 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000876 }
877
878 // Do the resolution.
879 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +0000880 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000881 case OR_Success: {
882 // Got one!
883 FunctionDecl *FnDecl = Best->Function;
884 // The first argument is size_t, and the first parameter must be size_t,
885 // too. This is checked on declaration and can be assumed. (It can't be
886 // asserted on, though, since invalid decls are left in there.)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000887 // Whatch out for variadic allocator function.
888 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
889 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Anders Carlssonfc27d262009-05-31 19:49:47 +0000890 if (PerformCopyInitialization(Args[i],
Sebastian Redl7f662392008-12-04 22:20:51 +0000891 FnDecl->getParamDecl(i)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +0000892 AA_Passing))
Sebastian Redl7f662392008-12-04 22:20:51 +0000893 return true;
894 }
895 Operator = FnDecl;
896 return false;
897 }
898
899 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +0000900 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000901 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000902 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000903 return true;
904
905 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000906 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000907 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000908 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +0000909 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000910
911 case OR_Deleted:
912 Diag(StartLoc, diag::err_ovl_deleted_call)
913 << Best->Function->isDeleted()
914 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +0000915 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000916 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000917 }
918 assert(false && "Unreachable, bad result from BestViableFunction");
919 return true;
920}
921
922
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000923/// DeclareGlobalNewDelete - Declare the global forms of operator new and
924/// delete. These are:
925/// @code
926/// void* operator new(std::size_t) throw(std::bad_alloc);
927/// void* operator new[](std::size_t) throw(std::bad_alloc);
928/// void operator delete(void *) throw();
929/// void operator delete[](void *) throw();
930/// @endcode
931/// Note that the placement and nothrow forms of new are *not* implicitly
932/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +0000933void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000934 if (GlobalNewDeleteDeclared)
935 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000936
937 // C++ [basic.std.dynamic]p2:
938 // [...] The following allocation and deallocation functions (18.4) are
939 // implicitly declared in global scope in each translation unit of a
940 // program
941 //
942 // void* operator new(std::size_t) throw(std::bad_alloc);
943 // void* operator new[](std::size_t) throw(std::bad_alloc);
944 // void operator delete(void*) throw();
945 // void operator delete[](void*) throw();
946 //
947 // These implicit declarations introduce only the function names operator
948 // new, operator new[], operator delete, operator delete[].
949 //
950 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
951 // "std" or "bad_alloc" as necessary to form the exception specification.
952 // However, we do not make these implicit declarations visible to name
953 // lookup.
954 if (!StdNamespace) {
955 // The "std" namespace has not yet been defined, so build one implicitly.
956 StdNamespace = NamespaceDecl::Create(Context,
957 Context.getTranslationUnitDecl(),
958 SourceLocation(),
959 &PP.getIdentifierTable().get("std"));
960 StdNamespace->setImplicit(true);
961 }
962
963 if (!StdBadAlloc) {
964 // The "std::bad_alloc" class has not yet been declared, so build it
965 // implicitly.
966 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
967 StdNamespace,
968 SourceLocation(),
969 &PP.getIdentifierTable().get("bad_alloc"),
970 SourceLocation(), 0);
971 StdBadAlloc->setImplicit(true);
972 }
973
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000974 GlobalNewDeleteDeclared = true;
975
976 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
977 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +0000978 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000979
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000980 DeclareGlobalAllocationFunction(
981 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000982 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000983 DeclareGlobalAllocationFunction(
984 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +0000985 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000986 DeclareGlobalAllocationFunction(
987 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
988 Context.VoidTy, VoidPtr);
989 DeclareGlobalAllocationFunction(
990 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
991 Context.VoidTy, VoidPtr);
992}
993
994/// DeclareGlobalAllocationFunction - Declares a single implicit global
995/// allocation function if it doesn't already exist.
996void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +0000997 QualType Return, QualType Argument,
998 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000999 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1000
1001 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001002 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001003 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001004 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001005 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001006 // Only look at non-template functions, as it is the predefined,
1007 // non-templated allocation function we are trying to declare here.
1008 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1009 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001010 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001011 Func->getParamDecl(0)->getType().getUnqualifiedType());
1012 // FIXME: Do we need to check for default arguments here?
1013 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1014 return;
1015 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001016 }
1017 }
1018
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001019 QualType BadAllocType;
1020 bool HasBadAllocExceptionSpec
1021 = (Name.getCXXOverloadedOperator() == OO_New ||
1022 Name.getCXXOverloadedOperator() == OO_Array_New);
1023 if (HasBadAllocExceptionSpec) {
1024 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1025 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1026 }
1027
1028 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1029 true, false,
1030 HasBadAllocExceptionSpec? 1 : 0,
1031 &BadAllocType);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001032 FunctionDecl *Alloc =
1033 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +00001034 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001035 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001036
1037 if (AddMallocAttr)
1038 Alloc->addAttr(::new (Context) MallocAttr());
1039
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001040 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001041 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001042 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001043 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001044
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001045 // FIXME: Also add this declaration to the IdentifierResolver, but
1046 // make sure it is at the end of the chain to coincide with the
1047 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001048 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001049}
1050
Anders Carlsson78f74552009-11-15 18:45:20 +00001051bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1052 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001053 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001054 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001055 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001056 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001057
John McCalla24dc2e2009-11-17 02:14:36 +00001058 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001059 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001060
1061 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1062 F != FEnd; ++F) {
1063 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1064 if (Delete->isUsualDeallocationFunction()) {
1065 Operator = Delete;
1066 return false;
1067 }
1068 }
1069
1070 // We did find operator delete/operator delete[] declarations, but
1071 // none of them were suitable.
1072 if (!Found.empty()) {
1073 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1074 << Name << RD;
1075
1076 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1077 F != FEnd; ++F) {
1078 Diag((*F)->getLocation(),
1079 diag::note_delete_member_function_declared_here)
1080 << Name;
1081 }
1082
1083 return true;
1084 }
1085
1086 // Look for a global declaration.
1087 DeclareGlobalNewDelete();
1088 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1089
1090 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1091 Expr* DeallocArgs[1];
1092 DeallocArgs[0] = &Null;
1093 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1094 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1095 Operator))
1096 return true;
1097
1098 assert(Operator && "Did not find a deallocation function!");
1099 return false;
1100}
1101
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001102/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1103/// @code ::delete ptr; @endcode
1104/// or
1105/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001106Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001107Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001108 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001109 // C++ [expr.delete]p1:
1110 // The operand shall have a pointer type, or a class type having a single
1111 // conversion function to a pointer type. The result has type void.
1112 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001113 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1114
Anders Carlssond67c4c32009-08-16 20:29:29 +00001115 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Sebastian Redlf53597f2009-03-15 17:47:39 +00001117 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001118 if (!Ex->isTypeDependent()) {
1119 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001120
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001121 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001122 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +00001123 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00001124 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001125
John McCalleec51cf2010-01-20 00:46:10 +00001126 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001127 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001128 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +00001129 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001130 continue;
1131
John McCallba135432009-11-21 08:51:07 +00001132 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001133
1134 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1135 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1136 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001137 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001138 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001139 if (ObjectPtrConversions.size() == 1) {
1140 // We have a single conversion to a pointer-to-object type. Perform
1141 // that conversion.
1142 Operand.release();
1143 if (!PerformImplicitConversion(Ex,
1144 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001145 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001146 Operand = Owned(Ex);
1147 Type = Ex->getType();
1148 }
1149 }
1150 else if (ObjectPtrConversions.size() > 1) {
1151 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1152 << Type << Ex->getSourceRange();
1153 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
1154 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +00001155 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001156 }
1157 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001158 }
Sebastian Redl28507842009-02-26 14:39:58 +00001159 }
1160
Sebastian Redlf53597f2009-03-15 17:47:39 +00001161 if (!Type->isPointerType())
1162 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1163 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001164
Ted Kremenek6217b802009-07-29 21:53:49 +00001165 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001166 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001167 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1168 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001169 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001170 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001171 PDiag(diag::warn_delete_incomplete)
1172 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001173 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001174
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001175 // C++ [expr.delete]p2:
1176 // [Note: a pointer to a const type can be the operand of a
1177 // delete-expression; it is not necessary to cast away the constness
1178 // (5.2.11) of the pointer expression before it is used as the operand
1179 // of the delete-expression. ]
1180 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1181 CastExpr::CK_NoOp);
1182
1183 // Update the operand.
1184 Operand.take();
1185 Operand = ExprArg(*this, Ex);
1186
Anders Carlssond67c4c32009-08-16 20:29:29 +00001187 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1188 ArrayForm ? OO_Array_Delete : OO_Delete);
1189
Anders Carlsson78f74552009-11-15 18:45:20 +00001190 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1191 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1192
1193 if (!UseGlobal &&
1194 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001195 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001196
Anders Carlsson78f74552009-11-15 18:45:20 +00001197 if (!RD->hasTrivialDestructor())
1198 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001199 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001200 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001201 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001202
Anders Carlssond67c4c32009-08-16 20:29:29 +00001203 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001204 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001205 DeclareGlobalNewDelete();
1206 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001207 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001208 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001209 OperatorDelete))
1210 return ExprError();
1211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Sebastian Redl28507842009-02-26 14:39:58 +00001213 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001214 }
1215
Sebastian Redlf53597f2009-03-15 17:47:39 +00001216 Operand.release();
1217 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001218 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001219}
1220
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001221/// \brief Check the use of the given variable as a C++ condition in an if,
1222/// while, do-while, or switch statement.
1223Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1224 QualType T = ConditionVar->getType();
1225
1226 // C++ [stmt.select]p2:
1227 // The declarator shall not specify a function or an array.
1228 if (T->isFunctionType())
1229 return ExprError(Diag(ConditionVar->getLocation(),
1230 diag::err_invalid_use_of_function_type)
1231 << ConditionVar->getSourceRange());
1232 else if (T->isArrayType())
1233 return ExprError(Diag(ConditionVar->getLocation(),
1234 diag::err_invalid_use_of_array_type)
1235 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001236
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001237 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1238 ConditionVar->getLocation(),
1239 ConditionVar->getType().getNonReferenceType()));
1240}
1241
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001242/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1243bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1244 // C++ 6.4p4:
1245 // The value of a condition that is an initialized declaration in a statement
1246 // other than a switch statement is the value of the declared variable
1247 // implicitly converted to type bool. If that conversion is ill-formed, the
1248 // program is ill-formed.
1249 // The value of a condition that is an expression is the value of the
1250 // expression, implicitly converted to bool.
1251 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001252 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001253}
Douglas Gregor77a52232008-09-12 00:47:35 +00001254
1255/// Helper function to determine whether this is the (deprecated) C++
1256/// conversion from a string literal to a pointer to non-const char or
1257/// non-const wchar_t (for narrow and wide string literals,
1258/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001259bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001260Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1261 // Look inside the implicit cast, if it exists.
1262 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1263 From = Cast->getSubExpr();
1264
1265 // A string literal (2.13.4) that is not a wide string literal can
1266 // be converted to an rvalue of type "pointer to char"; a wide
1267 // string literal can be converted to an rvalue of type "pointer
1268 // to wchar_t" (C++ 4.2p2).
1269 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001270 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001271 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001272 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001273 // This conversion is considered only when there is an
1274 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001275 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001276 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1277 (!StrLit->isWide() &&
1278 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1279 ToPointeeType->getKind() == BuiltinType::Char_S))))
1280 return true;
1281 }
1282
1283 return false;
1284}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001285
1286/// PerformImplicitConversion - Perform an implicit conversion of the
1287/// expression From to the type ToType. Returns true if there was an
1288/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001289/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001290/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001291/// explicit user-defined conversions are permitted. @p Elidable should be true
1292/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1293/// resolution works differently in that case.
1294bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001295Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001296 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001297 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001298 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001299 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001300 Elidable, ICS);
1301}
1302
1303bool
1304Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001305 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001306 bool Elidable,
1307 ImplicitConversionSequence& ICS) {
John McCall1d318332010-01-12 00:44:57 +00001308 ICS.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00001309 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001310 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001311 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001312 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001313 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001314 /*ForceRValue=*/true,
1315 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001316 }
John McCall1d318332010-01-12 00:44:57 +00001317 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001318 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001319 /*SuppressUserConversions=*/false,
1320 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001321 /*ForceRValue=*/false,
1322 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001323 }
Douglas Gregor68647482009-12-16 03:45:30 +00001324 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001325}
1326
1327/// PerformImplicitConversion - Perform an implicit conversion of the
1328/// expression From to the type ToType using the pre-computed implicit
1329/// conversion sequence ICS. Returns true if there was an error, false
1330/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001331/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001332/// used in the error message.
1333bool
1334Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1335 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001336 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001337 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001338 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001339 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001340 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001341 return true;
1342 break;
1343
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001344 case ImplicitConversionSequence::UserDefinedConversion: {
1345
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001346 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1347 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001348 QualType BeforeToType;
1349 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001350 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001351
1352 // If the user-defined conversion is specified by a conversion function,
1353 // the initial standard conversion sequence converts the source type to
1354 // the implicit object parameter of the conversion function.
1355 BeforeToType = Context.getTagDeclType(Conv->getParent());
1356 } else if (const CXXConstructorDecl *Ctor =
1357 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001358 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001359 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001360 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001361 // If the user-defined conversion is specified by a constructor, the
1362 // initial standard conversion sequence converts the source type to the
1363 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001364 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1365 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001366 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001367 else
1368 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001369 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001370 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001371 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001372 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001373 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001374 return true;
1375 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001376
Anders Carlsson0aebc812009-09-09 21:33:21 +00001377 OwningExprResult CastArg
1378 = BuildCXXCastArgument(From->getLocStart(),
1379 ToType.getNonReferenceType(),
1380 CastKind, cast<CXXMethodDecl>(FD),
1381 Owned(From));
1382
1383 if (CastArg.isInvalid())
1384 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001385
1386 From = CastArg.takeAs<Expr>();
1387
Eli Friedmand8889622009-11-27 04:41:50 +00001388 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001389 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001390 }
John McCall1d318332010-01-12 00:44:57 +00001391
1392 case ImplicitConversionSequence::AmbiguousConversion:
1393 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1394 PDiag(diag::err_typecheck_ambiguous_condition)
1395 << From->getSourceRange());
1396 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001397
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001398 case ImplicitConversionSequence::EllipsisConversion:
1399 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001400 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001401
1402 case ImplicitConversionSequence::BadConversion:
1403 return true;
1404 }
1405
1406 // Everything went well.
1407 return false;
1408}
1409
1410/// PerformImplicitConversion - Perform an implicit conversion of the
1411/// expression From to the type ToType by following the standard
1412/// conversion sequence SCS. Returns true if there was an error, false
1413/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001414/// expression. Flavor is the context in which we're performing this
1415/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001416bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001417Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001418 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001419 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001420 // Overall FIXME: we are recomputing too many types here and doing far too
1421 // much extra work. What this means is that we need to keep track of more
1422 // information that is computed when we try the implicit conversion initially,
1423 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001424 QualType FromType = From->getType();
1425
Douglas Gregor225c41e2008-11-03 19:09:14 +00001426 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001427 // FIXME: When can ToType be a reference type?
1428 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001429 if (SCS.Second == ICK_Derived_To_Base) {
1430 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1431 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1432 MultiExprArg(*this, (void **)&From, 1),
1433 /*FIXME:ConstructLoc*/SourceLocation(),
1434 ConstructorArgs))
1435 return true;
1436 OwningExprResult FromResult =
1437 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1438 ToType, SCS.CopyConstructor,
1439 move_arg(ConstructorArgs));
1440 if (FromResult.isInvalid())
1441 return true;
1442 From = FromResult.takeAs<Expr>();
1443 return false;
1444 }
Mike Stump1eb44332009-09-09 15:08:12 +00001445 OwningExprResult FromResult =
1446 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1447 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001448 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001450 if (FromResult.isInvalid())
1451 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001453 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001454 return false;
1455 }
1456
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001457 // Perform the first implicit conversion.
1458 switch (SCS.First) {
1459 case ICK_Identity:
1460 case ICK_Lvalue_To_Rvalue:
1461 // Nothing to do.
1462 break;
1463
1464 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001465 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001466 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001467 break;
1468
1469 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001470 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001471 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1472 if (!Fn)
1473 return true;
1474
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001475 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1476 return true;
1477
Anders Carlsson96ad5332009-10-21 17:16:23 +00001478 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001479 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001480
Sebastian Redl759986e2009-10-17 20:50:27 +00001481 // If there's already an address-of operator in the expression, we have
1482 // the right type already, and the code below would just introduce an
1483 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001484 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001485 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001486 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001487 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001488 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001489 break;
1490
1491 default:
1492 assert(false && "Improper first standard conversion");
1493 break;
1494 }
1495
1496 // Perform the second implicit conversion
1497 switch (SCS.Second) {
1498 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001499 // If both sides are functions (or pointers/references to them), there could
1500 // be incompatible exception declarations.
1501 if (CheckExceptionSpecCompatibility(From, ToType))
1502 return true;
1503 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001504 break;
1505
Douglas Gregor43c79c22009-12-09 00:47:37 +00001506 case ICK_NoReturn_Adjustment:
1507 // If both sides are functions (or pointers/references to them), there could
1508 // be incompatible exception declarations.
1509 if (CheckExceptionSpecCompatibility(From, ToType))
1510 return true;
1511
1512 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1513 CastExpr::CK_NoOp);
1514 break;
1515
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001516 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001517 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001518 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1519 break;
1520
1521 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001522 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001523 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1524 break;
1525
1526 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001527 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001528 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1529 break;
1530
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001531 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001532 if (ToType->isFloatingType())
1533 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1534 else
1535 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1536 break;
1537
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001538 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001539 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1540 break;
1541
Douglas Gregorf9201e02009-02-11 23:02:49 +00001542 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001543 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001544 break;
1545
Anders Carlsson61faec12009-09-12 04:46:44 +00001546 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001547 if (SCS.IncompatibleObjC) {
1548 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001549 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001550 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001551 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001552 << From->getSourceRange();
1553 }
1554
Anders Carlsson61faec12009-09-12 04:46:44 +00001555
1556 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001557 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001558 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001559 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001560 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001561 }
1562
1563 case ICK_Pointer_Member: {
1564 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001565 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001566 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001567 if (CheckExceptionSpecCompatibility(From, ToType))
1568 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001569 ImpCastExprToType(From, ToType, Kind);
1570 break;
1571 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001572 case ICK_Boolean_Conversion: {
1573 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1574 if (FromType->isMemberPointerType())
1575 Kind = CastExpr::CK_MemberPointerToBoolean;
1576
1577 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001578 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001579 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001580
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001581 case ICK_Derived_To_Base:
1582 if (CheckDerivedToBaseConversion(From->getType(),
1583 ToType.getNonReferenceType(),
1584 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001585 From->getSourceRange(),
1586 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001587 return true;
1588 ImpCastExprToType(From, ToType.getNonReferenceType(),
1589 CastExpr::CK_DerivedToBase);
1590 break;
1591
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001592 default:
1593 assert(false && "Improper second standard conversion");
1594 break;
1595 }
1596
1597 switch (SCS.Third) {
1598 case ICK_Identity:
1599 // Nothing to do.
1600 break;
1601
1602 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001603 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1604 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001605 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001606 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001607 ToType->isLValueReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001608 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001609
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001610 default:
1611 assert(false && "Improper second standard conversion");
1612 break;
1613 }
1614
1615 return false;
1616}
1617
Sebastian Redl64b45f72009-01-05 20:52:13 +00001618Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1619 SourceLocation KWLoc,
1620 SourceLocation LParen,
1621 TypeTy *Ty,
1622 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001623 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001625 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1626 // all traits except __is_class, __is_enum and __is_union require a the type
1627 // to be complete.
1628 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001629 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001630 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001631 return ExprError();
1632 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001633
1634 // There is no point in eagerly computing the value. The traits are designed
1635 // to be used from type trait templates, so Ty will be a template parameter
1636 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001637 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1638 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001639}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001640
1641QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001642 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001643 const char *OpSpelling = isIndirect ? "->*" : ".*";
1644 // C++ 5.5p2
1645 // The binary operator .* [p3: ->*] binds its second operand, which shall
1646 // be of type "pointer to member of T" (where T is a completely-defined
1647 // class type) [...]
1648 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001649 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001650 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001651 Diag(Loc, diag::err_bad_memptr_rhs)
1652 << OpSpelling << RType << rex->getSourceRange();
1653 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001654 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001655
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001656 QualType Class(MemPtr->getClass(), 0);
1657
1658 // C++ 5.5p2
1659 // [...] to its first operand, which shall be of class T or of a class of
1660 // which T is an unambiguous and accessible base class. [p3: a pointer to
1661 // such a class]
1662 QualType LType = lex->getType();
1663 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001664 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001665 LType = Ptr->getPointeeType().getNonReferenceType();
1666 else {
1667 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001668 << OpSpelling << 1 << LType
1669 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001670 return QualType();
1671 }
1672 }
1673
Douglas Gregora4923eb2009-11-16 21:35:15 +00001674 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001675 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1676 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001677 // FIXME: Would it be useful to print full ambiguity paths, or is that
1678 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001679 if (!IsDerivedFrom(LType, Class, Paths) ||
1680 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1681 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001682 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001683 return QualType();
1684 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001685 // Cast LHS to type of use.
1686 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1687 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1688 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001689 }
1690
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001691 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001692 // Diagnose use of pointer-to-member type which when used as
1693 // the functional cast in a pointer-to-member expression.
1694 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1695 return QualType();
1696 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001697 // C++ 5.5p2
1698 // The result is an object or a function of the type specified by the
1699 // second operand.
1700 // The cv qualifiers are the union of those in the pointer and the left side,
1701 // in accordance with 5.5p5 and 5.2.5.
1702 // FIXME: This returns a dereferenced member function pointer as a normal
1703 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001704 // calling them. There's also a GCC extension to get a function pointer to the
1705 // thing, which is another complication, because this type - unlike the type
1706 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001707 // argument.
1708 // We probably need a "MemberFunctionClosureType" or something like that.
1709 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001710 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001711 return Result;
1712}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001713
1714/// \brief Get the target type of a standard or user-defined conversion.
1715static QualType TargetType(const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001716 switch (ICS.getKind()) {
1717 case ImplicitConversionSequence::StandardConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001718 return ICS.Standard.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001719 case ImplicitConversionSequence::UserDefinedConversion:
Douglas Gregorad323a82010-01-27 03:51:04 +00001720 return ICS.UserDefined.After.getToType(2);
John McCall1d318332010-01-12 00:44:57 +00001721 case ImplicitConversionSequence::AmbiguousConversion:
1722 return ICS.Ambiguous.getToType();
1723 case ImplicitConversionSequence::EllipsisConversion:
1724 case ImplicitConversionSequence::BadConversion:
1725 llvm_unreachable("function not valid for ellipsis or bad conversions");
1726 }
1727 return QualType(); // silence warnings
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001728}
1729
1730/// \brief Try to convert a type to another according to C++0x 5.16p3.
1731///
1732/// This is part of the parameter validation for the ? operator. If either
1733/// value operand is a class type, the two operands are attempted to be
1734/// converted to each other. This function does the conversion in one direction.
1735/// It emits a diagnostic and returns true only if it finds an ambiguous
1736/// conversion.
1737static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1738 SourceLocation QuestionLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001739 ImplicitConversionSequence &ICS) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001740 // C++0x 5.16p3
1741 // The process for determining whether an operand expression E1 of type T1
1742 // can be converted to match an operand expression E2 of type T2 is defined
1743 // as follows:
1744 // -- If E2 is an lvalue:
1745 if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1746 // E1 can be converted to match E2 if E1 can be implicitly converted to
1747 // type "lvalue reference to T2", subject to the constraint that in the
1748 // conversion the reference must bind directly to E1.
1749 if (!Self.CheckReferenceInit(From,
1750 Self.Context.getLValueReferenceType(To->getType()),
Douglas Gregor739d8282009-09-23 23:04:10 +00001751 To->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001752 /*SuppressUserConversions=*/false,
1753 /*AllowExplicit=*/false,
1754 /*ForceRValue=*/false,
1755 &ICS))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001756 {
John McCall1d318332010-01-12 00:44:57 +00001757 assert((ICS.isStandard() || ICS.isUserDefined()) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001758 "expected a definite conversion");
1759 bool DirectBinding =
John McCall1d318332010-01-12 00:44:57 +00001760 ICS.isStandard() ? ICS.Standard.DirectBinding
1761 : ICS.UserDefined.After.DirectBinding;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001762 if (DirectBinding)
1763 return false;
1764 }
1765 }
John McCall1d318332010-01-12 00:44:57 +00001766 ICS.setBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001767 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1768 // -- if E1 and E2 have class type, and the underlying class types are
1769 // the same or one is a base class of the other:
1770 QualType FTy = From->getType();
1771 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001772 const RecordType *FRec = FTy->getAs<RecordType>();
1773 const RecordType *TRec = TTy->getAs<RecordType>();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001774 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1775 if (FRec && TRec && (FRec == TRec ||
1776 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1777 // E1 can be converted to match E2 if the class of T2 is the
1778 // same type as, or a base class of, the class of T1, and
1779 // [cv2 > cv1].
1780 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1781 // Could still fail if there's no copy constructor.
1782 // FIXME: Is this a hard error then, or just a conversion failure? The
1783 // standard doesn't say.
Mike Stump1eb44332009-09-09 15:08:12 +00001784 ICS = Self.TryCopyInitialization(From, TTy,
Anders Carlssond28b4282009-08-27 17:18:13 +00001785 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00001786 /*ForceRValue=*/false,
1787 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001788 }
1789 } else {
1790 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1791 // implicitly converted to the type that expression E2 would have
1792 // if E2 were converted to an rvalue.
1793 // First find the decayed type.
1794 if (TTy->isFunctionType())
1795 TTy = Self.Context.getPointerType(TTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001796 else if (TTy->isArrayType())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001797 TTy = Self.Context.getArrayDecayedType(TTy);
1798
1799 // Now try the implicit conversion.
1800 // FIXME: This doesn't detect ambiguities.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001801 ICS = Self.TryImplicitConversion(From, TTy,
1802 /*SuppressUserConversions=*/false,
1803 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00001804 /*ForceRValue=*/false,
1805 /*InOverloadResolution=*/false);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001806 }
1807 return false;
1808}
1809
1810/// \brief Try to find a common type for two according to C++0x 5.16p5.
1811///
1812/// This is part of the parameter validation for the ? operator. If either
1813/// value operand is a class type, overload resolution is used to find a
1814/// conversion to a common type.
1815static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1816 SourceLocation Loc) {
1817 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00001818 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00001819 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001820
1821 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001822 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001823 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001824 // We found a match. Perform the conversions on the arguments and move on.
1825 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00001826 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001827 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00001828 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001829 break;
1830 return false;
1831
Douglas Gregor20093b42009-12-09 23:02:17 +00001832 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001833 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1834 << LHS->getType() << RHS->getType()
1835 << LHS->getSourceRange() << RHS->getSourceRange();
1836 return true;
1837
Douglas Gregor20093b42009-12-09 23:02:17 +00001838 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001839 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1840 << LHS->getType() << RHS->getType()
1841 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00001842 // FIXME: Print the possible common types by printing the return types of
1843 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001844 break;
1845
Douglas Gregor20093b42009-12-09 23:02:17 +00001846 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001847 assert(false && "Conditional operator has only built-in overloads");
1848 break;
1849 }
1850 return true;
1851}
1852
Sebastian Redl76458502009-04-17 16:30:52 +00001853/// \brief Perform an "extended" implicit conversion as returned by
1854/// TryClassUnification.
1855///
1856/// TryClassUnification generates ICSs that include reference bindings.
1857/// PerformImplicitConversion is not suitable for this; it chokes if the
1858/// second part of a standard conversion is ICK_DerivedToBase. This function
1859/// handles the reference binding specially.
1860static bool ConvertForConditional(Sema &Self, Expr *&E,
Mike Stump1eb44332009-09-09 15:08:12 +00001861 const ImplicitConversionSequence &ICS) {
John McCall1d318332010-01-12 00:44:57 +00001862 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001863 assert(ICS.Standard.DirectBinding &&
1864 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001865 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1866 // redoing all the work.
1867 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001868 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001869 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001870 /*SuppressUserConversions=*/false,
1871 /*AllowExplicit=*/false,
1872 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001873 }
John McCall1d318332010-01-12 00:44:57 +00001874 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) {
Sebastian Redl76458502009-04-17 16:30:52 +00001875 assert(ICS.UserDefined.After.DirectBinding &&
1876 "TryClassUnification should never generate indirect ref bindings");
Sebastian Redla5cd2cd2009-04-26 11:21:02 +00001877 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001878 TargetType(ICS)),
Douglas Gregor739d8282009-09-23 23:04:10 +00001879 /*FIXME:*/E->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00001880 /*SuppressUserConversions=*/false,
1881 /*AllowExplicit=*/false,
1882 /*ForceRValue=*/false);
Sebastian Redl76458502009-04-17 16:30:52 +00001883 }
Douglas Gregor68647482009-12-16 03:45:30 +00001884 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting))
Sebastian Redl76458502009-04-17 16:30:52 +00001885 return true;
1886 return false;
1887}
1888
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001889/// \brief Check the operands of ?: under C++ semantics.
1890///
1891/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1892/// extension. In this case, LHS == Cond. (But they're not aliases.)
1893QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1894 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001895 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1896 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001897
1898 // C++0x 5.16p1
1899 // The first expression is contextually converted to bool.
1900 if (!Cond->isTypeDependent()) {
1901 if (CheckCXXBooleanCondition(Cond))
1902 return QualType();
1903 }
1904
1905 // Either of the arguments dependent?
1906 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1907 return Context.DependentTy;
1908
John McCallb13c87f2009-11-05 09:23:39 +00001909 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
1910
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001911 // C++0x 5.16p2
1912 // If either the second or the third operand has type (cv) void, ...
1913 QualType LTy = LHS->getType();
1914 QualType RTy = RHS->getType();
1915 bool LVoid = LTy->isVoidType();
1916 bool RVoid = RTy->isVoidType();
1917 if (LVoid || RVoid) {
1918 // ... then the [l2r] conversions are performed on the second and third
1919 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00001920 DefaultFunctionArrayLvalueConversion(LHS);
1921 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001922 LTy = LHS->getType();
1923 RTy = RHS->getType();
1924
1925 // ... and one of the following shall hold:
1926 // -- The second or the third operand (but not both) is a throw-
1927 // expression; the result is of the type of the other and is an rvalue.
1928 bool LThrow = isa<CXXThrowExpr>(LHS);
1929 bool RThrow = isa<CXXThrowExpr>(RHS);
1930 if (LThrow && !RThrow)
1931 return RTy;
1932 if (RThrow && !LThrow)
1933 return LTy;
1934
1935 // -- Both the second and third operands have type void; the result is of
1936 // type void and is an rvalue.
1937 if (LVoid && RVoid)
1938 return Context.VoidTy;
1939
1940 // Neither holds, error.
1941 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1942 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1943 << LHS->getSourceRange() << RHS->getSourceRange();
1944 return QualType();
1945 }
1946
1947 // Neither is void.
1948
1949 // C++0x 5.16p3
1950 // Otherwise, if the second and third operand have different types, and
1951 // either has (cv) class type, and attempt is made to convert each of those
1952 // operands to the other.
1953 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1954 (LTy->isRecordType() || RTy->isRecordType())) {
1955 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1956 // These return true if a single direction is already ambiguous.
1957 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1958 return QualType();
1959 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1960 return QualType();
1961
John McCall1d318332010-01-12 00:44:57 +00001962 bool HaveL2R = !ICSLeftToRight.isBad();
1963 bool HaveR2L = !ICSRightToLeft.isBad();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001964 // If both can be converted, [...] the program is ill-formed.
1965 if (HaveL2R && HaveR2L) {
1966 Diag(QuestionLoc, diag::err_conditional_ambiguous)
1967 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1968 return QualType();
1969 }
1970
1971 // If exactly one conversion is possible, that conversion is applied to
1972 // the chosen operand and the converted operands are used in place of the
1973 // original operands for the remainder of this section.
1974 if (HaveL2R) {
Sebastian Redl76458502009-04-17 16:30:52 +00001975 if (ConvertForConditional(*this, LHS, ICSLeftToRight))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001976 return QualType();
1977 LTy = LHS->getType();
1978 } else if (HaveR2L) {
Sebastian Redl76458502009-04-17 16:30:52 +00001979 if (ConvertForConditional(*this, RHS, ICSRightToLeft))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001980 return QualType();
1981 RTy = RHS->getType();
1982 }
1983 }
1984
1985 // C++0x 5.16p4
1986 // If the second and third operands are lvalues and have the same type,
1987 // the result is of that type [...]
1988 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1989 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1990 RHS->isLvalue(Context) == Expr::LV_Valid)
1991 return LTy;
1992
1993 // C++0x 5.16p5
1994 // Otherwise, the result is an rvalue. If the second and third operands
1995 // do not have the same type, and either has (cv) class type, ...
1996 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1997 // ... overload resolution is used to determine the conversions (if any)
1998 // to be applied to the operands. If the overload resolution fails, the
1999 // program is ill-formed.
2000 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2001 return QualType();
2002 }
2003
2004 // C++0x 5.16p6
2005 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2006 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002007 DefaultFunctionArrayLvalueConversion(LHS);
2008 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002009 LTy = LHS->getType();
2010 RTy = RHS->getType();
2011
2012 // After those conversions, one of the following shall hold:
2013 // -- The second and third operands have the same type; the result
2014 // is of that type.
2015 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2016 return LTy;
2017
2018 // -- The second and third operands have arithmetic or enumeration type;
2019 // the usual arithmetic conversions are performed to bring them to a
2020 // common type, and the result is of that type.
2021 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2022 UsualArithmeticConversions(LHS, RHS);
2023 return LHS->getType();
2024 }
2025
2026 // -- The second and third operands have pointer type, or one has pointer
2027 // type and the other is a null pointer constant; pointer conversions
2028 // and qualification conversions are performed to bring them to their
2029 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002030 // -- The second and third operands have pointer to member type, or one has
2031 // pointer to member type and the other is a null pointer constant;
2032 // pointer to member conversions and qualification conversions are
2033 // performed to bring them to a common type, whose cv-qualification
2034 // shall match the cv-qualification of either the second or the third
2035 // operand. The result is of the common type.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002036 QualType Composite = FindCompositePointerType(LHS, RHS);
2037 if (!Composite.isNull())
2038 return Composite;
Fariborz Jahanian55016362009-12-10 20:46:08 +00002039
2040 // Similarly, attempt to find composite type of twp objective-c pointers.
2041 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2042 if (!Composite.isNull())
2043 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002044
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002045 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2046 << LHS->getType() << RHS->getType()
2047 << LHS->getSourceRange() << RHS->getSourceRange();
2048 return QualType();
2049}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002050
2051/// \brief Find a merged pointer type and convert the two expressions to it.
2052///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002053/// This finds the composite pointer type (or member pointer type) for @p E1
2054/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2055/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002056/// It does not emit diagnostics.
2057QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
2058 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2059 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002061 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2062 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002063 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002064
2065 // C++0x 5.9p2
2066 // Pointer conversions and qualification conversions are performed on
2067 // pointer operands to bring them to their composite pointer type. If
2068 // one operand is a null pointer constant, the composite pointer type is
2069 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002070 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002071 if (T2->isMemberPointerType())
2072 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2073 else
2074 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002075 return T2;
2076 }
Douglas Gregorce940492009-09-25 04:25:58 +00002077 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002078 if (T1->isMemberPointerType())
2079 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2080 else
2081 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002082 return T1;
2083 }
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Douglas Gregor20b3e992009-08-24 17:42:35 +00002085 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002086 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2087 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002088 return QualType();
2089
2090 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2091 // the other has type "pointer to cv2 T" and the composite pointer type is
2092 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2093 // Otherwise, the composite pointer type is a pointer type similar to the
2094 // type of one of the operands, with a cv-qualification signature that is
2095 // the union of the cv-qualification signatures of the operand types.
2096 // In practice, the first part here is redundant; it's subsumed by the second.
2097 // What we do here is, we build the two possible composite types, and try the
2098 // conversions in both directions. If only one works, or if the two composite
2099 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002100 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002101 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2102 QualifierVector QualifierUnion;
2103 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2104 ContainingClassVector;
2105 ContainingClassVector MemberOfClass;
2106 QualType Composite1 = Context.getCanonicalType(T1),
2107 Composite2 = Context.getCanonicalType(T2);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002108 do {
2109 const PointerType *Ptr1, *Ptr2;
2110 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2111 (Ptr2 = Composite2->getAs<PointerType>())) {
2112 Composite1 = Ptr1->getPointeeType();
2113 Composite2 = Ptr2->getPointeeType();
2114 QualifierUnion.push_back(
2115 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2116 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2117 continue;
2118 }
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Douglas Gregor20b3e992009-08-24 17:42:35 +00002120 const MemberPointerType *MemPtr1, *MemPtr2;
2121 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2122 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2123 Composite1 = MemPtr1->getPointeeType();
2124 Composite2 = MemPtr2->getPointeeType();
2125 QualifierUnion.push_back(
2126 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2127 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2128 MemPtr2->getClass()));
2129 continue;
2130 }
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Douglas Gregor20b3e992009-08-24 17:42:35 +00002132 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Douglas Gregor20b3e992009-08-24 17:42:35 +00002134 // Cannot unwrap any more types.
2135 break;
2136 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Douglas Gregor20b3e992009-08-24 17:42:35 +00002138 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002139 ContainingClassVector::reverse_iterator MOC
2140 = MemberOfClass.rbegin();
2141 for (QualifierVector::reverse_iterator
2142 I = QualifierUnion.rbegin(),
2143 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002144 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002145 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002146 if (MOC->first && MOC->second) {
2147 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002148 Composite1 = Context.getMemberPointerType(
2149 Context.getQualifiedType(Composite1, Quals),
2150 MOC->first);
2151 Composite2 = Context.getMemberPointerType(
2152 Context.getQualifiedType(Composite2, Quals),
2153 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002154 } else {
2155 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002156 Composite1
2157 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2158 Composite2
2159 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002160 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002161 }
2162
Mike Stump1eb44332009-09-09 15:08:12 +00002163 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002164 TryImplicitConversion(E1, 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 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002170 TryImplicitConversion(E2, Composite1,
2171 /*SuppressUserConversions=*/false,
2172 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002173 /*ForceRValue=*/false,
2174 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002176 ImplicitConversionSequence E1ToC2, E2ToC2;
John McCall1d318332010-01-12 00:44:57 +00002177 E1ToC2.setBad();
John McCalladbb8f82010-01-13 09:16:55 +00002178 E2ToC2.setBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002179 if (Context.getCanonicalType(Composite1) !=
2180 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002181 E1ToC2 = TryImplicitConversion(E1, Composite2,
2182 /*SuppressUserConversions=*/false,
2183 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002184 /*ForceRValue=*/false,
2185 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002186 E2ToC2 = TryImplicitConversion(E2, Composite2,
2187 /*SuppressUserConversions=*/false,
2188 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002189 /*ForceRValue=*/false,
2190 /*InOverloadResolution=*/false);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002191 }
2192
John McCall1d318332010-01-12 00:44:57 +00002193 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
2194 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002195 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002196 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2197 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002198 return Composite1;
2199 }
2200 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002201 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2202 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002203 return Composite2;
2204 }
2205 return QualType();
2206}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002207
Anders Carlssondef11992009-05-30 20:36:53 +00002208Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002209 if (!Context.getLangOptions().CPlusPlus)
2210 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Douglas Gregor51326552009-12-24 18:51:59 +00002212 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2213
Ted Kremenek6217b802009-07-29 21:53:49 +00002214 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002215 if (!RT)
2216 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002217
John McCall86ff3082010-02-04 22:26:26 +00002218 // If this is the result of a call expression, our source might
2219 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002220 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2221 QualType Ty = CE->getCallee()->getType();
2222 if (const PointerType *PT = Ty->getAs<PointerType>())
2223 Ty = PT->getPointeeType();
2224
John McCall183700f2009-09-21 23:43:11 +00002225 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002226 if (FTy->getResultType()->isReferenceType())
2227 return Owned(E);
2228 }
John McCall86ff3082010-02-04 22:26:26 +00002229
2230 // That should be enough to guarantee that this type is complete.
2231 // If it has a trivial destructor, we can avoid the extra copy.
2232 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2233 if (RD->hasTrivialDestructor())
2234 return Owned(E);
2235
Mike Stump1eb44332009-09-09 15:08:12 +00002236 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002237 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002238 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002239 if (CXXDestructorDecl *Destructor =
2240 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2241 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002242 // FIXME: Add the temporary to the temporaries vector.
2243 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2244}
2245
Anders Carlsson0ece4912009-12-15 20:51:39 +00002246Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002247 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002249 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2250 assert(ExprTemporaries.size() >= FirstTemporary);
2251 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002252 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002254 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002255 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002256 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002257 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2258 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002260 return E;
2261}
2262
Douglas Gregor90f93822009-12-22 22:17:25 +00002263Sema::OwningExprResult
2264Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2265 if (SubExpr.isInvalid())
2266 return ExprError();
2267
2268 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2269}
2270
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002271FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2272 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2273 assert(ExprTemporaries.size() >= FirstTemporary);
2274
2275 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2276 CXXTemporary **Temporaries =
2277 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2278
2279 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2280
2281 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2282 ExprTemporaries.end());
2283
2284 return E;
2285}
2286
Mike Stump1eb44332009-09-09 15:08:12 +00002287Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002288Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
2289 tok::TokenKind OpKind, TypeTy *&ObjectType) {
2290 // Since this might be a postfix expression, get rid of ParenListExprs.
2291 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002293 Expr *BaseExpr = (Expr*)Base.get();
2294 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002296 QualType BaseType = BaseExpr->getType();
2297 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002298 // If we have a pointer to a dependent type and are using the -> operator,
2299 // the object type is the type that the pointer points to. We might still
2300 // have enough information about that type to do something useful.
2301 if (OpKind == tok::arrow)
2302 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2303 BaseType = Ptr->getPointeeType();
2304
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002305 ObjectType = BaseType.getAsOpaquePtr();
2306 return move(Base);
2307 }
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002309 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002310 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002311 // returned, with the original second operand.
2312 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002313 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002314 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002315 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002316 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002317
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002318 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002319 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002320 BaseExpr = (Expr*)Base.get();
2321 if (BaseExpr == NULL)
2322 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002323 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002324 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002325 BaseType = BaseExpr->getType();
2326 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002327 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002328 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002329 for (unsigned i = 0; i < Locations.size(); i++)
2330 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002331 return ExprError();
2332 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002333 }
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Douglas Gregor31658df2009-11-20 19:58:21 +00002335 if (BaseType->isPointerType())
2336 BaseType = BaseType->getPointeeType();
2337 }
Mike Stump1eb44332009-09-09 15:08:12 +00002338
2339 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002340 // vector types or Objective-C interfaces. Just return early and let
2341 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002342 if (!BaseType->isRecordType()) {
2343 // C++ [basic.lookup.classref]p2:
2344 // [...] If the type of the object expression is of pointer to scalar
2345 // type, the unqualified-id is looked up in the context of the complete
2346 // postfix-expression.
2347 ObjectType = 0;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002348 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002349 }
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Douglas Gregor03c57052009-11-17 05:17:33 +00002351 // The object type must be complete (or dependent).
2352 if (!BaseType->isDependentType() &&
2353 RequireCompleteType(OpLoc, BaseType,
2354 PDiag(diag::err_incomplete_member_access)))
2355 return ExprError();
2356
Douglas Gregorc68afe22009-09-03 21:38:09 +00002357 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002358 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002359 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002360 // type C (or of pointer to a class type C), the unqualified-id is looked
2361 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002362 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregor03c57052009-11-17 05:17:33 +00002363
Mike Stump1eb44332009-09-09 15:08:12 +00002364 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002365}
2366
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002367CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2368 CXXMethodDecl *Method) {
Eli Friedman772fffa2009-12-09 04:53:56 +00002369 if (PerformObjectArgumentInitialization(Exp, Method))
2370 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2371
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002372 MemberExpr *ME =
2373 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2374 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002375 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002376 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2377 CXXMemberCallExpr *CE =
2378 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2379 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002380 return CE;
2381}
2382
Anders Carlsson0aebc812009-09-09 21:33:21 +00002383Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2384 QualType Ty,
2385 CastExpr::CastKind Kind,
2386 CXXMethodDecl *Method,
2387 ExprArg Arg) {
2388 Expr *From = Arg.takeAs<Expr>();
2389
2390 switch (Kind) {
2391 default: assert(0 && "Unhandled cast kind!");
2392 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002393 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2394
2395 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2396 MultiExprArg(*this, (void **)&From, 1),
2397 CastLoc, ConstructorArgs))
2398 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002399
2400 OwningExprResult Result =
2401 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2402 move_arg(ConstructorArgs));
2403 if (Result.isInvalid())
2404 return ExprError();
2405
2406 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002407 }
2408
2409 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002410 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002411
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002412 // Create an implicit call expr that calls it.
2413 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002414 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002415 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002416 }
2417}
2418
Anders Carlsson165a0a02009-05-17 18:41:29 +00002419Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2420 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002421 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002422 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002423
Anders Carlsson165a0a02009-05-17 18:41:29 +00002424 return Owned(FullExpr);
2425}