blob: 48daf84d6b29866465673b84f8d69ba3ee08d778 [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"
Douglas Gregorb57fb492010-02-24 22:38:50 +000020#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/DeclSpec.h"
Douglas Gregord4dca082010-02-24 18:44:31 +000025#include "clang/Parse/Template.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Douglas Gregor124b8782010-02-16 19:09:40 +000029Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc,
30 IdentifierInfo &II,
31 SourceLocation NameLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000032 Scope *S, CXXScopeSpec &SS,
Douglas Gregor124b8782010-02-16 19:09:40 +000033 TypeTy *ObjectTypePtr,
34 bool EnteringContext) {
35 // Determine where to perform name lookup.
36
37 // FIXME: This area of the standard is very messy, and the current
38 // wording is rather unclear about which scopes we search for the
39 // destructor name; see core issues 399 and 555. Issue 399 in
40 // particular shows where the current description of destructor name
41 // lookup is completely out of line with existing practice, e.g.,
42 // this appears to be ill-formed:
43 //
44 // namespace N {
45 // template <typename T> struct S {
46 // ~S();
47 // };
48 // }
49 //
50 // void f(N::S<int>* s) {
51 // s->N::S<int>::~S();
52 // }
53 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000054 // See also PR6358 and PR6359.
Douglas Gregor124b8782010-02-16 19:09:40 +000055 QualType SearchType;
56 DeclContext *LookupCtx = 0;
57 bool isDependent = false;
58 bool LookInScope = false;
59
60 // If we have an object type, it's because we are in a
61 // pseudo-destructor-expression or a member access expression, and
62 // we know what type we're looking for.
63 if (ObjectTypePtr)
64 SearchType = GetTypeFromParser(ObjectTypePtr);
65
66 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000067 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
68
69 bool AlreadySearched = false;
70 bool LookAtPrefix = true;
71 if (!getLangOptions().CPlusPlus0x) {
72 // C++ [basic.lookup.qual]p6:
73 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
74 // the type-names are looked up as types in the scope designated by the
75 // nested-name-specifier. In a qualified-id of the form:
76 //
77 // ::[opt] nested-name-specifier ̃ class-name
78 //
79 // where the nested-name-specifier designates a namespace scope, and in
80 // a qualified-id of the form:
81 //
82 // ::opt nested-name-specifier class-name :: ̃ class-name
83 //
84 // the class-names are looked up as types in the scope designated by
85 // the nested-name-specifier.
86 //
87 // Here, we check the first case (completely) and determine whether the
88 // code below is permitted to look at the prefix of the
89 // nested-name-specifier (as we do in C++0x).
90 DeclContext *DC = computeDeclContext(SS, EnteringContext);
91 if (DC && DC->isFileContext()) {
92 AlreadySearched = true;
93 LookupCtx = DC;
94 isDependent = false;
95 } else if (DC && isa<CXXRecordDecl>(DC))
96 LookAtPrefix = false;
97 }
98
99 // C++0x [basic.lookup.qual]p6:
Douglas Gregor124b8782010-02-16 19:09:40 +0000100 // If a pseudo-destructor-name (5.2.4) contains a
101 // nested-name-specifier, the type-names are looked up as types
102 // in the scope designated by the nested-name-specifier. Similarly, in
Chandler Carruth5e895a82010-02-21 10:19:54 +0000103 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +0000104 //
105 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name
106 //
107 // the second class-name is looked up in the same scope as the first.
108 //
Douglas Gregor93649fd2010-02-23 00:15:22 +0000109 // To implement this, we look at the prefix of the
110 // nested-name-specifier we were given, and determine the lookup
111 // context from that.
112 //
113 // We also fold in the second case from the C++03 rules quoted further
114 // above.
115 NestedNameSpecifier *Prefix = 0;
116 if (AlreadySearched) {
117 // Nothing left to do.
118 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
119 CXXScopeSpec PrefixSS;
120 PrefixSS.setScopeRep(Prefix);
121 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
122 isDependent = isDependentScopeSpecifier(PrefixSS);
123 } else if (getLangOptions().CPlusPlus0x &&
124 (LookupCtx = computeDeclContext(SS, EnteringContext))) {
125 if (!LookupCtx->isTranslationUnit())
126 LookupCtx = LookupCtx->getParent();
127 isDependent = LookupCtx && LookupCtx->isDependentContext();
128 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000129 LookupCtx = computeDeclContext(SearchType);
130 isDependent = SearchType->isDependentType();
131 } else {
132 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000133 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000134 }
Douglas Gregor93649fd2010-02-23 00:15:22 +0000135
Douglas Gregoredc90502010-02-25 04:46:04 +0000136 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000137 } else if (ObjectTypePtr) {
138 // C++ [basic.lookup.classref]p3:
139 // If the unqualified-id is ~type-name, the type-name is looked up
140 // in the context of the entire postfix-expression. If the type T
141 // of the object expression is of a class type C, the type-name is
142 // also looked up in the scope of class C. At least one of the
143 // lookups shall find a name that refers to (possibly
144 // cv-qualified) T.
145 LookupCtx = computeDeclContext(SearchType);
146 isDependent = SearchType->isDependentType();
147 assert((isDependent || !SearchType->isIncompleteType()) &&
148 "Caller should have completed object type");
149
150 LookInScope = true;
151 } else {
152 // Perform lookup into the current scope (only).
153 LookInScope = true;
154 }
155
156 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
157 for (unsigned Step = 0; Step != 2; ++Step) {
158 // Look for the name first in the computed lookup context (if we
159 // have one) and, if that fails to find a match, in the sope (if
160 // we're allowed to look there).
161 Found.clear();
162 if (Step == 0 && LookupCtx)
163 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000164 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000165 LookupName(Found, S);
166 else
167 continue;
168
169 // FIXME: Should we be suppressing ambiguities here?
170 if (Found.isAmbiguous())
171 return 0;
172
173 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
174 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000175
176 if (SearchType.isNull() || SearchType->isDependentType() ||
177 Context.hasSameUnqualifiedType(T, SearchType)) {
178 // We found our type!
179
180 return T.getAsOpaquePtr();
181 }
182 }
183
184 // If the name that we found is a class template name, and it is
185 // the same name as the template name in the last part of the
186 // nested-name-specifier (if present) or the object type, then
187 // this is the destructor for that class.
188 // FIXME: This is a workaround until we get real drafting for core
189 // issue 399, for which there isn't even an obvious direction.
190 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
191 QualType MemberOfType;
192 if (SS.isSet()) {
193 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
194 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000195 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
196 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000197 }
198 }
199 if (MemberOfType.isNull())
200 MemberOfType = SearchType;
201
202 if (MemberOfType.isNull())
203 continue;
204
205 // We're referring into a class template specialization. If the
206 // class template we found is the same as the template being
207 // specialized, we found what we are looking for.
208 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
209 if (ClassTemplateSpecializationDecl *Spec
210 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
211 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
212 Template->getCanonicalDecl())
213 return MemberOfType.getAsOpaquePtr();
214 }
215
216 continue;
217 }
218
219 // We're referring to an unresolved class template
220 // specialization. Determine whether we class template we found
221 // is the same as the template being specialized or, if we don't
222 // know which template is being specialized, that it at least
223 // has the same name.
224 if (const TemplateSpecializationType *SpecType
225 = MemberOfType->getAs<TemplateSpecializationType>()) {
226 TemplateName SpecName = SpecType->getTemplateName();
227
228 // The class template we found is the same template being
229 // specialized.
230 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
231 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
232 return MemberOfType.getAsOpaquePtr();
233
234 continue;
235 }
236
237 // The class template we found has the same name as the
238 // (dependent) template name being specialized.
239 if (DependentTemplateName *DepTemplate
240 = SpecName.getAsDependentTemplateName()) {
241 if (DepTemplate->isIdentifier() &&
242 DepTemplate->getIdentifier() == Template->getIdentifier())
243 return MemberOfType.getAsOpaquePtr();
244
245 continue;
246 }
247 }
248 }
249 }
250
251 if (isDependent) {
252 // We didn't find our type, but that's okay: it's dependent
253 // anyway.
254 NestedNameSpecifier *NNS = 0;
255 SourceRange Range;
256 if (SS.isSet()) {
257 NNS = (NestedNameSpecifier *)SS.getScopeRep();
258 Range = SourceRange(SS.getRange().getBegin(), NameLoc);
259 } else {
260 NNS = NestedNameSpecifier::Create(Context, &II);
261 Range = SourceRange(NameLoc);
262 }
263
Douglas Gregor107de902010-04-24 15:35:55 +0000264 return CheckTypenameType(ETK_None, NNS, II, Range).getAsOpaquePtr();
Douglas Gregor124b8782010-02-16 19:09:40 +0000265 }
266
267 if (ObjectTypePtr)
268 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type)
269 << &II;
270 else
271 Diag(NameLoc, diag::err_destructor_class_name);
272
273 return 0;
274}
275
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000276/// \brief Build a C++ typeid expression with a type operand.
277Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
278 SourceLocation TypeidLoc,
279 TypeSourceInfo *Operand,
280 SourceLocation RParenLoc) {
281 // C++ [expr.typeid]p4:
282 // The top-level cv-qualifiers of the lvalue expression or the type-id
283 // that is the operand of typeid are always ignored.
284 // If the type of the type-id is a class type or a reference to a class
285 // type, the class shall be completely-defined.
286 QualType T = Operand->getType().getNonReferenceType();
287 if (T->getAs<RecordType>() &&
288 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
289 return ExprError();
Daniel Dunbar380c2132010-05-11 21:32:35 +0000290
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000291 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
292 Operand,
293 SourceRange(TypeidLoc, RParenLoc)));
294}
295
296/// \brief Build a C++ typeid expression with an expression operand.
297Sema::OwningExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
298 SourceLocation TypeidLoc,
299 ExprArg Operand,
300 SourceLocation RParenLoc) {
301 bool isUnevaluatedOperand = true;
302 Expr *E = static_cast<Expr *>(Operand.get());
303 if (E && !E->isTypeDependent()) {
304 QualType T = E->getType();
305 if (const RecordType *RecordT = T->getAs<RecordType>()) {
306 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
307 // C++ [expr.typeid]p3:
308 // [...] If the type of the expression is a class type, the class
309 // shall be completely-defined.
310 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
311 return ExprError();
312
313 // C++ [expr.typeid]p3:
314 // When typeid is applied to an expression other than an lvalue of a
315 // polymorphic class type [...] [the] expression is an unevaluated
316 // operand. [...]
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000317 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000318 isUnevaluatedOperand = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000319
320 // We require a vtable to query the type at run time.
321 MarkVTableUsed(TypeidLoc, RecordD);
322 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000323 }
324
325 // C++ [expr.typeid]p4:
326 // [...] If the type of the type-id is a reference to a possibly
327 // cv-qualified type, the result of the typeid expression refers to a
328 // std::type_info object representing the cv-unqualified referenced
329 // type.
330 if (T.hasQualifiers()) {
331 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
332 E->isLvalue(Context));
333 Operand.release();
334 Operand = Owned(E);
335 }
336 }
337
338 // If this is an unevaluated operand, clear out the set of
339 // declaration references we have been computing and eliminate any
340 // temporaries introduced in its computation.
341 if (isUnevaluatedOperand)
342 ExprEvalContexts.back().Context = Unevaluated;
343
344 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
345 Operand.takeAs<Expr>(),
346 SourceRange(TypeidLoc, RParenLoc)));
347}
348
349/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000350Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000351Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
352 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000353 // Find the std::type_info type.
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000354 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000355 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000356
Chris Lattner572af492008-11-20 05:51:55 +0000357 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000358 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
359 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000360 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000361 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000362 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000363
Sebastian Redlc42e1182008-11-11 11:37:55 +0000364 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000365
366 if (isType) {
367 // The operand is a type; handle it as such.
368 TypeSourceInfo *TInfo = 0;
369 QualType T = GetTypeFromParser(TyOrExpr, &TInfo);
370 if (T.isNull())
371 return ExprError();
372
373 if (!TInfo)
374 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000375
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000376 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000377 }
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000379 // The operand is an expression.
380 return BuildCXXTypeId(TypeInfoType, OpLoc, Owned((Expr*)TyOrExpr), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000381}
382
Steve Naroff1b273c42007-09-16 14:56:35 +0000383/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000384Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000385Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000386 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000387 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000388 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
389 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000390}
Chris Lattner50dd2892008-02-26 00:51:44 +0000391
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000392/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
393Action::OwningExprResult
394Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
395 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
396}
397
Chris Lattner50dd2892008-02-26 00:51:44 +0000398/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000399Action::OwningExprResult
400Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000401 Expr *Ex = E.takeAs<Expr>();
402 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
403 return ExprError();
404 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
405}
406
407/// CheckCXXThrowOperand - Validate the operand of a throw.
408bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
409 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000410 // A throw-expression initializes a temporary object, called the exception
411 // object, the type of which is determined by removing any top-level
412 // cv-qualifiers from the static type of the operand of throw and adjusting
413 // the type from "array of T" or "function returning T" to "pointer to T"
414 // or "pointer to function returning T", [...]
415 if (E->getType().hasQualifiers())
416 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
417 E->isLvalue(Context) == Expr::LV_Valid);
418
Sebastian Redl972041f2009-04-27 20:27:31 +0000419 DefaultFunctionArrayConversion(E);
420
421 // If the type of the exception would be an incomplete type or a pointer
422 // to an incomplete type other than (cv) void the program is ill-formed.
423 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000424 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000425 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000426 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000427 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000428 }
429 if (!isPointer || !Ty->isVoidType()) {
430 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000431 PDiag(isPointer ? diag::err_throw_incomplete_ptr
432 : diag::err_throw_incomplete)
433 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000434 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000435
Douglas Gregorbf422f92010-04-15 18:05:39 +0000436 if (RequireNonAbstractType(ThrowLoc, E->getType(),
437 PDiag(diag::err_throw_abstract_type)
438 << E->getSourceRange()))
439 return true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000440 }
441
John McCallac418162010-04-22 01:10:34 +0000442 // Initialize the exception result. This implicitly weeds out
443 // abstract types or types with inaccessible copy constructors.
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000444 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34.
John McCallac418162010-04-22 01:10:34 +0000445 InitializedEntity Entity =
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000446 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
447 /*NRVO=*/false);
John McCallac418162010-04-22 01:10:34 +0000448 OwningExprResult Res = PerformCopyInitialization(Entity,
449 SourceLocation(),
450 Owned(E));
451 if (Res.isInvalid())
452 return true;
453 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000454
455 // If we are throwing a polymorphic class type or pointer thereof,
456 // exception handling will make use of the vtable.
457 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
458 MarkVTableUsed(ThrowLoc, cast<CXXRecordDecl>(RecordTy->getDecl()));
459
Sebastian Redl972041f2009-04-27 20:27:31 +0000460 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000461}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000462
Sebastian Redlf53597f2009-03-15 17:47:39 +0000463Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000464 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
465 /// is a non-lvalue expression whose value is the address of the object for
466 /// which the function is called.
467
Sebastian Redlf53597f2009-03-15 17:47:39 +0000468 if (!isa<FunctionDecl>(CurContext))
469 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000470
471 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
472 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000473 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000474 MD->getThisType(Context),
475 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000476
Sebastian Redlf53597f2009-03-15 17:47:39 +0000477 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000478}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000479
480/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
481/// Can be interpreted either as function-style casting ("int(x)")
482/// or class type construction ("ClassType(x,y,z)")
483/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000484Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000485Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
486 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000487 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000488 SourceLocation *CommaLocs,
489 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000490 if (!TypeRep)
491 return ExprError();
492
John McCall9d125032010-01-15 18:39:57 +0000493 TypeSourceInfo *TInfo;
494 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
495 if (!TInfo)
496 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000497 unsigned NumExprs = exprs.size();
498 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000499 SourceLocation TyBeginLoc = TypeRange.getBegin();
500 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
501
Sebastian Redlf53597f2009-03-15 17:47:39 +0000502 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000503 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000504 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000505
506 return Owned(CXXUnresolvedConstructExpr::Create(Context,
507 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000508 LParenLoc,
509 Exprs, NumExprs,
510 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000511 }
512
Anders Carlssonbb60a502009-08-27 03:53:50 +0000513 if (Ty->isArrayType())
514 return ExprError(Diag(TyBeginLoc,
515 diag::err_value_init_for_array_type) << FullRange);
516 if (!Ty->isVoidType() &&
517 RequireCompleteType(TyBeginLoc, Ty,
518 PDiag(diag::err_invalid_incomplete_type_use)
519 << FullRange))
520 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000521
Anders Carlssonbb60a502009-08-27 03:53:50 +0000522 if (RequireNonAbstractType(TyBeginLoc, Ty,
523 diag::err_allocation_of_abstract_type))
524 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000525
526
Douglas Gregor506ae412009-01-16 18:33:17 +0000527 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000528 // If the expression list is a single expression, the type conversion
529 // expression is equivalent (in definedness, and if defined in meaning) to the
530 // corresponding cast expression.
531 //
532 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000533 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000534 CXXBaseSpecifierArray BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000535 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
536 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000537 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000538
539 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000540
541 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000542 TInfo, TyBeginLoc, Kind,
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000543 Exprs[0], BasePath,
544 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000545 }
546
Ted Kremenek6217b802009-07-29 21:53:49 +0000547 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000548 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000549
Mike Stump1eb44332009-09-09 15:08:12 +0000550 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000551 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000552 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
553 InitializationKind Kind
554 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
555 LParenLoc, RParenLoc)
556 : InitializationKind::CreateValue(TypeRange.getBegin(),
557 LParenLoc, RParenLoc);
558 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
559 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
560 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000561
Eli Friedman6997aae2010-01-31 20:58:15 +0000562 // FIXME: Improve AST representation?
563 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000564 }
565
566 // Fall through to value-initialize an object of class type that
567 // doesn't have a user-declared default constructor.
568 }
569
570 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000571 // If the expression list specifies more than a single value, the type shall
572 // be a class with a suitably declared constructor.
573 //
574 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000575 return ExprError(Diag(CommaLocs[0],
576 diag::err_builtin_func_cast_more_than_one_arg)
577 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000578
579 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000580 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000581 // The expression T(), where T is a simple-type-specifier for a non-array
582 // complete object type or the (possibly cv-qualified) void type, creates an
583 // rvalue of the specified type, which is value-initialized.
584 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000585 exprs.release();
586 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000587}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000588
589
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000590/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
591/// @code new (memory) int[size][4] @endcode
592/// or
593/// @code ::new Foo(23, "hello") @endcode
594/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000595Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000596Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000597 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000598 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000599 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000600 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000601 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000602 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000603 // If the specified type is an array, unwrap it and save the expression.
604 if (D.getNumTypeObjects() > 0 &&
605 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
606 DeclaratorChunk &Chunk = D.getTypeObject(0);
607 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000608 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
609 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000610 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000611 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
612 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000613
614 if (ParenTypeId) {
615 // Can't have dynamic array size when the type-id is in parentheses.
616 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
617 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
618 !NumElts->isIntegerConstantExpr(Context)) {
619 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
620 << NumElts->getSourceRange();
621 return ExprError();
622 }
623 }
624
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000625 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000626 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000627 }
628
Douglas Gregor043cad22009-09-11 00:18:58 +0000629 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000630 if (ArraySize) {
631 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000632 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
633 break;
634
635 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
636 if (Expr *NumElts = (Expr *)Array.NumElts) {
637 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
638 !NumElts->isIntegerConstantExpr(Context)) {
639 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
640 << NumElts->getSourceRange();
641 return ExprError();
642 }
643 }
644 }
645 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000646
John McCalla93c9342009-12-07 02:54:59 +0000647 //FIXME: Store TypeSourceInfo in CXXNew expression.
648 TypeSourceInfo *TInfo = 0;
649 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000650 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000651 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000652
Mike Stump1eb44332009-09-09 15:08:12 +0000653 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000654 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000655 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000656 PlacementRParen,
657 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000658 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000659 D.getSourceRange().getBegin(),
660 D.getSourceRange(),
661 Owned(ArraySize),
662 ConstructorLParen,
663 move(ConstructorArgs),
664 ConstructorRParen);
665}
666
Mike Stump1eb44332009-09-09 15:08:12 +0000667Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000668Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
669 SourceLocation PlacementLParen,
670 MultiExprArg PlacementArgs,
671 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000672 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000673 QualType AllocType,
674 SourceLocation TypeLoc,
675 SourceRange TypeRange,
676 ExprArg ArraySizeE,
677 SourceLocation ConstructorLParen,
678 MultiExprArg ConstructorArgs,
679 SourceLocation ConstructorRParen) {
680 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000681 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000682
Douglas Gregor3433cf72009-05-21 00:00:09 +0000683 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000684
685 // That every array dimension except the first is constant was already
686 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000687
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000688 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
689 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000690 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000691 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000692 QualType SizeType = ArraySize->getType();
693 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000694 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
695 diag::err_array_size_not_integral)
696 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000697 // Let's see if this is a constant < 0. If so, we reject it out of hand.
698 // We don't care about special rules, so we tell the machinery it's not
699 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000700 if (!ArraySize->isValueDependent()) {
701 llvm::APSInt Value;
702 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
703 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000704 llvm::APInt::getNullValue(Value.getBitWidth()),
705 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000706 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
707 diag::err_typecheck_negative_array_size)
708 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000709 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000710 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000711
Eli Friedman73c39ab2009-10-20 08:27:19 +0000712 ImpCastExprToType(ArraySize, Context.getSizeType(),
713 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000714 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000715
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000716 FunctionDecl *OperatorNew = 0;
717 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000718 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
719 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000720
Sebastian Redl28507842009-02-26 14:39:58 +0000721 if (!AllocType->isDependentType() &&
722 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
723 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000724 SourceRange(PlacementLParen, PlacementRParen),
725 UseGlobal, AllocType, ArraySize, PlaceArgs,
726 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000727 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000728 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000729 if (OperatorNew) {
730 // Add default arguments, if any.
731 const FunctionProtoType *Proto =
732 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000733 VariadicCallType CallType =
734 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000735
736 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
737 Proto, 1, PlaceArgs, NumPlaceArgs,
738 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000739 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000740
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000741 NumPlaceArgs = AllPlaceArgs.size();
742 if (NumPlaceArgs > 0)
743 PlaceArgs = &AllPlaceArgs[0];
744 }
745
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000746 bool Init = ConstructorLParen.isValid();
747 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000748 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000749 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
750 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000751 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
752
Anders Carlsson48c95012010-05-03 15:45:23 +0000753 // Array 'new' can't have any initializers.
754 if (NumConsArgs && ArraySize) {
755 SourceRange InitRange(ConsArgs[0]->getLocStart(),
756 ConsArgs[NumConsArgs - 1]->getLocEnd());
757
758 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
759 return ExprError();
760 }
761
Douglas Gregor99a2e602009-12-16 01:38:02 +0000762 if (!AllocType->isDependentType() &&
763 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
764 // C++0x [expr.new]p15:
765 // A new-expression that creates an object of type T initializes that
766 // object as follows:
767 InitializationKind Kind
768 // - If the new-initializer is omitted, the object is default-
769 // initialized (8.5); if no initialization is performed,
770 // the object has indeterminate value
771 = !Init? InitializationKind::CreateDefault(TypeLoc)
772 // - Otherwise, the new-initializer is interpreted according to the
773 // initialization rules of 8.5 for direct-initialization.
774 : InitializationKind::CreateDirect(TypeLoc,
775 ConstructorLParen,
776 ConstructorRParen);
777
Douglas Gregor99a2e602009-12-16 01:38:02 +0000778 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000779 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000780 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000781 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
782 move(ConstructorArgs));
783 if (FullInit.isInvalid())
784 return ExprError();
785
786 // FullInit is our initializer; walk through it to determine if it's a
787 // constructor call, which CXXNewExpr handles directly.
788 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
789 if (CXXBindTemporaryExpr *Binder
790 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
791 FullInitExpr = Binder->getSubExpr();
792 if (CXXConstructExpr *Construct
793 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
794 Constructor = Construct->getConstructor();
795 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
796 AEnd = Construct->arg_end();
797 A != AEnd; ++A)
798 ConvertedConstructorArgs.push_back(A->Retain());
799 } else {
800 // Take the converted initializer.
801 ConvertedConstructorArgs.push_back(FullInit.release());
802 }
803 } else {
804 // No initialization required.
805 }
806
807 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000808 NumConsArgs = ConvertedConstructorArgs.size();
809 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000810 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000811
Douglas Gregor6d908702010-02-26 05:06:18 +0000812 // Mark the new and delete operators as referenced.
813 if (OperatorNew)
814 MarkDeclarationReferenced(StartLoc, OperatorNew);
815 if (OperatorDelete)
816 MarkDeclarationReferenced(StartLoc, OperatorDelete);
817
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000818 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000819
Sebastian Redlf53597f2009-03-15 17:47:39 +0000820 PlacementArgs.release();
821 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000822 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000823 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
824 PlaceArgs, NumPlaceArgs, ParenTypeId,
825 ArraySize, Constructor, Init,
826 ConsArgs, NumConsArgs, OperatorDelete,
827 ResultType, StartLoc,
828 Init ? ConstructorRParen :
829 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000830}
831
832/// CheckAllocatedType - Checks that a type is suitable as the allocated type
833/// in a new-expression.
834/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000835bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000836 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000837 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
838 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000839 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000840 return Diag(Loc, diag::err_bad_new_type)
841 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000842 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000843 return Diag(Loc, diag::err_bad_new_type)
844 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000845 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000846 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000847 PDiag(diag::err_new_incomplete_type)
848 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000849 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000850 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000851 diag::err_allocation_of_abstract_type))
852 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000853
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000854 return false;
855}
856
Douglas Gregor6d908702010-02-26 05:06:18 +0000857/// \brief Determine whether the given function is a non-placement
858/// deallocation function.
859static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
860 if (FD->isInvalidDecl())
861 return false;
862
863 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
864 return Method->isUsualDeallocationFunction();
865
866 return ((FD->getOverloadedOperator() == OO_Delete ||
867 FD->getOverloadedOperator() == OO_Array_Delete) &&
868 FD->getNumParams() == 1);
869}
870
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000871/// FindAllocationFunctions - Finds the overloads of operator new and delete
872/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000873bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
874 bool UseGlobal, QualType AllocType,
875 bool IsArray, Expr **PlaceArgs,
876 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000877 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000878 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000879 // --- Choosing an allocation function ---
880 // C++ 5.3.4p8 - 14 & 18
881 // 1) If UseGlobal is true, only look in the global scope. Else, also look
882 // in the scope of the allocated class.
883 // 2) If an array size is given, look for operator new[], else look for
884 // operator new.
885 // 3) The first argument is always size_t. Append the arguments from the
886 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000887
888 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
889 // We don't care about the actual value of this argument.
890 // FIXME: Should the Sema create the expression and embed it in the syntax
891 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000892 IntegerLiteral Size(llvm::APInt::getNullValue(
893 Context.Target.getPointerWidth(0)),
894 Context.getSizeType(),
895 SourceLocation());
896 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000897 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
898
Douglas Gregor6d908702010-02-26 05:06:18 +0000899 // C++ [expr.new]p8:
900 // If the allocated type is a non-array type, the allocation
901 // function’s name is operator new and the deallocation function’s
902 // name is operator delete. If the allocated type is an array
903 // type, the allocation function’s name is operator new[] and the
904 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000905 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
906 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000907 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
908 IsArray ? OO_Array_Delete : OO_Delete);
909
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000910 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000911 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000912 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000913 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000914 AllocArgs.size(), Record, /*AllowMissing=*/true,
915 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000916 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000917 }
918 if (!OperatorNew) {
919 // Didn't find a member overload. Look for a global one.
920 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000921 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000922 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000923 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
924 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000925 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000926 }
927
John McCall9c82afc2010-04-20 02:18:25 +0000928 // We don't need an operator delete if we're running under
929 // -fno-exceptions.
930 if (!getLangOptions().Exceptions) {
931 OperatorDelete = 0;
932 return false;
933 }
934
Anders Carlssond9583892009-05-31 20:26:12 +0000935 // FindAllocationOverload can change the passed in arguments, so we need to
936 // copy them back.
937 if (NumPlaceArgs > 0)
938 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Douglas Gregor6d908702010-02-26 05:06:18 +0000940 // C++ [expr.new]p19:
941 //
942 // If the new-expression begins with a unary :: operator, the
943 // deallocation function’s name is looked up in the global
944 // scope. Otherwise, if the allocated type is a class type T or an
945 // array thereof, the deallocation function’s name is looked up in
946 // the scope of T. If this lookup fails to find the name, or if
947 // the allocated type is not a class type or array thereof, the
948 // deallocation function’s name is looked up in the global scope.
949 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
950 if (AllocType->isRecordType() && !UseGlobal) {
951 CXXRecordDecl *RD
952 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
953 LookupQualifiedName(FoundDelete, RD);
954 }
John McCall90c8c572010-03-18 08:19:33 +0000955 if (FoundDelete.isAmbiguous())
956 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000957
958 if (FoundDelete.empty()) {
959 DeclareGlobalNewDelete();
960 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
961 }
962
963 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000964
965 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
966
John McCall90c8c572010-03-18 08:19:33 +0000967 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +0000968 // C++ [expr.new]p20:
969 // A declaration of a placement deallocation function matches the
970 // declaration of a placement allocation function if it has the
971 // same number of parameters and, after parameter transformations
972 // (8.3.5), all parameter types except the first are
973 // identical. [...]
974 //
975 // To perform this comparison, we compute the function type that
976 // the deallocation function should have, and use that type both
977 // for template argument deduction and for comparison purposes.
978 QualType ExpectedFunctionType;
979 {
980 const FunctionProtoType *Proto
981 = OperatorNew->getType()->getAs<FunctionProtoType>();
982 llvm::SmallVector<QualType, 4> ArgTypes;
983 ArgTypes.push_back(Context.VoidPtrTy);
984 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
985 ArgTypes.push_back(Proto->getArgType(I));
986
987 ExpectedFunctionType
988 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
989 ArgTypes.size(),
990 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +0000991 0, false, false, 0, 0,
992 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +0000993 }
994
995 for (LookupResult::iterator D = FoundDelete.begin(),
996 DEnd = FoundDelete.end();
997 D != DEnd; ++D) {
998 FunctionDecl *Fn = 0;
999 if (FunctionTemplateDecl *FnTmpl
1000 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1001 // Perform template argument deduction to try to match the
1002 // expected function type.
1003 TemplateDeductionInfo Info(Context, StartLoc);
1004 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1005 continue;
1006 } else
1007 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1008
1009 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001010 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001011 }
1012 } else {
1013 // C++ [expr.new]p20:
1014 // [...] Any non-placement deallocation function matches a
1015 // non-placement allocation function. [...]
1016 for (LookupResult::iterator D = FoundDelete.begin(),
1017 DEnd = FoundDelete.end();
1018 D != DEnd; ++D) {
1019 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1020 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001021 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001022 }
1023 }
1024
1025 // C++ [expr.new]p20:
1026 // [...] If the lookup finds a single matching deallocation
1027 // function, that function will be called; otherwise, no
1028 // deallocation function will be called.
1029 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001030 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001031
1032 // C++0x [expr.new]p20:
1033 // If the lookup finds the two-parameter form of a usual
1034 // deallocation function (3.7.4.2) and that function, considered
1035 // as a placement deallocation function, would have been
1036 // selected as a match for the allocation function, the program
1037 // is ill-formed.
1038 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1039 isNonPlacementDeallocationFunction(OperatorDelete)) {
1040 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1041 << SourceRange(PlaceArgs[0]->getLocStart(),
1042 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1043 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1044 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001045 } else {
1046 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001047 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001048 }
1049 }
1050
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001051 return false;
1052}
1053
Sebastian Redl7f662392008-12-04 22:20:51 +00001054/// FindAllocationOverload - Find an fitting overload for the allocation
1055/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001056bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1057 DeclarationName Name, Expr** Args,
1058 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001059 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001060 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1061 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001062 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001063 if (AllowMissing)
1064 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001065 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001066 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001067 }
1068
John McCall90c8c572010-03-18 08:19:33 +00001069 if (R.isAmbiguous())
1070 return true;
1071
1072 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001073
John McCall5769d612010-02-08 23:07:23 +00001074 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001075 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1076 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001077 // Even member operator new/delete are implicitly treated as
1078 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001079 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001080
John McCall9aa472c2010-03-19 07:35:19 +00001081 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1082 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001083 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1084 Candidates,
1085 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001086 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001087 }
1088
John McCall9aa472c2010-03-19 07:35:19 +00001089 FunctionDecl *Fn = cast<FunctionDecl>(D);
1090 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001091 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001092 }
1093
1094 // Do the resolution.
1095 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001096 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001097 case OR_Success: {
1098 // Got one!
1099 FunctionDecl *FnDecl = Best->Function;
1100 // The first argument is size_t, and the first parameter must be size_t,
1101 // too. This is checked on declaration and can be assumed. (It can't be
1102 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001103 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001104 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1105 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001106 OwningExprResult Result
1107 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1108 FnDecl->getParamDecl(i)),
1109 SourceLocation(),
1110 Owned(Args[i]->Retain()));
1111 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001112 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001113
1114 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001115 }
1116 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001117 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001118 return false;
1119 }
1120
1121 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001122 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001123 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001124 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001125 return true;
1126
1127 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001128 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001129 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001130 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001131 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001132
1133 case OR_Deleted:
1134 Diag(StartLoc, diag::err_ovl_deleted_call)
1135 << Best->Function->isDeleted()
1136 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001137 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001138 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001139 }
1140 assert(false && "Unreachable, bad result from BestViableFunction");
1141 return true;
1142}
1143
1144
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001145/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1146/// delete. These are:
1147/// @code
1148/// void* operator new(std::size_t) throw(std::bad_alloc);
1149/// void* operator new[](std::size_t) throw(std::bad_alloc);
1150/// void operator delete(void *) throw();
1151/// void operator delete[](void *) throw();
1152/// @endcode
1153/// Note that the placement and nothrow forms of new are *not* implicitly
1154/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001155void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001156 if (GlobalNewDeleteDeclared)
1157 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001158
1159 // C++ [basic.std.dynamic]p2:
1160 // [...] The following allocation and deallocation functions (18.4) are
1161 // implicitly declared in global scope in each translation unit of a
1162 // program
1163 //
1164 // void* operator new(std::size_t) throw(std::bad_alloc);
1165 // void* operator new[](std::size_t) throw(std::bad_alloc);
1166 // void operator delete(void*) throw();
1167 // void operator delete[](void*) throw();
1168 //
1169 // These implicit declarations introduce only the function names operator
1170 // new, operator new[], operator delete, operator delete[].
1171 //
1172 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1173 // "std" or "bad_alloc" as necessary to form the exception specification.
1174 // However, we do not make these implicit declarations visible to name
1175 // lookup.
1176 if (!StdNamespace) {
1177 // The "std" namespace has not yet been defined, so build one implicitly.
1178 StdNamespace = NamespaceDecl::Create(Context,
1179 Context.getTranslationUnitDecl(),
1180 SourceLocation(),
1181 &PP.getIdentifierTable().get("std"));
1182 StdNamespace->setImplicit(true);
1183 }
1184
1185 if (!StdBadAlloc) {
1186 // The "std::bad_alloc" class has not yet been declared, so build it
1187 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001188 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001189 StdNamespace,
1190 SourceLocation(),
1191 &PP.getIdentifierTable().get("bad_alloc"),
1192 SourceLocation(), 0);
1193 StdBadAlloc->setImplicit(true);
1194 }
1195
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001196 GlobalNewDeleteDeclared = true;
1197
1198 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1199 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001200 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001201
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001202 DeclareGlobalAllocationFunction(
1203 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001204 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001205 DeclareGlobalAllocationFunction(
1206 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001207 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001208 DeclareGlobalAllocationFunction(
1209 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1210 Context.VoidTy, VoidPtr);
1211 DeclareGlobalAllocationFunction(
1212 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1213 Context.VoidTy, VoidPtr);
1214}
1215
1216/// DeclareGlobalAllocationFunction - Declares a single implicit global
1217/// allocation function if it doesn't already exist.
1218void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001219 QualType Return, QualType Argument,
1220 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001221 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1222
1223 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001224 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001225 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001226 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001227 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001228 // Only look at non-template functions, as it is the predefined,
1229 // non-templated allocation function we are trying to declare here.
1230 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1231 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001232 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001233 Func->getParamDecl(0)->getType().getUnqualifiedType());
1234 // FIXME: Do we need to check for default arguments here?
1235 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1236 return;
1237 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001238 }
1239 }
1240
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001241 QualType BadAllocType;
1242 bool HasBadAllocExceptionSpec
1243 = (Name.getCXXOverloadedOperator() == OO_New ||
1244 Name.getCXXOverloadedOperator() == OO_Array_New);
1245 if (HasBadAllocExceptionSpec) {
1246 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1247 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1248 }
1249
1250 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1251 true, false,
1252 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001253 &BadAllocType,
1254 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001255 FunctionDecl *Alloc =
1256 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001257 FnType, /*TInfo=*/0, FunctionDecl::None,
1258 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001259 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001260
1261 if (AddMallocAttr)
1262 Alloc->addAttr(::new (Context) MallocAttr());
1263
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001264 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001265 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001266 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001267 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001268 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001269
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001270 // FIXME: Also add this declaration to the IdentifierResolver, but
1271 // make sure it is at the end of the chain to coincide with the
1272 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001273 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001274}
1275
Anders Carlsson78f74552009-11-15 18:45:20 +00001276bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1277 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001278 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001279 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001280 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001281 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001282
John McCalla24dc2e2009-11-17 02:14:36 +00001283 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001284 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001285
1286 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1287 F != FEnd; ++F) {
1288 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1289 if (Delete->isUsualDeallocationFunction()) {
1290 Operator = Delete;
1291 return false;
1292 }
1293 }
1294
1295 // We did find operator delete/operator delete[] declarations, but
1296 // none of them were suitable.
1297 if (!Found.empty()) {
1298 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1299 << Name << RD;
1300
1301 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1302 F != FEnd; ++F) {
Douglas Gregorb0fd4832010-04-25 20:55:08 +00001303 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlsson78f74552009-11-15 18:45:20 +00001304 << Name;
1305 }
1306
1307 return true;
1308 }
1309
1310 // Look for a global declaration.
1311 DeclareGlobalNewDelete();
1312 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1313
1314 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1315 Expr* DeallocArgs[1];
1316 DeallocArgs[0] = &Null;
1317 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1318 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1319 Operator))
1320 return true;
1321
1322 assert(Operator && "Did not find a deallocation function!");
1323 return false;
1324}
1325
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001326/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1327/// @code ::delete ptr; @endcode
1328/// or
1329/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001330Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001331Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001332 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001333 // C++ [expr.delete]p1:
1334 // The operand shall have a pointer type, or a class type having a single
1335 // conversion function to a pointer type. The result has type void.
1336 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001337 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1338
Anders Carlssond67c4c32009-08-16 20:29:29 +00001339 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Sebastian Redlf53597f2009-03-15 17:47:39 +00001341 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001342 if (!Ex->isTypeDependent()) {
1343 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001344
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001345 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCall32daa422010-03-31 01:36:47 +00001346 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1347
Fariborz Jahanian53462782009-09-11 21:44:33 +00001348 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001349 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001350 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001351 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001352 NamedDecl *D = I.getDecl();
1353 if (isa<UsingShadowDecl>(D))
1354 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1355
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001356 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001357 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001358 continue;
1359
John McCall32daa422010-03-31 01:36:47 +00001360 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001361
1362 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1363 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1364 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001365 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001366 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001367 if (ObjectPtrConversions.size() == 1) {
1368 // We have a single conversion to a pointer-to-object type. Perform
1369 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001370 // TODO: don't redo the conversion calculation.
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001371 Operand.release();
John McCall32daa422010-03-31 01:36:47 +00001372 if (!PerformImplicitConversion(Ex,
1373 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001374 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001375 Operand = Owned(Ex);
1376 Type = Ex->getType();
1377 }
1378 }
1379 else if (ObjectPtrConversions.size() > 1) {
1380 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1381 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001382 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1383 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001384 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001385 }
Sebastian Redl28507842009-02-26 14:39:58 +00001386 }
1387
Sebastian Redlf53597f2009-03-15 17:47:39 +00001388 if (!Type->isPointerType())
1389 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1390 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001391
Ted Kremenek6217b802009-07-29 21:53:49 +00001392 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001393 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001394 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1395 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001396 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001397 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001398 PDiag(diag::warn_delete_incomplete)
1399 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001400 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001401
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001402 // C++ [expr.delete]p2:
1403 // [Note: a pointer to a const type can be the operand of a
1404 // delete-expression; it is not necessary to cast away the constness
1405 // (5.2.11) of the pointer expression before it is used as the operand
1406 // of the delete-expression. ]
1407 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1408 CastExpr::CK_NoOp);
1409
1410 // Update the operand.
1411 Operand.take();
1412 Operand = ExprArg(*this, Ex);
1413
Anders Carlssond67c4c32009-08-16 20:29:29 +00001414 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1415 ArrayForm ? OO_Array_Delete : OO_Delete);
1416
Anders Carlsson78f74552009-11-15 18:45:20 +00001417 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1418 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1419
1420 if (!UseGlobal &&
1421 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001422 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001423
Anders Carlsson78f74552009-11-15 18:45:20 +00001424 if (!RD->hasTrivialDestructor())
1425 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001426 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001427 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001428 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001429
Anders Carlssond67c4c32009-08-16 20:29:29 +00001430 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001431 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001432 DeclareGlobalNewDelete();
1433 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001434 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001435 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001436 OperatorDelete))
1437 return ExprError();
1438 }
Mike Stump1eb44332009-09-09 15:08:12 +00001439
John McCall9c82afc2010-04-20 02:18:25 +00001440 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1441
Sebastian Redl28507842009-02-26 14:39:58 +00001442 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001443 }
1444
Sebastian Redlf53597f2009-03-15 17:47:39 +00001445 Operand.release();
1446 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001447 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001448}
1449
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001450/// \brief Check the use of the given variable as a C++ condition in an if,
1451/// while, do-while, or switch statement.
Douglas Gregor586596f2010-05-06 17:25:47 +00001452Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1453 SourceLocation StmtLoc,
1454 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001455 QualType T = ConditionVar->getType();
1456
1457 // C++ [stmt.select]p2:
1458 // The declarator shall not specify a function or an array.
1459 if (T->isFunctionType())
1460 return ExprError(Diag(ConditionVar->getLocation(),
1461 diag::err_invalid_use_of_function_type)
1462 << ConditionVar->getSourceRange());
1463 else if (T->isArrayType())
1464 return ExprError(Diag(ConditionVar->getLocation(),
1465 diag::err_invalid_use_of_array_type)
1466 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001467
Douglas Gregor586596f2010-05-06 17:25:47 +00001468 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1469 ConditionVar->getLocation(),
1470 ConditionVar->getType().getNonReferenceType());
1471 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1472 Condition->Destroy(Context);
1473 return ExprError();
1474 }
1475
1476 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001477}
1478
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001479/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1480bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1481 // C++ 6.4p4:
1482 // The value of a condition that is an initialized declaration in a statement
1483 // other than a switch statement is the value of the declared variable
1484 // implicitly converted to type bool. If that conversion is ill-formed, the
1485 // program is ill-formed.
1486 // The value of a condition that is an expression is the value of the
1487 // expression, implicitly converted to bool.
1488 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001489 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001490}
Douglas Gregor77a52232008-09-12 00:47:35 +00001491
1492/// Helper function to determine whether this is the (deprecated) C++
1493/// conversion from a string literal to a pointer to non-const char or
1494/// non-const wchar_t (for narrow and wide string literals,
1495/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001496bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001497Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1498 // Look inside the implicit cast, if it exists.
1499 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1500 From = Cast->getSubExpr();
1501
1502 // A string literal (2.13.4) that is not a wide string literal can
1503 // be converted to an rvalue of type "pointer to char"; a wide
1504 // string literal can be converted to an rvalue of type "pointer
1505 // to wchar_t" (C++ 4.2p2).
1506 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001507 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001508 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001509 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001510 // This conversion is considered only when there is an
1511 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001512 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001513 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1514 (!StrLit->isWide() &&
1515 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1516 ToPointeeType->getKind() == BuiltinType::Char_S))))
1517 return true;
1518 }
1519
1520 return false;
1521}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001522
Douglas Gregorba70ab62010-04-16 22:17:36 +00001523static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1524 SourceLocation CastLoc,
1525 QualType Ty,
1526 CastExpr::CastKind Kind,
1527 CXXMethodDecl *Method,
1528 Sema::ExprArg Arg) {
1529 Expr *From = Arg.takeAs<Expr>();
1530
1531 switch (Kind) {
1532 default: assert(0 && "Unhandled cast kind!");
1533 case CastExpr::CK_ConstructorConversion: {
1534 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1535
1536 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1537 Sema::MultiExprArg(S, (void **)&From, 1),
1538 CastLoc, ConstructorArgs))
1539 return S.ExprError();
1540
1541 Sema::OwningExprResult Result =
1542 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1543 move_arg(ConstructorArgs));
1544 if (Result.isInvalid())
1545 return S.ExprError();
1546
1547 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1548 }
1549
1550 case CastExpr::CK_UserDefinedConversion: {
1551 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1552
1553 // Create an implicit call expr that calls it.
1554 // FIXME: pass the FoundDecl for the user-defined conversion here
1555 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1556 return S.MaybeBindToTemporary(CE);
1557 }
1558 }
1559}
1560
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001561/// PerformImplicitConversion - Perform an implicit conversion of the
1562/// expression From to the type ToType using the pre-computed implicit
1563/// conversion sequence ICS. Returns true if there was an error, false
1564/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001565/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001566/// used in the error message.
1567bool
1568Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1569 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001570 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001571 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001572 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001573 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001574 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001575 return true;
1576 break;
1577
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001578 case ImplicitConversionSequence::UserDefinedConversion: {
1579
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001580 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1581 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001582 QualType BeforeToType;
1583 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001584 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001585
1586 // If the user-defined conversion is specified by a conversion function,
1587 // the initial standard conversion sequence converts the source type to
1588 // the implicit object parameter of the conversion function.
1589 BeforeToType = Context.getTagDeclType(Conv->getParent());
1590 } else if (const CXXConstructorDecl *Ctor =
1591 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001592 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001593 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001594 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001595 // If the user-defined conversion is specified by a constructor, the
1596 // initial standard conversion sequence converts the source type to the
1597 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001598 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1599 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001600 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001601 else
1602 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001603 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001604 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001605 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001606 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001607 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001608 return true;
1609 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001610
Anders Carlsson0aebc812009-09-09 21:33:21 +00001611 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001612 = BuildCXXCastArgument(*this,
1613 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001614 ToType.getNonReferenceType(),
1615 CastKind, cast<CXXMethodDecl>(FD),
1616 Owned(From));
1617
1618 if (CastArg.isInvalid())
1619 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001620
1621 From = CastArg.takeAs<Expr>();
1622
Eli Friedmand8889622009-11-27 04:41:50 +00001623 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001624 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001625 }
John McCall1d318332010-01-12 00:44:57 +00001626
1627 case ImplicitConversionSequence::AmbiguousConversion:
1628 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1629 PDiag(diag::err_typecheck_ambiguous_condition)
1630 << From->getSourceRange());
1631 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001632
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001633 case ImplicitConversionSequence::EllipsisConversion:
1634 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001635 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001636
1637 case ImplicitConversionSequence::BadConversion:
1638 return true;
1639 }
1640
1641 // Everything went well.
1642 return false;
1643}
1644
1645/// PerformImplicitConversion - Perform an implicit conversion of the
1646/// expression From to the type ToType by following the standard
1647/// conversion sequence SCS. Returns true if there was an error, false
1648/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001649/// expression. Flavor is the context in which we're performing this
1650/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001651bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001652Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001653 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001654 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001655 // Overall FIXME: we are recomputing too many types here and doing far too
1656 // much extra work. What this means is that we need to keep track of more
1657 // information that is computed when we try the implicit conversion initially,
1658 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001659 QualType FromType = From->getType();
1660
Douglas Gregor225c41e2008-11-03 19:09:14 +00001661 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001662 // FIXME: When can ToType be a reference type?
1663 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001664 if (SCS.Second == ICK_Derived_To_Base) {
1665 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1666 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1667 MultiExprArg(*this, (void **)&From, 1),
1668 /*FIXME:ConstructLoc*/SourceLocation(),
1669 ConstructorArgs))
1670 return true;
1671 OwningExprResult FromResult =
1672 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1673 ToType, SCS.CopyConstructor,
1674 move_arg(ConstructorArgs));
1675 if (FromResult.isInvalid())
1676 return true;
1677 From = FromResult.takeAs<Expr>();
1678 return false;
1679 }
Mike Stump1eb44332009-09-09 15:08:12 +00001680 OwningExprResult FromResult =
1681 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1682 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001683 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001685 if (FromResult.isInvalid())
1686 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001688 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001689 return false;
1690 }
1691
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001692 // Resolve overloaded function references.
1693 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1694 DeclAccessPair Found;
1695 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1696 true, Found);
1697 if (!Fn)
1698 return true;
1699
1700 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1701 return true;
1702
1703 From = FixOverloadedFunctionReference(From, Found, Fn);
1704 FromType = From->getType();
1705 }
1706
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001707 // Perform the first implicit conversion.
1708 switch (SCS.First) {
1709 case ICK_Identity:
1710 case ICK_Lvalue_To_Rvalue:
1711 // Nothing to do.
1712 break;
1713
1714 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001715 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001716 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001717 break;
1718
1719 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001720 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001721 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001722 break;
1723
1724 default:
1725 assert(false && "Improper first standard conversion");
1726 break;
1727 }
1728
1729 // Perform the second implicit conversion
1730 switch (SCS.Second) {
1731 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001732 // If both sides are functions (or pointers/references to them), there could
1733 // be incompatible exception declarations.
1734 if (CheckExceptionSpecCompatibility(From, ToType))
1735 return true;
1736 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001737 break;
1738
Douglas Gregor43c79c22009-12-09 00:47:37 +00001739 case ICK_NoReturn_Adjustment:
1740 // If both sides are functions (or pointers/references to them), there could
1741 // be incompatible exception declarations.
1742 if (CheckExceptionSpecCompatibility(From, ToType))
1743 return true;
1744
1745 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1746 CastExpr::CK_NoOp);
1747 break;
1748
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001749 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001750 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001751 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1752 break;
1753
1754 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001755 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001756 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1757 break;
1758
1759 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001760 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001761 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1762 break;
1763
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001764 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001765 if (ToType->isFloatingType())
1766 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1767 else
1768 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1769 break;
1770
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001771 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001772 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1773 break;
1774
Douglas Gregorf9201e02009-02-11 23:02:49 +00001775 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001776 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001777 break;
1778
Anders Carlsson61faec12009-09-12 04:46:44 +00001779 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001780 if (SCS.IncompatibleObjC) {
1781 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001782 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001783 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001784 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001785 << From->getSourceRange();
1786 }
1787
Anders Carlsson61faec12009-09-12 04:46:44 +00001788
1789 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001790 CXXBaseSpecifierArray BasePath;
1791 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001792 return true;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001793 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001794 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001795 }
1796
1797 case ICK_Pointer_Member: {
1798 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001799 CXXBaseSpecifierArray BasePath;
1800 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1801 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001802 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001803 if (CheckExceptionSpecCompatibility(From, ToType))
1804 return true;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001805 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001806 break;
1807 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001808 case ICK_Boolean_Conversion: {
1809 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1810 if (FromType->isMemberPointerType())
1811 Kind = CastExpr::CK_MemberPointerToBoolean;
1812
1813 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001814 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001815 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001816
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001817 case ICK_Derived_To_Base: {
1818 CXXBaseSpecifierArray BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001819 if (CheckDerivedToBaseConversion(From->getType(),
1820 ToType.getNonReferenceType(),
1821 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001822 From->getSourceRange(),
1823 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001824 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001825 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001826
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001827 ImpCastExprToType(From, ToType.getNonReferenceType(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001828 CastExpr::CK_DerivedToBase,
1829 /*isLvalue=*/(From->getType()->isRecordType() &&
1830 From->isLvalue(Context) == Expr::LV_Valid),
1831 BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001832 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001833 }
1834
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001835 default:
1836 assert(false && "Improper second standard conversion");
1837 break;
1838 }
1839
1840 switch (SCS.Third) {
1841 case ICK_Identity:
1842 // Nothing to do.
1843 break;
1844
1845 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001846 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1847 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001848 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00001849 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001850
1851 if (SCS.DeprecatedStringLiteralToCharPtr)
1852 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1853 << ToType.getNonReferenceType();
1854
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001855 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001856
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001857 default:
1858 assert(false && "Improper second standard conversion");
1859 break;
1860 }
1861
1862 return false;
1863}
1864
Sebastian Redl64b45f72009-01-05 20:52:13 +00001865Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1866 SourceLocation KWLoc,
1867 SourceLocation LParen,
1868 TypeTy *Ty,
1869 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001870 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001872 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1873 // all traits except __is_class, __is_enum and __is_union require a the type
1874 // to be complete.
1875 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001876 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001877 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001878 return ExprError();
1879 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001880
1881 // There is no point in eagerly computing the value. The traits are designed
1882 // to be used from type trait templates, so Ty will be a template parameter
1883 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001884 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1885 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001886}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001887
1888QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001889 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001890 const char *OpSpelling = isIndirect ? "->*" : ".*";
1891 // C++ 5.5p2
1892 // The binary operator .* [p3: ->*] binds its second operand, which shall
1893 // be of type "pointer to member of T" (where T is a completely-defined
1894 // class type) [...]
1895 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001896 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001897 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001898 Diag(Loc, diag::err_bad_memptr_rhs)
1899 << OpSpelling << RType << rex->getSourceRange();
1900 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001901 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001902
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001903 QualType Class(MemPtr->getClass(), 0);
1904
Sebastian Redl59fc2692010-04-10 10:14:54 +00001905 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1906 return QualType();
1907
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001908 // C++ 5.5p2
1909 // [...] to its first operand, which shall be of class T or of a class of
1910 // which T is an unambiguous and accessible base class. [p3: a pointer to
1911 // such a class]
1912 QualType LType = lex->getType();
1913 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001914 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001915 LType = Ptr->getPointeeType().getNonReferenceType();
1916 else {
1917 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001918 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001919 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001920 return QualType();
1921 }
1922 }
1923
Douglas Gregora4923eb2009-11-16 21:35:15 +00001924 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00001925 // If we want to check the hierarchy, we need a complete type.
1926 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1927 << OpSpelling << (int)isIndirect)) {
1928 return QualType();
1929 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001930 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001931 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001932 // FIXME: Would it be useful to print full ambiguity paths, or is that
1933 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001934 if (!IsDerivedFrom(LType, Class, Paths) ||
1935 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1936 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001937 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001938 return QualType();
1939 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001940 // Cast LHS to type of use.
1941 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1942 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001943
1944 CXXBaseSpecifierArray BasePath;
1945 BuildBasePathArray(Paths, BasePath);
1946 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1947 BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001948 }
1949
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001950 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001951 // Diagnose use of pointer-to-member type which when used as
1952 // the functional cast in a pointer-to-member expression.
1953 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1954 return QualType();
1955 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001956 // C++ 5.5p2
1957 // The result is an object or a function of the type specified by the
1958 // second operand.
1959 // The cv qualifiers are the union of those in the pointer and the left side,
1960 // in accordance with 5.5p5 and 5.2.5.
1961 // FIXME: This returns a dereferenced member function pointer as a normal
1962 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001963 // calling them. There's also a GCC extension to get a function pointer to the
1964 // thing, which is another complication, because this type - unlike the type
1965 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001966 // argument.
1967 // We probably need a "MemberFunctionClosureType" or something like that.
1968 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001969 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001970 return Result;
1971}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001972
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001973/// \brief Try to convert a type to another according to C++0x 5.16p3.
1974///
1975/// This is part of the parameter validation for the ? operator. If either
1976/// value operand is a class type, the two operands are attempted to be
1977/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001978/// It returns true if the program is ill-formed and has already been diagnosed
1979/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001980static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1981 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00001982 bool &HaveConversion,
1983 QualType &ToType) {
1984 HaveConversion = false;
1985 ToType = To->getType();
1986
1987 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1988 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001989 // C++0x 5.16p3
1990 // The process for determining whether an operand expression E1 of type T1
1991 // can be converted to match an operand expression E2 of type T2 is defined
1992 // as follows:
1993 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00001994 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1995 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001996 // E1 can be converted to match E2 if E1 can be implicitly converted to
1997 // type "lvalue reference to T2", subject to the constraint that in the
1998 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001999 QualType T = Self.Context.getLValueReferenceType(ToType);
2000 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2001
2002 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2003 if (InitSeq.isDirectReferenceBinding()) {
2004 ToType = T;
2005 HaveConversion = true;
2006 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002007 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002008
2009 if (InitSeq.isAmbiguous())
2010 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002011 }
John McCallb1bdc622010-02-25 01:37:24 +00002012
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002013 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2014 // -- if E1 and E2 have class type, and the underlying class types are
2015 // the same or one is a base class of the other:
2016 QualType FTy = From->getType();
2017 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002018 const RecordType *FRec = FTy->getAs<RecordType>();
2019 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002020 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2021 Self.IsDerivedFrom(FTy, TTy);
2022 if (FRec && TRec &&
2023 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002024 // E1 can be converted to match E2 if the class of T2 is the
2025 // same type as, or a base class of, the class of T1, and
2026 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002027 if (FRec == TRec || FDerivedFromT) {
2028 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002029 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2030 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2031 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2032 HaveConversion = true;
2033 return false;
2034 }
2035
2036 if (InitSeq.isAmbiguous())
2037 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2038 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002039 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002040
2041 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002042 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002043
2044 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2045 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002046 // if E2 were converted to an rvalue (or the type it has, if E2 is
2047 // an rvalue).
2048 //
2049 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2050 // to the array-to-pointer or function-to-pointer conversions.
2051 if (!TTy->getAs<TagType>())
2052 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002053
2054 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2055 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2056 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2057 ToType = TTy;
2058 if (InitSeq.isAmbiguous())
2059 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2060
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002061 return false;
2062}
2063
2064/// \brief Try to find a common type for two according to C++0x 5.16p5.
2065///
2066/// This is part of the parameter validation for the ? operator. If either
2067/// value operand is a class type, overload resolution is used to find a
2068/// conversion to a common type.
2069static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2070 SourceLocation Loc) {
2071 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002072 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002073 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002074
2075 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002076 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002077 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002078 // We found a match. Perform the conversions on the arguments and move on.
2079 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002080 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002081 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002082 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002083 break;
2084 return false;
2085
Douglas Gregor20093b42009-12-09 23:02:17 +00002086 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002087 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2088 << LHS->getType() << RHS->getType()
2089 << LHS->getSourceRange() << RHS->getSourceRange();
2090 return true;
2091
Douglas Gregor20093b42009-12-09 23:02:17 +00002092 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002093 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2094 << LHS->getType() << RHS->getType()
2095 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002096 // FIXME: Print the possible common types by printing the return types of
2097 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002098 break;
2099
Douglas Gregor20093b42009-12-09 23:02:17 +00002100 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002101 assert(false && "Conditional operator has only built-in overloads");
2102 break;
2103 }
2104 return true;
2105}
2106
Sebastian Redl76458502009-04-17 16:30:52 +00002107/// \brief Perform an "extended" implicit conversion as returned by
2108/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002109static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2110 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2111 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2112 SourceLocation());
2113 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2114 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2115 Sema::MultiExprArg(Self, (void **)&E, 1));
2116 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002117 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002118
2119 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002120 return false;
2121}
2122
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002123/// \brief Check the operands of ?: under C++ semantics.
2124///
2125/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2126/// extension. In this case, LHS == Cond. (But they're not aliases.)
2127QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2128 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002129 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2130 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002131
2132 // C++0x 5.16p1
2133 // The first expression is contextually converted to bool.
2134 if (!Cond->isTypeDependent()) {
2135 if (CheckCXXBooleanCondition(Cond))
2136 return QualType();
2137 }
2138
2139 // Either of the arguments dependent?
2140 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2141 return Context.DependentTy;
2142
2143 // C++0x 5.16p2
2144 // If either the second or the third operand has type (cv) void, ...
2145 QualType LTy = LHS->getType();
2146 QualType RTy = RHS->getType();
2147 bool LVoid = LTy->isVoidType();
2148 bool RVoid = RTy->isVoidType();
2149 if (LVoid || RVoid) {
2150 // ... then the [l2r] conversions are performed on the second and third
2151 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002152 DefaultFunctionArrayLvalueConversion(LHS);
2153 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002154 LTy = LHS->getType();
2155 RTy = RHS->getType();
2156
2157 // ... and one of the following shall hold:
2158 // -- The second or the third operand (but not both) is a throw-
2159 // expression; the result is of the type of the other and is an rvalue.
2160 bool LThrow = isa<CXXThrowExpr>(LHS);
2161 bool RThrow = isa<CXXThrowExpr>(RHS);
2162 if (LThrow && !RThrow)
2163 return RTy;
2164 if (RThrow && !LThrow)
2165 return LTy;
2166
2167 // -- Both the second and third operands have type void; the result is of
2168 // type void and is an rvalue.
2169 if (LVoid && RVoid)
2170 return Context.VoidTy;
2171
2172 // Neither holds, error.
2173 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2174 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2175 << LHS->getSourceRange() << RHS->getSourceRange();
2176 return QualType();
2177 }
2178
2179 // Neither is void.
2180
2181 // C++0x 5.16p3
2182 // Otherwise, if the second and third operand have different types, and
2183 // either has (cv) class type, and attempt is made to convert each of those
2184 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002185 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002186 (LTy->isRecordType() || RTy->isRecordType())) {
2187 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2188 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002189 QualType L2RType, R2LType;
2190 bool HaveL2R, HaveR2L;
2191 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002192 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002193 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002194 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002195
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002196 // If both can be converted, [...] the program is ill-formed.
2197 if (HaveL2R && HaveR2L) {
2198 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2199 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2200 return QualType();
2201 }
2202
2203 // If exactly one conversion is possible, that conversion is applied to
2204 // the chosen operand and the converted operands are used in place of the
2205 // original operands for the remainder of this section.
2206 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002207 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002208 return QualType();
2209 LTy = LHS->getType();
2210 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002211 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002212 return QualType();
2213 RTy = RHS->getType();
2214 }
2215 }
2216
2217 // C++0x 5.16p4
2218 // If the second and third operands are lvalues and have the same type,
2219 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002220 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002221 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2222 RHS->isLvalue(Context) == Expr::LV_Valid)
2223 return LTy;
2224
2225 // C++0x 5.16p5
2226 // Otherwise, the result is an rvalue. If the second and third operands
2227 // do not have the same type, and either has (cv) class type, ...
2228 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2229 // ... overload resolution is used to determine the conversions (if any)
2230 // to be applied to the operands. If the overload resolution fails, the
2231 // program is ill-formed.
2232 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2233 return QualType();
2234 }
2235
2236 // C++0x 5.16p6
2237 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2238 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002239 DefaultFunctionArrayLvalueConversion(LHS);
2240 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002241 LTy = LHS->getType();
2242 RTy = RHS->getType();
2243
2244 // After those conversions, one of the following shall hold:
2245 // -- The second and third operands have the same type; the result
2246 // is of that type.
2247 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2248 return LTy;
2249
2250 // -- The second and third operands have arithmetic or enumeration type;
2251 // the usual arithmetic conversions are performed to bring them to a
2252 // common type, and the result is of that type.
2253 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2254 UsualArithmeticConversions(LHS, RHS);
2255 return LHS->getType();
2256 }
2257
2258 // -- The second and third operands have pointer type, or one has pointer
2259 // type and the other is a null pointer constant; pointer conversions
2260 // and qualification conversions are performed to bring them to their
2261 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002262 // -- The second and third operands have pointer to member type, or one has
2263 // pointer to member type and the other is a null pointer constant;
2264 // pointer to member conversions and qualification conversions are
2265 // performed to bring them to a common type, whose cv-qualification
2266 // shall match the cv-qualification of either the second or the third
2267 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002268 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002269 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002270 isSFINAEContext()? 0 : &NonStandardCompositeType);
2271 if (!Composite.isNull()) {
2272 if (NonStandardCompositeType)
2273 Diag(QuestionLoc,
2274 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2275 << LTy << RTy << Composite
2276 << LHS->getSourceRange() << RHS->getSourceRange();
2277
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002278 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002279 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002280
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002281 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002282 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2283 if (!Composite.isNull())
2284 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002285
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002286 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2287 << LHS->getType() << RHS->getType()
2288 << LHS->getSourceRange() << RHS->getSourceRange();
2289 return QualType();
2290}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002291
2292/// \brief Find a merged pointer type and convert the two expressions to it.
2293///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002294/// This finds the composite pointer type (or member pointer type) for @p E1
2295/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2296/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002297/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002298///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002299/// \param Loc The location of the operator requiring these two expressions to
2300/// be converted to the composite pointer type.
2301///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002302/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2303/// a non-standard (but still sane) composite type to which both expressions
2304/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2305/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002306QualType Sema::FindCompositePointerType(SourceLocation Loc,
2307 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002308 bool *NonStandardCompositeType) {
2309 if (NonStandardCompositeType)
2310 *NonStandardCompositeType = false;
2311
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002312 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2313 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002315 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2316 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002317 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002318
2319 // C++0x 5.9p2
2320 // Pointer conversions and qualification conversions are performed on
2321 // pointer operands to bring them to their composite pointer type. If
2322 // one operand is a null pointer constant, the composite pointer type is
2323 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002324 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002325 if (T2->isMemberPointerType())
2326 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2327 else
2328 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002329 return T2;
2330 }
Douglas Gregorce940492009-09-25 04:25:58 +00002331 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002332 if (T1->isMemberPointerType())
2333 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2334 else
2335 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002336 return T1;
2337 }
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Douglas Gregor20b3e992009-08-24 17:42:35 +00002339 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002340 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2341 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002342 return QualType();
2343
2344 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2345 // the other has type "pointer to cv2 T" and the composite pointer type is
2346 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2347 // Otherwise, the composite pointer type is a pointer type similar to the
2348 // type of one of the operands, with a cv-qualification signature that is
2349 // the union of the cv-qualification signatures of the operand types.
2350 // In practice, the first part here is redundant; it's subsumed by the second.
2351 // What we do here is, we build the two possible composite types, and try the
2352 // conversions in both directions. If only one works, or if the two composite
2353 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002354 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002355 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2356 QualifierVector QualifierUnion;
2357 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2358 ContainingClassVector;
2359 ContainingClassVector MemberOfClass;
2360 QualType Composite1 = Context.getCanonicalType(T1),
2361 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002362 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002363 do {
2364 const PointerType *Ptr1, *Ptr2;
2365 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2366 (Ptr2 = Composite2->getAs<PointerType>())) {
2367 Composite1 = Ptr1->getPointeeType();
2368 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002369
2370 // If we're allowed to create a non-standard composite type, keep track
2371 // of where we need to fill in additional 'const' qualifiers.
2372 if (NonStandardCompositeType &&
2373 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2374 NeedConstBefore = QualifierUnion.size();
2375
Douglas Gregor20b3e992009-08-24 17:42:35 +00002376 QualifierUnion.push_back(
2377 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2378 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2379 continue;
2380 }
Mike Stump1eb44332009-09-09 15:08:12 +00002381
Douglas Gregor20b3e992009-08-24 17:42:35 +00002382 const MemberPointerType *MemPtr1, *MemPtr2;
2383 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2384 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2385 Composite1 = MemPtr1->getPointeeType();
2386 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002387
2388 // If we're allowed to create a non-standard composite type, keep track
2389 // of where we need to fill in additional 'const' qualifiers.
2390 if (NonStandardCompositeType &&
2391 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2392 NeedConstBefore = QualifierUnion.size();
2393
Douglas Gregor20b3e992009-08-24 17:42:35 +00002394 QualifierUnion.push_back(
2395 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2396 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2397 MemPtr2->getClass()));
2398 continue;
2399 }
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Douglas Gregor20b3e992009-08-24 17:42:35 +00002401 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Douglas Gregor20b3e992009-08-24 17:42:35 +00002403 // Cannot unwrap any more types.
2404 break;
2405 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002406
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002407 if (NeedConstBefore && NonStandardCompositeType) {
2408 // Extension: Add 'const' to qualifiers that come before the first qualifier
2409 // mismatch, so that our (non-standard!) composite type meets the
2410 // requirements of C++ [conv.qual]p4 bullet 3.
2411 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2412 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2413 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2414 *NonStandardCompositeType = true;
2415 }
2416 }
2417 }
2418
Douglas Gregor20b3e992009-08-24 17:42:35 +00002419 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002420 ContainingClassVector::reverse_iterator MOC
2421 = MemberOfClass.rbegin();
2422 for (QualifierVector::reverse_iterator
2423 I = QualifierUnion.rbegin(),
2424 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002425 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002426 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002427 if (MOC->first && MOC->second) {
2428 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002429 Composite1 = Context.getMemberPointerType(
2430 Context.getQualifiedType(Composite1, Quals),
2431 MOC->first);
2432 Composite2 = Context.getMemberPointerType(
2433 Context.getQualifiedType(Composite2, Quals),
2434 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002435 } else {
2436 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002437 Composite1
2438 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2439 Composite2
2440 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002441 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002442 }
2443
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002444 // Try to convert to the first composite pointer type.
2445 InitializedEntity Entity1
2446 = InitializedEntity::InitializeTemporary(Composite1);
2447 InitializationKind Kind
2448 = InitializationKind::CreateCopy(Loc, SourceLocation());
2449 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2450 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002451
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002452 if (E1ToC1 && E2ToC1) {
2453 // Conversion to Composite1 is viable.
2454 if (!Context.hasSameType(Composite1, Composite2)) {
2455 // Composite2 is a different type from Composite1. Check whether
2456 // Composite2 is also viable.
2457 InitializedEntity Entity2
2458 = InitializedEntity::InitializeTemporary(Composite2);
2459 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2460 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2461 if (E1ToC2 && E2ToC2) {
2462 // Both Composite1 and Composite2 are viable and are different;
2463 // this is an ambiguity.
2464 return QualType();
2465 }
2466 }
2467
2468 // Convert E1 to Composite1
2469 OwningExprResult E1Result
2470 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2471 if (E1Result.isInvalid())
2472 return QualType();
2473 E1 = E1Result.takeAs<Expr>();
2474
2475 // Convert E2 to Composite1
2476 OwningExprResult E2Result
2477 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2478 if (E2Result.isInvalid())
2479 return QualType();
2480 E2 = E2Result.takeAs<Expr>();
2481
2482 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002483 }
2484
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002485 // Check whether Composite2 is viable.
2486 InitializedEntity Entity2
2487 = InitializedEntity::InitializeTemporary(Composite2);
2488 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2489 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2490 if (!E1ToC2 || !E2ToC2)
2491 return QualType();
2492
2493 // Convert E1 to Composite2
2494 OwningExprResult E1Result
2495 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2496 if (E1Result.isInvalid())
2497 return QualType();
2498 E1 = E1Result.takeAs<Expr>();
2499
2500 // Convert E2 to Composite2
2501 OwningExprResult E2Result
2502 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2503 if (E2Result.isInvalid())
2504 return QualType();
2505 E2 = E2Result.takeAs<Expr>();
2506
2507 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002508}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002509
Anders Carlssondef11992009-05-30 20:36:53 +00002510Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002511 if (!Context.getLangOptions().CPlusPlus)
2512 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Douglas Gregor51326552009-12-24 18:51:59 +00002514 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2515
Ted Kremenek6217b802009-07-29 21:53:49 +00002516 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002517 if (!RT)
2518 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002519
John McCall86ff3082010-02-04 22:26:26 +00002520 // If this is the result of a call expression, our source might
2521 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002522 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2523 QualType Ty = CE->getCallee()->getType();
2524 if (const PointerType *PT = Ty->getAs<PointerType>())
2525 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002526 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2527 Ty = BPT->getPointeeType();
2528
John McCall183700f2009-09-21 23:43:11 +00002529 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002530 if (FTy->getResultType()->isReferenceType())
2531 return Owned(E);
2532 }
John McCall86ff3082010-02-04 22:26:26 +00002533
2534 // That should be enough to guarantee that this type is complete.
2535 // If it has a trivial destructor, we can avoid the extra copy.
2536 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2537 if (RD->hasTrivialDestructor())
2538 return Owned(E);
2539
Mike Stump1eb44332009-09-09 15:08:12 +00002540 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002541 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002542 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002543 if (CXXDestructorDecl *Destructor =
John McCallc91cc662010-04-07 00:41:46 +00002544 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002545 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002546 CheckDestructorAccess(E->getExprLoc(), Destructor,
2547 PDiag(diag::err_access_dtor_temp)
2548 << E->getType());
2549 }
Anders Carlssondef11992009-05-30 20:36:53 +00002550 // FIXME: Add the temporary to the temporaries vector.
2551 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2552}
2553
Anders Carlsson0ece4912009-12-15 20:51:39 +00002554Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002555 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002556
John McCall323ed742010-05-06 08:58:33 +00002557 // Check any implicit conversions within the expression.
2558 CheckImplicitConversions(SubExpr);
2559
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002560 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2561 assert(ExprTemporaries.size() >= FirstTemporary);
2562 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002563 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002564
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002565 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002566 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002567 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002568 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2569 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002570
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002571 return E;
2572}
2573
Douglas Gregor90f93822009-12-22 22:17:25 +00002574Sema::OwningExprResult
2575Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2576 if (SubExpr.isInvalid())
2577 return ExprError();
2578
2579 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2580}
2581
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002582FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2583 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2584 assert(ExprTemporaries.size() >= FirstTemporary);
2585
2586 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2587 CXXTemporary **Temporaries =
2588 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2589
2590 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2591
2592 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2593 ExprTemporaries.end());
2594
2595 return E;
2596}
2597
Mike Stump1eb44332009-09-09 15:08:12 +00002598Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002599Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002600 tok::TokenKind OpKind, TypeTy *&ObjectType,
2601 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002602 // Since this might be a postfix expression, get rid of ParenListExprs.
2603 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002604
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002605 Expr *BaseExpr = (Expr*)Base.get();
2606 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002607
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002608 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002609 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002610 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002611 // If we have a pointer to a dependent type and are using the -> operator,
2612 // the object type is the type that the pointer points to. We might still
2613 // have enough information about that type to do something useful.
2614 if (OpKind == tok::arrow)
2615 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2616 BaseType = Ptr->getPointeeType();
2617
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002618 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002619 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002620 return move(Base);
2621 }
Mike Stump1eb44332009-09-09 15:08:12 +00002622
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002623 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002624 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002625 // returned, with the original second operand.
2626 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002627 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002628 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002629 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002630 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002631
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002632 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002633 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002634 BaseExpr = (Expr*)Base.get();
2635 if (BaseExpr == NULL)
2636 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002637 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002638 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002639 BaseType = BaseExpr->getType();
2640 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002641 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002642 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002643 for (unsigned i = 0; i < Locations.size(); i++)
2644 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002645 return ExprError();
2646 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002647 }
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Douglas Gregor31658df2009-11-20 19:58:21 +00002649 if (BaseType->isPointerType())
2650 BaseType = BaseType->getPointeeType();
2651 }
Mike Stump1eb44332009-09-09 15:08:12 +00002652
2653 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002654 // vector types or Objective-C interfaces. Just return early and let
2655 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002656 if (!BaseType->isRecordType()) {
2657 // C++ [basic.lookup.classref]p2:
2658 // [...] If the type of the object expression is of pointer to scalar
2659 // type, the unqualified-id is looked up in the context of the complete
2660 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002661 //
2662 // This also indicates that we should be parsing a
2663 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002664 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002665 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002666 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002667 }
Mike Stump1eb44332009-09-09 15:08:12 +00002668
Douglas Gregor03c57052009-11-17 05:17:33 +00002669 // The object type must be complete (or dependent).
2670 if (!BaseType->isDependentType() &&
2671 RequireCompleteType(OpLoc, BaseType,
2672 PDiag(diag::err_incomplete_member_access)))
2673 return ExprError();
2674
Douglas Gregorc68afe22009-09-03 21:38:09 +00002675 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002676 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002677 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002678 // type C (or of pointer to a class type C), the unqualified-id is looked
2679 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002680 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002681 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002682}
2683
Douglas Gregor77549082010-02-24 21:29:12 +00002684Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2685 ExprArg MemExpr) {
2686 Expr *E = (Expr *) MemExpr.get();
2687 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2688 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2689 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregor849b2432010-03-31 17:46:05 +00002690 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002691
2692 return ActOnCallExpr(/*Scope*/ 0,
2693 move(MemExpr),
2694 /*LPLoc*/ ExpectedLParenLoc,
2695 Sema::MultiExprArg(*this, 0, 0),
2696 /*CommaLocs*/ 0,
2697 /*RPLoc*/ ExpectedLParenLoc);
2698}
Douglas Gregord4dca082010-02-24 18:44:31 +00002699
Douglas Gregorb57fb492010-02-24 22:38:50 +00002700Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2701 SourceLocation OpLoc,
2702 tok::TokenKind OpKind,
2703 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002704 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002705 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002706 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002707 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002708 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002709 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002710
2711 // C++ [expr.pseudo]p2:
2712 // The left-hand side of the dot operator shall be of scalar type. The
2713 // left-hand side of the arrow operator shall be of pointer to scalar type.
2714 // This scalar type is the object type.
2715 Expr *BaseE = (Expr *)Base.get();
2716 QualType ObjectType = BaseE->getType();
2717 if (OpKind == tok::arrow) {
2718 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2719 ObjectType = Ptr->getPointeeType();
2720 } else if (!BaseE->isTypeDependent()) {
2721 // The user wrote "p->" when she probably meant "p."; fix it.
2722 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2723 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002724 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002725 if (isSFINAEContext())
2726 return ExprError();
2727
2728 OpKind = tok::period;
2729 }
2730 }
2731
2732 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2733 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2734 << ObjectType << BaseE->getSourceRange();
2735 return ExprError();
2736 }
2737
2738 // C++ [expr.pseudo]p2:
2739 // [...] The cv-unqualified versions of the object type and of the type
2740 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002741 if (DestructedTypeInfo) {
2742 QualType DestructedType = DestructedTypeInfo->getType();
2743 SourceLocation DestructedTypeStart
2744 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2745 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2746 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2747 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2748 << ObjectType << DestructedType << BaseE->getSourceRange()
2749 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2750
2751 // Recover by setting the destructed type to the object type.
2752 DestructedType = ObjectType;
2753 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2754 DestructedTypeStart);
2755 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2756 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002757 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002758
Douglas Gregorb57fb492010-02-24 22:38:50 +00002759 // C++ [expr.pseudo]p2:
2760 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2761 // form
2762 //
2763 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2764 //
2765 // shall designate the same scalar type.
2766 if (ScopeTypeInfo) {
2767 QualType ScopeType = ScopeTypeInfo->getType();
2768 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2769 !Context.hasSameType(ScopeType, ObjectType)) {
2770
2771 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2772 diag::err_pseudo_dtor_type_mismatch)
2773 << ObjectType << ScopeType << BaseE->getSourceRange()
2774 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2775
2776 ScopeType = QualType();
2777 ScopeTypeInfo = 0;
2778 }
2779 }
2780
2781 OwningExprResult Result
2782 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2783 Base.takeAs<Expr>(),
2784 OpKind == tok::arrow,
2785 OpLoc,
2786 (NestedNameSpecifier *) SS.getScopeRep(),
2787 SS.getRange(),
2788 ScopeTypeInfo,
2789 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002790 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002791 Destructed));
2792
Douglas Gregorb57fb492010-02-24 22:38:50 +00002793 if (HasTrailingLParen)
2794 return move(Result);
2795
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002796 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002797}
2798
2799Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2800 SourceLocation OpLoc,
2801 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002802 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002803 UnqualifiedId &FirstTypeName,
2804 SourceLocation CCLoc,
2805 SourceLocation TildeLoc,
2806 UnqualifiedId &SecondTypeName,
2807 bool HasTrailingLParen) {
2808 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2809 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2810 "Invalid first type name in pseudo-destructor");
2811 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2812 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2813 "Invalid second type name in pseudo-destructor");
2814
2815 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002816
2817 // C++ [expr.pseudo]p2:
2818 // The left-hand side of the dot operator shall be of scalar type. The
2819 // left-hand side of the arrow operator shall be of pointer to scalar type.
2820 // This scalar type is the object type.
2821 QualType ObjectType = BaseE->getType();
2822 if (OpKind == tok::arrow) {
2823 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2824 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002825 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002826 // The user wrote "p->" when she probably meant "p."; fix it.
2827 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002828 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002829 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002830 if (isSFINAEContext())
2831 return ExprError();
2832
2833 OpKind = tok::period;
2834 }
2835 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002836
2837 // Compute the object type that we should use for name lookup purposes. Only
2838 // record types and dependent types matter.
2839 void *ObjectTypePtrForLookup = 0;
2840 if (!SS.isSet()) {
2841 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2842 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2843 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2844 }
Douglas Gregor77549082010-02-24 21:29:12 +00002845
Douglas Gregorb57fb492010-02-24 22:38:50 +00002846 // Convert the name of the type being destructed (following the ~) into a
2847 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002848 QualType DestructedType;
2849 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002850 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002851 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2852 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2853 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002854 S, &SS, true, ObjectTypePtrForLookup);
2855 if (!T &&
2856 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2857 (!SS.isSet() && ObjectType->isDependentType()))) {
2858 // The name of the type being destroyed is a dependent name, and we
2859 // couldn't find anything useful in scope. Just store the identifier and
2860 // it's location, and we'll perform (qualified) name lookup again at
2861 // template instantiation time.
2862 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2863 SecondTypeName.StartLocation);
2864 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002865 Diag(SecondTypeName.StartLocation,
2866 diag::err_pseudo_dtor_destructor_non_type)
2867 << SecondTypeName.Identifier << ObjectType;
2868 if (isSFINAEContext())
2869 return ExprError();
2870
2871 // Recover by assuming we had the right type all along.
2872 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002873 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002874 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002875 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002876 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002877 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002878 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2879 TemplateId->getTemplateArgs(),
2880 TemplateId->NumArgs);
2881 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2882 TemplateId->TemplateNameLoc,
2883 TemplateId->LAngleLoc,
2884 TemplateArgsPtr,
2885 TemplateId->RAngleLoc);
2886 if (T.isInvalid() || !T.get()) {
2887 // Recover by assuming we had the right type all along.
2888 DestructedType = ObjectType;
2889 } else
2890 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002891 }
2892
Douglas Gregorb57fb492010-02-24 22:38:50 +00002893 // If we've performed some kind of recovery, (re-)build the type source
2894 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002895 if (!DestructedType.isNull()) {
2896 if (!DestructedTypeInfo)
2897 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002898 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002899 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2900 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002901
2902 // Convert the name of the scope type (the type prior to '::') into a type.
2903 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002904 QualType ScopeType;
2905 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2906 FirstTypeName.Identifier) {
2907 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2908 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2909 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002910 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002911 if (!T) {
2912 Diag(FirstTypeName.StartLocation,
2913 diag::err_pseudo_dtor_destructor_non_type)
2914 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002915
Douglas Gregorb57fb492010-02-24 22:38:50 +00002916 if (isSFINAEContext())
2917 return ExprError();
2918
2919 // Just drop this type. It's unnecessary anyway.
2920 ScopeType = QualType();
2921 } else
2922 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002923 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002924 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002925 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002926 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2927 TemplateId->getTemplateArgs(),
2928 TemplateId->NumArgs);
2929 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2930 TemplateId->TemplateNameLoc,
2931 TemplateId->LAngleLoc,
2932 TemplateArgsPtr,
2933 TemplateId->RAngleLoc);
2934 if (T.isInvalid() || !T.get()) {
2935 // Recover by dropping this type.
2936 ScopeType = QualType();
2937 } else
2938 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002939 }
2940 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00002941
2942 if (!ScopeType.isNull() && !ScopeTypeInfo)
2943 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2944 FirstTypeName.StartLocation);
2945
2946
Douglas Gregorb57fb492010-02-24 22:38:50 +00002947 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002948 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002949 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00002950}
2951
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002952CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00002953 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002954 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00002955 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2956 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00002957 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2958
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002959 MemberExpr *ME =
2960 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2961 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002962 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002963 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2964 CXXMemberCallExpr *CE =
2965 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2966 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002967 return CE;
2968}
2969
Anders Carlsson165a0a02009-05-17 18:41:29 +00002970Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2971 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002972 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002973 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregoreecf38f2010-05-06 21:39:56 +00002974 else
2975 return ExprError();
2976
Anders Carlsson165a0a02009-05-17 18:41:29 +00002977 return Owned(FullExpr);
2978}