blob: 15c21008bed38a052ffe1de37689d5f5ab1b8e93 [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.
444 InitializedEntity Entity =
445 InitializedEntity::InitializeException(ThrowLoc, E->getType());
446 OwningExprResult Res = PerformCopyInitialization(Entity,
447 SourceLocation(),
448 Owned(E));
449 if (Res.isInvalid())
450 return true;
451 E = Res.takeAs<Expr>();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000452
453 // If we are throwing a polymorphic class type or pointer thereof,
454 // exception handling will make use of the vtable.
455 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
456 MarkVTableUsed(ThrowLoc, cast<CXXRecordDecl>(RecordTy->getDecl()));
457
Sebastian Redl972041f2009-04-27 20:27:31 +0000458 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000459}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000460
Sebastian Redlf53597f2009-03-15 17:47:39 +0000461Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000462 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
463 /// is a non-lvalue expression whose value is the address of the object for
464 /// which the function is called.
465
Sebastian Redlf53597f2009-03-15 17:47:39 +0000466 if (!isa<FunctionDecl>(CurContext))
467 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000468
469 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
470 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000471 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000472 MD->getThisType(Context),
473 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000474
Sebastian Redlf53597f2009-03-15 17:47:39 +0000475 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000476}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000477
478/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
479/// Can be interpreted either as function-style casting ("int(x)")
480/// or class type construction ("ClassType(x,y,z)")
481/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000482Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000483Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
484 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000485 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000486 SourceLocation *CommaLocs,
487 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000488 if (!TypeRep)
489 return ExprError();
490
John McCall9d125032010-01-15 18:39:57 +0000491 TypeSourceInfo *TInfo;
492 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
493 if (!TInfo)
494 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000495 unsigned NumExprs = exprs.size();
496 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000497 SourceLocation TyBeginLoc = TypeRange.getBegin();
498 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
499
Sebastian Redlf53597f2009-03-15 17:47:39 +0000500 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000501 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000502 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000503
504 return Owned(CXXUnresolvedConstructExpr::Create(Context,
505 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000506 LParenLoc,
507 Exprs, NumExprs,
508 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000509 }
510
Anders Carlssonbb60a502009-08-27 03:53:50 +0000511 if (Ty->isArrayType())
512 return ExprError(Diag(TyBeginLoc,
513 diag::err_value_init_for_array_type) << FullRange);
514 if (!Ty->isVoidType() &&
515 RequireCompleteType(TyBeginLoc, Ty,
516 PDiag(diag::err_invalid_incomplete_type_use)
517 << FullRange))
518 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000519
Anders Carlssonbb60a502009-08-27 03:53:50 +0000520 if (RequireNonAbstractType(TyBeginLoc, Ty,
521 diag::err_allocation_of_abstract_type))
522 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000523
524
Douglas Gregor506ae412009-01-16 18:33:17 +0000525 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000526 // If the expression list is a single expression, the type conversion
527 // expression is equivalent (in definedness, and if defined in meaning) to the
528 // corresponding cast expression.
529 //
530 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000531 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000532 CXXBaseSpecifierArray BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000533 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath,
534 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000535 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000536
537 exprs.release();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000538
539 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000540 TInfo, TyBeginLoc, Kind,
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000541 Exprs[0], BasePath,
542 RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000543 }
544
Ted Kremenek6217b802009-07-29 21:53:49 +0000545 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000546 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000547
Mike Stump1eb44332009-09-09 15:08:12 +0000548 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000549 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000550 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
551 InitializationKind Kind
552 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
553 LParenLoc, RParenLoc)
554 : InitializationKind::CreateValue(TypeRange.getBegin(),
555 LParenLoc, RParenLoc);
556 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
557 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
558 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000559
Eli Friedman6997aae2010-01-31 20:58:15 +0000560 // FIXME: Improve AST representation?
561 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000562 }
563
564 // Fall through to value-initialize an object of class type that
565 // doesn't have a user-declared default constructor.
566 }
567
568 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000569 // If the expression list specifies more than a single value, the type shall
570 // be a class with a suitably declared constructor.
571 //
572 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000573 return ExprError(Diag(CommaLocs[0],
574 diag::err_builtin_func_cast_more_than_one_arg)
575 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000576
577 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000578 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000579 // The expression T(), where T is a simple-type-specifier for a non-array
580 // complete object type or the (possibly cv-qualified) void type, creates an
581 // rvalue of the specified type, which is value-initialized.
582 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000583 exprs.release();
584 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000585}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000586
587
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000588/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
589/// @code new (memory) int[size][4] @endcode
590/// or
591/// @code ::new Foo(23, "hello") @endcode
592/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000593Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000594Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000595 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000596 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000597 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000598 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000599 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000600 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000601 // If the specified type is an array, unwrap it and save the expression.
602 if (D.getNumTypeObjects() > 0 &&
603 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
604 DeclaratorChunk &Chunk = D.getTypeObject(0);
605 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000606 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
607 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000608 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000609 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
610 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000611
612 if (ParenTypeId) {
613 // Can't have dynamic array size when the type-id is in parentheses.
614 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
615 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
616 !NumElts->isIntegerConstantExpr(Context)) {
617 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
618 << NumElts->getSourceRange();
619 return ExprError();
620 }
621 }
622
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000623 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000624 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000625 }
626
Douglas Gregor043cad22009-09-11 00:18:58 +0000627 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000628 if (ArraySize) {
629 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000630 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
631 break;
632
633 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
634 if (Expr *NumElts = (Expr *)Array.NumElts) {
635 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
636 !NumElts->isIntegerConstantExpr(Context)) {
637 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
638 << NumElts->getSourceRange();
639 return ExprError();
640 }
641 }
642 }
643 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000644
John McCalla93c9342009-12-07 02:54:59 +0000645 //FIXME: Store TypeSourceInfo in CXXNew expression.
646 TypeSourceInfo *TInfo = 0;
647 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000648 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000649 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000650
Mike Stump1eb44332009-09-09 15:08:12 +0000651 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000652 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000653 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000654 PlacementRParen,
655 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000656 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000657 D.getSourceRange().getBegin(),
658 D.getSourceRange(),
659 Owned(ArraySize),
660 ConstructorLParen,
661 move(ConstructorArgs),
662 ConstructorRParen);
663}
664
Mike Stump1eb44332009-09-09 15:08:12 +0000665Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000666Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
667 SourceLocation PlacementLParen,
668 MultiExprArg PlacementArgs,
669 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000670 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000671 QualType AllocType,
672 SourceLocation TypeLoc,
673 SourceRange TypeRange,
674 ExprArg ArraySizeE,
675 SourceLocation ConstructorLParen,
676 MultiExprArg ConstructorArgs,
677 SourceLocation ConstructorRParen) {
678 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000679 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000680
Douglas Gregor3433cf72009-05-21 00:00:09 +0000681 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000682
683 // That every array dimension except the first is constant was already
684 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000685
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000686 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
687 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000688 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000689 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000690 QualType SizeType = ArraySize->getType();
691 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000692 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
693 diag::err_array_size_not_integral)
694 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000695 // Let's see if this is a constant < 0. If so, we reject it out of hand.
696 // We don't care about special rules, so we tell the machinery it's not
697 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000698 if (!ArraySize->isValueDependent()) {
699 llvm::APSInt Value;
700 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
701 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000702 llvm::APInt::getNullValue(Value.getBitWidth()),
703 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000704 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
705 diag::err_typecheck_negative_array_size)
706 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000707 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000708 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000709
Eli Friedman73c39ab2009-10-20 08:27:19 +0000710 ImpCastExprToType(ArraySize, Context.getSizeType(),
711 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000712 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000713
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000714 FunctionDecl *OperatorNew = 0;
715 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000716 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
717 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000718
Sebastian Redl28507842009-02-26 14:39:58 +0000719 if (!AllocType->isDependentType() &&
720 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
721 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000722 SourceRange(PlacementLParen, PlacementRParen),
723 UseGlobal, AllocType, ArraySize, PlaceArgs,
724 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000725 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000726 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000727 if (OperatorNew) {
728 // Add default arguments, if any.
729 const FunctionProtoType *Proto =
730 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000731 VariadicCallType CallType =
732 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Anders Carlsson28e94832010-05-03 02:07:56 +0000733
734 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
735 Proto, 1, PlaceArgs, NumPlaceArgs,
736 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000737 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000738
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000739 NumPlaceArgs = AllPlaceArgs.size();
740 if (NumPlaceArgs > 0)
741 PlaceArgs = &AllPlaceArgs[0];
742 }
743
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000744 bool Init = ConstructorLParen.isValid();
745 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000746 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000747 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
748 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000749 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
750
Anders Carlsson48c95012010-05-03 15:45:23 +0000751 // Array 'new' can't have any initializers.
752 if (NumConsArgs && ArraySize) {
753 SourceRange InitRange(ConsArgs[0]->getLocStart(),
754 ConsArgs[NumConsArgs - 1]->getLocEnd());
755
756 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
757 return ExprError();
758 }
759
Douglas Gregor99a2e602009-12-16 01:38:02 +0000760 if (!AllocType->isDependentType() &&
761 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
762 // C++0x [expr.new]p15:
763 // A new-expression that creates an object of type T initializes that
764 // object as follows:
765 InitializationKind Kind
766 // - If the new-initializer is omitted, the object is default-
767 // initialized (8.5); if no initialization is performed,
768 // the object has indeterminate value
769 = !Init? InitializationKind::CreateDefault(TypeLoc)
770 // - Otherwise, the new-initializer is interpreted according to the
771 // initialization rules of 8.5 for direct-initialization.
772 : InitializationKind::CreateDirect(TypeLoc,
773 ConstructorLParen,
774 ConstructorRParen);
775
Douglas Gregor99a2e602009-12-16 01:38:02 +0000776 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000777 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000778 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000779 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
780 move(ConstructorArgs));
781 if (FullInit.isInvalid())
782 return ExprError();
783
784 // FullInit is our initializer; walk through it to determine if it's a
785 // constructor call, which CXXNewExpr handles directly.
786 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
787 if (CXXBindTemporaryExpr *Binder
788 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
789 FullInitExpr = Binder->getSubExpr();
790 if (CXXConstructExpr *Construct
791 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
792 Constructor = Construct->getConstructor();
793 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
794 AEnd = Construct->arg_end();
795 A != AEnd; ++A)
796 ConvertedConstructorArgs.push_back(A->Retain());
797 } else {
798 // Take the converted initializer.
799 ConvertedConstructorArgs.push_back(FullInit.release());
800 }
801 } else {
802 // No initialization required.
803 }
804
805 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000806 NumConsArgs = ConvertedConstructorArgs.size();
807 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000808 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000809
Douglas Gregor6d908702010-02-26 05:06:18 +0000810 // Mark the new and delete operators as referenced.
811 if (OperatorNew)
812 MarkDeclarationReferenced(StartLoc, OperatorNew);
813 if (OperatorDelete)
814 MarkDeclarationReferenced(StartLoc, OperatorDelete);
815
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000816 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000817
Sebastian Redlf53597f2009-03-15 17:47:39 +0000818 PlacementArgs.release();
819 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000820 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000821 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
822 PlaceArgs, NumPlaceArgs, ParenTypeId,
823 ArraySize, Constructor, Init,
824 ConsArgs, NumConsArgs, OperatorDelete,
825 ResultType, StartLoc,
826 Init ? ConstructorRParen :
827 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000828}
829
830/// CheckAllocatedType - Checks that a type is suitable as the allocated type
831/// in a new-expression.
832/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000833bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000834 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000835 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
836 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000837 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000838 return Diag(Loc, diag::err_bad_new_type)
839 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000840 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000841 return Diag(Loc, diag::err_bad_new_type)
842 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000843 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000844 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000845 PDiag(diag::err_new_incomplete_type)
846 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000847 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000848 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000849 diag::err_allocation_of_abstract_type))
850 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000851
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000852 return false;
853}
854
Douglas Gregor6d908702010-02-26 05:06:18 +0000855/// \brief Determine whether the given function is a non-placement
856/// deallocation function.
857static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
858 if (FD->isInvalidDecl())
859 return false;
860
861 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
862 return Method->isUsualDeallocationFunction();
863
864 return ((FD->getOverloadedOperator() == OO_Delete ||
865 FD->getOverloadedOperator() == OO_Array_Delete) &&
866 FD->getNumParams() == 1);
867}
868
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000869/// FindAllocationFunctions - Finds the overloads of operator new and delete
870/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000871bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
872 bool UseGlobal, QualType AllocType,
873 bool IsArray, Expr **PlaceArgs,
874 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000875 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000876 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000877 // --- Choosing an allocation function ---
878 // C++ 5.3.4p8 - 14 & 18
879 // 1) If UseGlobal is true, only look in the global scope. Else, also look
880 // in the scope of the allocated class.
881 // 2) If an array size is given, look for operator new[], else look for
882 // operator new.
883 // 3) The first argument is always size_t. Append the arguments from the
884 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000885
886 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
887 // We don't care about the actual value of this argument.
888 // FIXME: Should the Sema create the expression and embed it in the syntax
889 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000890 IntegerLiteral Size(llvm::APInt::getNullValue(
891 Context.Target.getPointerWidth(0)),
892 Context.getSizeType(),
893 SourceLocation());
894 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000895 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
896
Douglas Gregor6d908702010-02-26 05:06:18 +0000897 // C++ [expr.new]p8:
898 // If the allocated type is a non-array type, the allocation
899 // function’s name is operator new and the deallocation function’s
900 // name is operator delete. If the allocated type is an array
901 // type, the allocation function’s name is operator new[] and the
902 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000903 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
904 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000905 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
906 IsArray ? OO_Array_Delete : OO_Delete);
907
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000908 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000909 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000910 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000911 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000912 AllocArgs.size(), Record, /*AllowMissing=*/true,
913 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000914 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000915 }
916 if (!OperatorNew) {
917 // Didn't find a member overload. Look for a global one.
918 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000919 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000920 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000921 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
922 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000923 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000924 }
925
John McCall9c82afc2010-04-20 02:18:25 +0000926 // We don't need an operator delete if we're running under
927 // -fno-exceptions.
928 if (!getLangOptions().Exceptions) {
929 OperatorDelete = 0;
930 return false;
931 }
932
Anders Carlssond9583892009-05-31 20:26:12 +0000933 // FindAllocationOverload can change the passed in arguments, so we need to
934 // copy them back.
935 if (NumPlaceArgs > 0)
936 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Douglas Gregor6d908702010-02-26 05:06:18 +0000938 // C++ [expr.new]p19:
939 //
940 // If the new-expression begins with a unary :: operator, the
941 // deallocation function’s name is looked up in the global
942 // scope. Otherwise, if the allocated type is a class type T or an
943 // array thereof, the deallocation function’s name is looked up in
944 // the scope of T. If this lookup fails to find the name, or if
945 // the allocated type is not a class type or array thereof, the
946 // deallocation function’s name is looked up in the global scope.
947 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
948 if (AllocType->isRecordType() && !UseGlobal) {
949 CXXRecordDecl *RD
950 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
951 LookupQualifiedName(FoundDelete, RD);
952 }
John McCall90c8c572010-03-18 08:19:33 +0000953 if (FoundDelete.isAmbiguous())
954 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000955
956 if (FoundDelete.empty()) {
957 DeclareGlobalNewDelete();
958 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
959 }
960
961 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000962
963 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
964
John McCall90c8c572010-03-18 08:19:33 +0000965 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +0000966 // C++ [expr.new]p20:
967 // A declaration of a placement deallocation function matches the
968 // declaration of a placement allocation function if it has the
969 // same number of parameters and, after parameter transformations
970 // (8.3.5), all parameter types except the first are
971 // identical. [...]
972 //
973 // To perform this comparison, we compute the function type that
974 // the deallocation function should have, and use that type both
975 // for template argument deduction and for comparison purposes.
976 QualType ExpectedFunctionType;
977 {
978 const FunctionProtoType *Proto
979 = OperatorNew->getType()->getAs<FunctionProtoType>();
980 llvm::SmallVector<QualType, 4> ArgTypes;
981 ArgTypes.push_back(Context.VoidPtrTy);
982 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
983 ArgTypes.push_back(Proto->getArgType(I));
984
985 ExpectedFunctionType
986 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
987 ArgTypes.size(),
988 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +0000989 0, false, false, 0, 0,
990 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +0000991 }
992
993 for (LookupResult::iterator D = FoundDelete.begin(),
994 DEnd = FoundDelete.end();
995 D != DEnd; ++D) {
996 FunctionDecl *Fn = 0;
997 if (FunctionTemplateDecl *FnTmpl
998 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
999 // Perform template argument deduction to try to match the
1000 // expected function type.
1001 TemplateDeductionInfo Info(Context, StartLoc);
1002 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1003 continue;
1004 } else
1005 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1006
1007 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001008 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001009 }
1010 } else {
1011 // C++ [expr.new]p20:
1012 // [...] Any non-placement deallocation function matches a
1013 // non-placement allocation function. [...]
1014 for (LookupResult::iterator D = FoundDelete.begin(),
1015 DEnd = FoundDelete.end();
1016 D != DEnd; ++D) {
1017 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1018 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001019 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001020 }
1021 }
1022
1023 // C++ [expr.new]p20:
1024 // [...] If the lookup finds a single matching deallocation
1025 // function, that function will be called; otherwise, no
1026 // deallocation function will be called.
1027 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001028 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001029
1030 // C++0x [expr.new]p20:
1031 // If the lookup finds the two-parameter form of a usual
1032 // deallocation function (3.7.4.2) and that function, considered
1033 // as a placement deallocation function, would have been
1034 // selected as a match for the allocation function, the program
1035 // is ill-formed.
1036 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
1037 isNonPlacementDeallocationFunction(OperatorDelete)) {
1038 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1039 << SourceRange(PlaceArgs[0]->getLocStart(),
1040 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1041 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1042 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001043 } else {
1044 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001045 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001046 }
1047 }
1048
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001049 return false;
1050}
1051
Sebastian Redl7f662392008-12-04 22:20:51 +00001052/// FindAllocationOverload - Find an fitting overload for the allocation
1053/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001054bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1055 DeclarationName Name, Expr** Args,
1056 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001057 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001058 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1059 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001060 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001061 if (AllowMissing)
1062 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001063 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001064 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001065 }
1066
John McCall90c8c572010-03-18 08:19:33 +00001067 if (R.isAmbiguous())
1068 return true;
1069
1070 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001071
John McCall5769d612010-02-08 23:07:23 +00001072 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001073 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1074 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001075 // Even member operator new/delete are implicitly treated as
1076 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001077 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001078
John McCall9aa472c2010-03-19 07:35:19 +00001079 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1080 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001081 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1082 Candidates,
1083 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001084 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001085 }
1086
John McCall9aa472c2010-03-19 07:35:19 +00001087 FunctionDecl *Fn = cast<FunctionDecl>(D);
1088 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001089 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001090 }
1091
1092 // Do the resolution.
1093 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001094 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001095 case OR_Success: {
1096 // Got one!
1097 FunctionDecl *FnDecl = Best->Function;
1098 // The first argument is size_t, and the first parameter must be size_t,
1099 // too. This is checked on declaration and can be assumed. (It can't be
1100 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001101 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001102 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1103 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001104 OwningExprResult Result
1105 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1106 FnDecl->getParamDecl(i)),
1107 SourceLocation(),
1108 Owned(Args[i]->Retain()));
1109 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001110 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001111
1112 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001113 }
1114 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001115 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001116 return false;
1117 }
1118
1119 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001120 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001121 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001122 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001123 return true;
1124
1125 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001126 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001127 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001128 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001129 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001130
1131 case OR_Deleted:
1132 Diag(StartLoc, diag::err_ovl_deleted_call)
1133 << Best->Function->isDeleted()
1134 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001135 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001136 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001137 }
1138 assert(false && "Unreachable, bad result from BestViableFunction");
1139 return true;
1140}
1141
1142
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001143/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1144/// delete. These are:
1145/// @code
1146/// void* operator new(std::size_t) throw(std::bad_alloc);
1147/// void* operator new[](std::size_t) throw(std::bad_alloc);
1148/// void operator delete(void *) throw();
1149/// void operator delete[](void *) throw();
1150/// @endcode
1151/// Note that the placement and nothrow forms of new are *not* implicitly
1152/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001153void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001154 if (GlobalNewDeleteDeclared)
1155 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001156
1157 // C++ [basic.std.dynamic]p2:
1158 // [...] The following allocation and deallocation functions (18.4) are
1159 // implicitly declared in global scope in each translation unit of a
1160 // program
1161 //
1162 // void* operator new(std::size_t) throw(std::bad_alloc);
1163 // void* operator new[](std::size_t) throw(std::bad_alloc);
1164 // void operator delete(void*) throw();
1165 // void operator delete[](void*) throw();
1166 //
1167 // These implicit declarations introduce only the function names operator
1168 // new, operator new[], operator delete, operator delete[].
1169 //
1170 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1171 // "std" or "bad_alloc" as necessary to form the exception specification.
1172 // However, we do not make these implicit declarations visible to name
1173 // lookup.
1174 if (!StdNamespace) {
1175 // The "std" namespace has not yet been defined, so build one implicitly.
1176 StdNamespace = NamespaceDecl::Create(Context,
1177 Context.getTranslationUnitDecl(),
1178 SourceLocation(),
1179 &PP.getIdentifierTable().get("std"));
1180 StdNamespace->setImplicit(true);
1181 }
1182
1183 if (!StdBadAlloc) {
1184 // The "std::bad_alloc" class has not yet been declared, so build it
1185 // implicitly.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001186 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001187 StdNamespace,
1188 SourceLocation(),
1189 &PP.getIdentifierTable().get("bad_alloc"),
1190 SourceLocation(), 0);
1191 StdBadAlloc->setImplicit(true);
1192 }
1193
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001194 GlobalNewDeleteDeclared = true;
1195
1196 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1197 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001198 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001199
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001200 DeclareGlobalAllocationFunction(
1201 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001202 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001203 DeclareGlobalAllocationFunction(
1204 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001205 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001206 DeclareGlobalAllocationFunction(
1207 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1208 Context.VoidTy, VoidPtr);
1209 DeclareGlobalAllocationFunction(
1210 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1211 Context.VoidTy, VoidPtr);
1212}
1213
1214/// DeclareGlobalAllocationFunction - Declares a single implicit global
1215/// allocation function if it doesn't already exist.
1216void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001217 QualType Return, QualType Argument,
1218 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001219 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1220
1221 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001222 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001223 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001224 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001225 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001226 // Only look at non-template functions, as it is the predefined,
1227 // non-templated allocation function we are trying to declare here.
1228 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1229 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001230 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001231 Func->getParamDecl(0)->getType().getUnqualifiedType());
1232 // FIXME: Do we need to check for default arguments here?
1233 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1234 return;
1235 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001236 }
1237 }
1238
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001239 QualType BadAllocType;
1240 bool HasBadAllocExceptionSpec
1241 = (Name.getCXXOverloadedOperator() == OO_New ||
1242 Name.getCXXOverloadedOperator() == OO_Array_New);
1243 if (HasBadAllocExceptionSpec) {
1244 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1245 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1246 }
1247
1248 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1249 true, false,
1250 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001251 &BadAllocType,
1252 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001253 FunctionDecl *Alloc =
1254 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001255 FnType, /*TInfo=*/0, FunctionDecl::None,
1256 FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001257 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001258
1259 if (AddMallocAttr)
1260 Alloc->addAttr(::new (Context) MallocAttr());
1261
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001262 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001263 0, Argument, /*TInfo=*/0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001264 VarDecl::None,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001265 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001266 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001267
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001268 // FIXME: Also add this declaration to the IdentifierResolver, but
1269 // make sure it is at the end of the chain to coincide with the
1270 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001271 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001272}
1273
Anders Carlsson78f74552009-11-15 18:45:20 +00001274bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1275 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001276 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001277 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001278 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001279 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001280
John McCalla24dc2e2009-11-17 02:14:36 +00001281 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001282 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001283
1284 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1285 F != FEnd; ++F) {
1286 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1287 if (Delete->isUsualDeallocationFunction()) {
1288 Operator = Delete;
1289 return false;
1290 }
1291 }
1292
1293 // We did find operator delete/operator delete[] declarations, but
1294 // none of them were suitable.
1295 if (!Found.empty()) {
1296 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1297 << Name << RD;
1298
1299 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1300 F != FEnd; ++F) {
Douglas Gregorb0fd4832010-04-25 20:55:08 +00001301 Diag((*F)->getLocation(), diag::note_member_declared_here)
Anders Carlsson78f74552009-11-15 18:45:20 +00001302 << Name;
1303 }
1304
1305 return true;
1306 }
1307
1308 // Look for a global declaration.
1309 DeclareGlobalNewDelete();
1310 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1311
1312 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1313 Expr* DeallocArgs[1];
1314 DeallocArgs[0] = &Null;
1315 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1316 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1317 Operator))
1318 return true;
1319
1320 assert(Operator && "Did not find a deallocation function!");
1321 return false;
1322}
1323
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001324/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1325/// @code ::delete ptr; @endcode
1326/// or
1327/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001328Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001329Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001330 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001331 // C++ [expr.delete]p1:
1332 // The operand shall have a pointer type, or a class type having a single
1333 // conversion function to a pointer type. The result has type void.
1334 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001335 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1336
Anders Carlssond67c4c32009-08-16 20:29:29 +00001337 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Sebastian Redlf53597f2009-03-15 17:47:39 +00001339 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001340 if (!Ex->isTypeDependent()) {
1341 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001342
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001343 if (const RecordType *Record = Type->getAs<RecordType>()) {
John McCall32daa422010-03-31 01:36:47 +00001344 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
1345
Fariborz Jahanian53462782009-09-11 21:44:33 +00001346 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCall32daa422010-03-31 01:36:47 +00001347 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001348 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001349 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00001350 NamedDecl *D = I.getDecl();
1351 if (isa<UsingShadowDecl>(D))
1352 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1353
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001354 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00001355 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001356 continue;
1357
John McCall32daa422010-03-31 01:36:47 +00001358 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001359
1360 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1361 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1362 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001363 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001364 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001365 if (ObjectPtrConversions.size() == 1) {
1366 // We have a single conversion to a pointer-to-object type. Perform
1367 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00001368 // TODO: don't redo the conversion calculation.
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001369 Operand.release();
John McCall32daa422010-03-31 01:36:47 +00001370 if (!PerformImplicitConversion(Ex,
1371 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001372 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001373 Operand = Owned(Ex);
1374 Type = Ex->getType();
1375 }
1376 }
1377 else if (ObjectPtrConversions.size() > 1) {
1378 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1379 << Type << Ex->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00001380 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
1381 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001382 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001383 }
Sebastian Redl28507842009-02-26 14:39:58 +00001384 }
1385
Sebastian Redlf53597f2009-03-15 17:47:39 +00001386 if (!Type->isPointerType())
1387 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1388 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001389
Ted Kremenek6217b802009-07-29 21:53:49 +00001390 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001391 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001392 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1393 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001394 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001395 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001396 PDiag(diag::warn_delete_incomplete)
1397 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001398 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001399
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001400 // C++ [expr.delete]p2:
1401 // [Note: a pointer to a const type can be the operand of a
1402 // delete-expression; it is not necessary to cast away the constness
1403 // (5.2.11) of the pointer expression before it is used as the operand
1404 // of the delete-expression. ]
1405 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1406 CastExpr::CK_NoOp);
1407
1408 // Update the operand.
1409 Operand.take();
1410 Operand = ExprArg(*this, Ex);
1411
Anders Carlssond67c4c32009-08-16 20:29:29 +00001412 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1413 ArrayForm ? OO_Array_Delete : OO_Delete);
1414
Anders Carlsson78f74552009-11-15 18:45:20 +00001415 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1416 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1417
1418 if (!UseGlobal &&
1419 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001420 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001421
Anders Carlsson78f74552009-11-15 18:45:20 +00001422 if (!RD->hasTrivialDestructor())
1423 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001424 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001425 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001426 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001427
Anders Carlssond67c4c32009-08-16 20:29:29 +00001428 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001429 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001430 DeclareGlobalNewDelete();
1431 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001432 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001433 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001434 OperatorDelete))
1435 return ExprError();
1436 }
Mike Stump1eb44332009-09-09 15:08:12 +00001437
John McCall9c82afc2010-04-20 02:18:25 +00001438 MarkDeclarationReferenced(StartLoc, OperatorDelete);
1439
Sebastian Redl28507842009-02-26 14:39:58 +00001440 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001441 }
1442
Sebastian Redlf53597f2009-03-15 17:47:39 +00001443 Operand.release();
1444 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001445 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001446}
1447
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001448/// \brief Check the use of the given variable as a C++ condition in an if,
1449/// while, do-while, or switch statement.
Douglas Gregor586596f2010-05-06 17:25:47 +00001450Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
1451 SourceLocation StmtLoc,
1452 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001453 QualType T = ConditionVar->getType();
1454
1455 // C++ [stmt.select]p2:
1456 // The declarator shall not specify a function or an array.
1457 if (T->isFunctionType())
1458 return ExprError(Diag(ConditionVar->getLocation(),
1459 diag::err_invalid_use_of_function_type)
1460 << ConditionVar->getSourceRange());
1461 else if (T->isArrayType())
1462 return ExprError(Diag(ConditionVar->getLocation(),
1463 diag::err_invalid_use_of_array_type)
1464 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001465
Douglas Gregor586596f2010-05-06 17:25:47 +00001466 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1467 ConditionVar->getLocation(),
1468 ConditionVar->getType().getNonReferenceType());
1469 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) {
1470 Condition->Destroy(Context);
1471 return ExprError();
1472 }
1473
1474 return Owned(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001475}
1476
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001477/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1478bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1479 // C++ 6.4p4:
1480 // The value of a condition that is an initialized declaration in a statement
1481 // other than a switch statement is the value of the declared variable
1482 // implicitly converted to type bool. If that conversion is ill-formed, the
1483 // program is ill-formed.
1484 // The value of a condition that is an expression is the value of the
1485 // expression, implicitly converted to bool.
1486 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001487 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001488}
Douglas Gregor77a52232008-09-12 00:47:35 +00001489
1490/// Helper function to determine whether this is the (deprecated) C++
1491/// conversion from a string literal to a pointer to non-const char or
1492/// non-const wchar_t (for narrow and wide string literals,
1493/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001494bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001495Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1496 // Look inside the implicit cast, if it exists.
1497 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1498 From = Cast->getSubExpr();
1499
1500 // A string literal (2.13.4) that is not a wide string literal can
1501 // be converted to an rvalue of type "pointer to char"; a wide
1502 // string literal can be converted to an rvalue of type "pointer
1503 // to wchar_t" (C++ 4.2p2).
1504 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001505 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001506 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001507 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001508 // This conversion is considered only when there is an
1509 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001510 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001511 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1512 (!StrLit->isWide() &&
1513 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1514 ToPointeeType->getKind() == BuiltinType::Char_S))))
1515 return true;
1516 }
1517
1518 return false;
1519}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001520
Douglas Gregorba70ab62010-04-16 22:17:36 +00001521static Sema::OwningExprResult BuildCXXCastArgument(Sema &S,
1522 SourceLocation CastLoc,
1523 QualType Ty,
1524 CastExpr::CastKind Kind,
1525 CXXMethodDecl *Method,
1526 Sema::ExprArg Arg) {
1527 Expr *From = Arg.takeAs<Expr>();
1528
1529 switch (Kind) {
1530 default: assert(0 && "Unhandled cast kind!");
1531 case CastExpr::CK_ConstructorConversion: {
1532 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
1533
1534 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
1535 Sema::MultiExprArg(S, (void **)&From, 1),
1536 CastLoc, ConstructorArgs))
1537 return S.ExprError();
1538
1539 Sema::OwningExprResult Result =
1540 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
1541 move_arg(ConstructorArgs));
1542 if (Result.isInvalid())
1543 return S.ExprError();
1544
1545 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
1546 }
1547
1548 case CastExpr::CK_UserDefinedConversion: {
1549 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
1550
1551 // Create an implicit call expr that calls it.
1552 // FIXME: pass the FoundDecl for the user-defined conversion here
1553 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method);
1554 return S.MaybeBindToTemporary(CE);
1555 }
1556 }
1557}
1558
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001559/// PerformImplicitConversion - Perform an implicit conversion of the
1560/// expression From to the type ToType using the pre-computed implicit
1561/// conversion sequence ICS. Returns true if there was an error, false
1562/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001563/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001564/// used in the error message.
1565bool
1566Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1567 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001568 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001569 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001570 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001571 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001572 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001573 return true;
1574 break;
1575
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001576 case ImplicitConversionSequence::UserDefinedConversion: {
1577
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001578 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1579 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001580 QualType BeforeToType;
1581 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001582 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001583
1584 // If the user-defined conversion is specified by a conversion function,
1585 // the initial standard conversion sequence converts the source type to
1586 // the implicit object parameter of the conversion function.
1587 BeforeToType = Context.getTagDeclType(Conv->getParent());
1588 } else if (const CXXConstructorDecl *Ctor =
1589 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001590 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001591 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001592 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001593 // If the user-defined conversion is specified by a constructor, the
1594 // initial standard conversion sequence converts the source type to the
1595 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001596 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1597 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001598 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001599 else
1600 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001601 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001602 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001603 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001604 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001605 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001606 return true;
1607 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001608
Anders Carlsson0aebc812009-09-09 21:33:21 +00001609 OwningExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00001610 = BuildCXXCastArgument(*this,
1611 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00001612 ToType.getNonReferenceType(),
1613 CastKind, cast<CXXMethodDecl>(FD),
1614 Owned(From));
1615
1616 if (CastArg.isInvalid())
1617 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001618
1619 From = CastArg.takeAs<Expr>();
1620
Eli Friedmand8889622009-11-27 04:41:50 +00001621 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001622 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001623 }
John McCall1d318332010-01-12 00:44:57 +00001624
1625 case ImplicitConversionSequence::AmbiguousConversion:
1626 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1627 PDiag(diag::err_typecheck_ambiguous_condition)
1628 << From->getSourceRange());
1629 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001630
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001631 case ImplicitConversionSequence::EllipsisConversion:
1632 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001633 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001634
1635 case ImplicitConversionSequence::BadConversion:
1636 return true;
1637 }
1638
1639 // Everything went well.
1640 return false;
1641}
1642
1643/// PerformImplicitConversion - Perform an implicit conversion of the
1644/// expression From to the type ToType by following the standard
1645/// conversion sequence SCS. Returns true if there was an error, false
1646/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001647/// expression. Flavor is the context in which we're performing this
1648/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001649bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001650Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001651 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001652 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001653 // Overall FIXME: we are recomputing too many types here and doing far too
1654 // much extra work. What this means is that we need to keep track of more
1655 // information that is computed when we try the implicit conversion initially,
1656 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001657 QualType FromType = From->getType();
1658
Douglas Gregor225c41e2008-11-03 19:09:14 +00001659 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001660 // FIXME: When can ToType be a reference type?
1661 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001662 if (SCS.Second == ICK_Derived_To_Base) {
1663 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1664 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1665 MultiExprArg(*this, (void **)&From, 1),
1666 /*FIXME:ConstructLoc*/SourceLocation(),
1667 ConstructorArgs))
1668 return true;
1669 OwningExprResult FromResult =
1670 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1671 ToType, SCS.CopyConstructor,
1672 move_arg(ConstructorArgs));
1673 if (FromResult.isInvalid())
1674 return true;
1675 From = FromResult.takeAs<Expr>();
1676 return false;
1677 }
Mike Stump1eb44332009-09-09 15:08:12 +00001678 OwningExprResult FromResult =
1679 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1680 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001681 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001683 if (FromResult.isInvalid())
1684 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001686 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001687 return false;
1688 }
1689
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001690 // Resolve overloaded function references.
1691 if (Context.hasSameType(FromType, Context.OverloadTy)) {
1692 DeclAccessPair Found;
1693 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
1694 true, Found);
1695 if (!Fn)
1696 return true;
1697
1698 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1699 return true;
1700
1701 From = FixOverloadedFunctionReference(From, Found, Fn);
1702 FromType = From->getType();
1703 }
1704
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001705 // Perform the first implicit conversion.
1706 switch (SCS.First) {
1707 case ICK_Identity:
1708 case ICK_Lvalue_To_Rvalue:
1709 // Nothing to do.
1710 break;
1711
1712 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001713 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001714 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001715 break;
1716
1717 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001718 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001719 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001720 break;
1721
1722 default:
1723 assert(false && "Improper first standard conversion");
1724 break;
1725 }
1726
1727 // Perform the second implicit conversion
1728 switch (SCS.Second) {
1729 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001730 // If both sides are functions (or pointers/references to them), there could
1731 // be incompatible exception declarations.
1732 if (CheckExceptionSpecCompatibility(From, ToType))
1733 return true;
1734 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001735 break;
1736
Douglas Gregor43c79c22009-12-09 00:47:37 +00001737 case ICK_NoReturn_Adjustment:
1738 // If both sides are functions (or pointers/references to them), there could
1739 // be incompatible exception declarations.
1740 if (CheckExceptionSpecCompatibility(From, ToType))
1741 return true;
1742
1743 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1744 CastExpr::CK_NoOp);
1745 break;
1746
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001747 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001748 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001749 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1750 break;
1751
1752 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001753 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001754 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1755 break;
1756
1757 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001758 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001759 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1760 break;
1761
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001762 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001763 if (ToType->isFloatingType())
1764 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1765 else
1766 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1767 break;
1768
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001769 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001770 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1771 break;
1772
Douglas Gregorf9201e02009-02-11 23:02:49 +00001773 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001774 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001775 break;
1776
Anders Carlsson61faec12009-09-12 04:46:44 +00001777 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001778 if (SCS.IncompatibleObjC) {
1779 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001780 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001781 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001782 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001783 << From->getSourceRange();
1784 }
1785
Anders Carlsson61faec12009-09-12 04:46:44 +00001786
1787 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001788 CXXBaseSpecifierArray BasePath;
1789 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001790 return true;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001791 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001792 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001793 }
1794
1795 case ICK_Pointer_Member: {
1796 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001797 CXXBaseSpecifierArray BasePath;
1798 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath,
1799 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001800 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001801 if (CheckExceptionSpecCompatibility(From, ToType))
1802 return true;
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001803 ImpCastExprToType(From, ToType, Kind, /*isLvalue=*/false, BasePath);
Anders Carlsson61faec12009-09-12 04:46:44 +00001804 break;
1805 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001806 case ICK_Boolean_Conversion: {
1807 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1808 if (FromType->isMemberPointerType())
1809 Kind = CastExpr::CK_MemberPointerToBoolean;
1810
1811 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001812 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001813 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001814
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001815 case ICK_Derived_To_Base: {
1816 CXXBaseSpecifierArray BasePath;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001817 if (CheckDerivedToBaseConversion(From->getType(),
1818 ToType.getNonReferenceType(),
1819 From->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001820 From->getSourceRange(),
1821 &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001822 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001823 return true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001824
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001825 ImpCastExprToType(From, ToType.getNonReferenceType(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001826 CastExpr::CK_DerivedToBase,
1827 /*isLvalue=*/(From->getType()->isRecordType() &&
1828 From->isLvalue(Context) == Expr::LV_Valid),
1829 BasePath);
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001830 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001831 }
1832
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001833 default:
1834 assert(false && "Improper second standard conversion");
1835 break;
1836 }
1837
1838 switch (SCS.Third) {
1839 case ICK_Identity:
1840 // Nothing to do.
1841 break;
1842
1843 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001844 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1845 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001846 ImpCastExprToType(From, ToType.getNonReferenceType(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00001847 CastExpr::CK_NoOp, ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001848
1849 if (SCS.DeprecatedStringLiteralToCharPtr)
1850 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1851 << ToType.getNonReferenceType();
1852
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001853 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001854
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001855 default:
1856 assert(false && "Improper second standard conversion");
1857 break;
1858 }
1859
1860 return false;
1861}
1862
Sebastian Redl64b45f72009-01-05 20:52:13 +00001863Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1864 SourceLocation KWLoc,
1865 SourceLocation LParen,
1866 TypeTy *Ty,
1867 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001868 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001870 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1871 // all traits except __is_class, __is_enum and __is_union require a the type
1872 // to be complete.
1873 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001874 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001875 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001876 return ExprError();
1877 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001878
1879 // There is no point in eagerly computing the value. The traits are designed
1880 // to be used from type trait templates, so Ty will be a template parameter
1881 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001882 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1883 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001884}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001885
1886QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001887 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001888 const char *OpSpelling = isIndirect ? "->*" : ".*";
1889 // C++ 5.5p2
1890 // The binary operator .* [p3: ->*] binds its second operand, which shall
1891 // be of type "pointer to member of T" (where T is a completely-defined
1892 // class type) [...]
1893 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001894 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001895 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001896 Diag(Loc, diag::err_bad_memptr_rhs)
1897 << OpSpelling << RType << rex->getSourceRange();
1898 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001899 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001900
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001901 QualType Class(MemPtr->getClass(), 0);
1902
Sebastian Redl59fc2692010-04-10 10:14:54 +00001903 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete))
1904 return QualType();
1905
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001906 // C++ 5.5p2
1907 // [...] to its first operand, which shall be of class T or of a class of
1908 // which T is an unambiguous and accessible base class. [p3: a pointer to
1909 // such a class]
1910 QualType LType = lex->getType();
1911 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001912 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001913 LType = Ptr->getPointeeType().getNonReferenceType();
1914 else {
1915 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001916 << OpSpelling << 1 << LType
Douglas Gregor849b2432010-03-31 17:46:05 +00001917 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001918 return QualType();
1919 }
1920 }
1921
Douglas Gregora4923eb2009-11-16 21:35:15 +00001922 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00001923 // If we want to check the hierarchy, we need a complete type.
1924 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs)
1925 << OpSpelling << (int)isIndirect)) {
1926 return QualType();
1927 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001928 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001929 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001930 // FIXME: Would it be useful to print full ambiguity paths, or is that
1931 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001932 if (!IsDerivedFrom(LType, Class, Paths) ||
1933 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1934 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001935 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001936 return QualType();
1937 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001938 // Cast LHS to type of use.
1939 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1940 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001941
1942 CXXBaseSpecifierArray BasePath;
1943 BuildBasePathArray(Paths, BasePath);
1944 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue,
1945 BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001946 }
1947
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001948 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001949 // Diagnose use of pointer-to-member type which when used as
1950 // the functional cast in a pointer-to-member expression.
1951 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1952 return QualType();
1953 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001954 // C++ 5.5p2
1955 // The result is an object or a function of the type specified by the
1956 // second operand.
1957 // The cv qualifiers are the union of those in the pointer and the left side,
1958 // in accordance with 5.5p5 and 5.2.5.
1959 // FIXME: This returns a dereferenced member function pointer as a normal
1960 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001961 // calling them. There's also a GCC extension to get a function pointer to the
1962 // thing, which is another complication, because this type - unlike the type
1963 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001964 // argument.
1965 // We probably need a "MemberFunctionClosureType" or something like that.
1966 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001967 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001968 return Result;
1969}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001970
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001971/// \brief Try to convert a type to another according to C++0x 5.16p3.
1972///
1973/// This is part of the parameter validation for the ? operator. If either
1974/// value operand is a class type, the two operands are attempted to be
1975/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001976/// It returns true if the program is ill-formed and has already been diagnosed
1977/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001978static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1979 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00001980 bool &HaveConversion,
1981 QualType &ToType) {
1982 HaveConversion = false;
1983 ToType = To->getType();
1984
1985 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1986 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001987 // C++0x 5.16p3
1988 // The process for determining whether an operand expression E1 of type T1
1989 // can be converted to match an operand expression E2 of type T2 is defined
1990 // as follows:
1991 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00001992 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1993 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001994 // E1 can be converted to match E2 if E1 can be implicitly converted to
1995 // type "lvalue reference to T2", subject to the constraint that in the
1996 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001997 QualType T = Self.Context.getLValueReferenceType(ToType);
1998 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
1999
2000 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2001 if (InitSeq.isDirectReferenceBinding()) {
2002 ToType = T;
2003 HaveConversion = true;
2004 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002005 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002006
2007 if (InitSeq.isAmbiguous())
2008 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002009 }
John McCallb1bdc622010-02-25 01:37:24 +00002010
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002011 // -- If E2 is an rvalue, or if the conversion above cannot be done:
2012 // -- if E1 and E2 have class type, and the underlying class types are
2013 // the same or one is a base class of the other:
2014 QualType FTy = From->getType();
2015 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002016 const RecordType *FRec = FTy->getAs<RecordType>();
2017 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002018 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
2019 Self.IsDerivedFrom(FTy, TTy);
2020 if (FRec && TRec &&
2021 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002022 // E1 can be converted to match E2 if the class of T2 is the
2023 // same type as, or a base class of, the class of T1, and
2024 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00002025 if (FRec == TRec || FDerivedFromT) {
2026 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002027 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2028 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2029 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
2030 HaveConversion = true;
2031 return false;
2032 }
2033
2034 if (InitSeq.isAmbiguous())
2035 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2036 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002037 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002038
2039 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002040 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00002041
2042 // -- Otherwise: E1 can be converted to match E2 if E1 can be
2043 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00002044 // if E2 were converted to an rvalue (or the type it has, if E2 is
2045 // an rvalue).
2046 //
2047 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
2048 // to the array-to-pointer or function-to-pointer conversions.
2049 if (!TTy->getAs<TagType>())
2050 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002051
2052 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
2053 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
2054 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
2055 ToType = TTy;
2056 if (InitSeq.isAmbiguous())
2057 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
2058
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002059 return false;
2060}
2061
2062/// \brief Try to find a common type for two according to C++0x 5.16p5.
2063///
2064/// This is part of the parameter validation for the ? operator. If either
2065/// value operand is a class type, overload resolution is used to find a
2066/// conversion to a common type.
2067static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
2068 SourceLocation Loc) {
2069 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002070 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002071 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002072
2073 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002074 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002075 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002076 // We found a match. Perform the conversions on the arguments and move on.
2077 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002078 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002079 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002080 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002081 break;
2082 return false;
2083
Douglas Gregor20093b42009-12-09 23:02:17 +00002084 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002085 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2086 << LHS->getType() << RHS->getType()
2087 << LHS->getSourceRange() << RHS->getSourceRange();
2088 return true;
2089
Douglas Gregor20093b42009-12-09 23:02:17 +00002090 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002091 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2092 << LHS->getType() << RHS->getType()
2093 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002094 // FIXME: Print the possible common types by printing the return types of
2095 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002096 break;
2097
Douglas Gregor20093b42009-12-09 23:02:17 +00002098 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002099 assert(false && "Conditional operator has only built-in overloads");
2100 break;
2101 }
2102 return true;
2103}
2104
Sebastian Redl76458502009-04-17 16:30:52 +00002105/// \brief Perform an "extended" implicit conversion as returned by
2106/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002107static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2108 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2109 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2110 SourceLocation());
2111 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2112 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2113 Sema::MultiExprArg(Self, (void **)&E, 1));
2114 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002115 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002116
2117 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002118 return false;
2119}
2120
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002121/// \brief Check the operands of ?: under C++ semantics.
2122///
2123/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2124/// extension. In this case, LHS == Cond. (But they're not aliases.)
2125QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2126 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002127 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2128 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002129
2130 // C++0x 5.16p1
2131 // The first expression is contextually converted to bool.
2132 if (!Cond->isTypeDependent()) {
2133 if (CheckCXXBooleanCondition(Cond))
2134 return QualType();
2135 }
2136
2137 // Either of the arguments dependent?
2138 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2139 return Context.DependentTy;
2140
2141 // C++0x 5.16p2
2142 // If either the second or the third operand has type (cv) void, ...
2143 QualType LTy = LHS->getType();
2144 QualType RTy = RHS->getType();
2145 bool LVoid = LTy->isVoidType();
2146 bool RVoid = RTy->isVoidType();
2147 if (LVoid || RVoid) {
2148 // ... then the [l2r] conversions are performed on the second and third
2149 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002150 DefaultFunctionArrayLvalueConversion(LHS);
2151 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002152 LTy = LHS->getType();
2153 RTy = RHS->getType();
2154
2155 // ... and one of the following shall hold:
2156 // -- The second or the third operand (but not both) is a throw-
2157 // expression; the result is of the type of the other and is an rvalue.
2158 bool LThrow = isa<CXXThrowExpr>(LHS);
2159 bool RThrow = isa<CXXThrowExpr>(RHS);
2160 if (LThrow && !RThrow)
2161 return RTy;
2162 if (RThrow && !LThrow)
2163 return LTy;
2164
2165 // -- Both the second and third operands have type void; the result is of
2166 // type void and is an rvalue.
2167 if (LVoid && RVoid)
2168 return Context.VoidTy;
2169
2170 // Neither holds, error.
2171 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2172 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2173 << LHS->getSourceRange() << RHS->getSourceRange();
2174 return QualType();
2175 }
2176
2177 // Neither is void.
2178
2179 // C++0x 5.16p3
2180 // Otherwise, if the second and third operand have different types, and
2181 // either has (cv) class type, and attempt is made to convert each of those
2182 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002183 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002184 (LTy->isRecordType() || RTy->isRecordType())) {
2185 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2186 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002187 QualType L2RType, R2LType;
2188 bool HaveL2R, HaveR2L;
2189 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002190 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002191 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002192 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002193
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002194 // If both can be converted, [...] the program is ill-formed.
2195 if (HaveL2R && HaveR2L) {
2196 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2197 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2198 return QualType();
2199 }
2200
2201 // If exactly one conversion is possible, that conversion is applied to
2202 // the chosen operand and the converted operands are used in place of the
2203 // original operands for the remainder of this section.
2204 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002205 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002206 return QualType();
2207 LTy = LHS->getType();
2208 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002209 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002210 return QualType();
2211 RTy = RHS->getType();
2212 }
2213 }
2214
2215 // C++0x 5.16p4
2216 // If the second and third operands are lvalues and have the same type,
2217 // the result is of that type [...]
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002218 bool Same = Context.hasSameType(LTy, RTy);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002219 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2220 RHS->isLvalue(Context) == Expr::LV_Valid)
2221 return LTy;
2222
2223 // C++0x 5.16p5
2224 // Otherwise, the result is an rvalue. If the second and third operands
2225 // do not have the same type, and either has (cv) class type, ...
2226 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2227 // ... overload resolution is used to determine the conversions (if any)
2228 // to be applied to the operands. If the overload resolution fails, the
2229 // program is ill-formed.
2230 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2231 return QualType();
2232 }
2233
2234 // C++0x 5.16p6
2235 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2236 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002237 DefaultFunctionArrayLvalueConversion(LHS);
2238 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002239 LTy = LHS->getType();
2240 RTy = RHS->getType();
2241
2242 // After those conversions, one of the following shall hold:
2243 // -- The second and third operands have the same type; the result
2244 // is of that type.
2245 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2246 return LTy;
2247
2248 // -- The second and third operands have arithmetic or enumeration type;
2249 // the usual arithmetic conversions are performed to bring them to a
2250 // common type, and the result is of that type.
2251 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2252 UsualArithmeticConversions(LHS, RHS);
2253 return LHS->getType();
2254 }
2255
2256 // -- The second and third operands have pointer type, or one has pointer
2257 // type and the other is a null pointer constant; pointer conversions
2258 // and qualification conversions are performed to bring them to their
2259 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002260 // -- The second and third operands have pointer to member type, or one has
2261 // pointer to member type and the other is a null pointer constant;
2262 // pointer to member conversions and qualification conversions are
2263 // performed to bring them to a common type, whose cv-qualification
2264 // shall match the cv-qualification of either the second or the third
2265 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002266 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002267 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002268 isSFINAEContext()? 0 : &NonStandardCompositeType);
2269 if (!Composite.isNull()) {
2270 if (NonStandardCompositeType)
2271 Diag(QuestionLoc,
2272 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2273 << LTy << RTy << Composite
2274 << LHS->getSourceRange() << RHS->getSourceRange();
2275
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002276 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002277 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002278
Douglas Gregor1927b1f2010-04-01 22:47:07 +00002279 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00002280 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2281 if (!Composite.isNull())
2282 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002283
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002284 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2285 << LHS->getType() << RHS->getType()
2286 << LHS->getSourceRange() << RHS->getSourceRange();
2287 return QualType();
2288}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002289
2290/// \brief Find a merged pointer type and convert the two expressions to it.
2291///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002292/// This finds the composite pointer type (or member pointer type) for @p E1
2293/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2294/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002295/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002296///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002297/// \param Loc The location of the operator requiring these two expressions to
2298/// be converted to the composite pointer type.
2299///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002300/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2301/// a non-standard (but still sane) composite type to which both expressions
2302/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2303/// will be set true.
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002304QualType Sema::FindCompositePointerType(SourceLocation Loc,
2305 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002306 bool *NonStandardCompositeType) {
2307 if (NonStandardCompositeType)
2308 *NonStandardCompositeType = false;
2309
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002310 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2311 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002312
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002313 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2314 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002315 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002316
2317 // C++0x 5.9p2
2318 // Pointer conversions and qualification conversions are performed on
2319 // pointer operands to bring them to their composite pointer type. If
2320 // one operand is a null pointer constant, the composite pointer type is
2321 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002322 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002323 if (T2->isMemberPointerType())
2324 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2325 else
2326 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002327 return T2;
2328 }
Douglas Gregorce940492009-09-25 04:25:58 +00002329 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002330 if (T1->isMemberPointerType())
2331 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2332 else
2333 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002334 return T1;
2335 }
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Douglas Gregor20b3e992009-08-24 17:42:35 +00002337 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002338 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2339 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002340 return QualType();
2341
2342 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2343 // the other has type "pointer to cv2 T" and the composite pointer type is
2344 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2345 // Otherwise, the composite pointer type is a pointer type similar to the
2346 // type of one of the operands, with a cv-qualification signature that is
2347 // the union of the cv-qualification signatures of the operand types.
2348 // In practice, the first part here is redundant; it's subsumed by the second.
2349 // What we do here is, we build the two possible composite types, and try the
2350 // conversions in both directions. If only one works, or if the two composite
2351 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002352 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002353 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2354 QualifierVector QualifierUnion;
2355 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2356 ContainingClassVector;
2357 ContainingClassVector MemberOfClass;
2358 QualType Composite1 = Context.getCanonicalType(T1),
2359 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002360 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002361 do {
2362 const PointerType *Ptr1, *Ptr2;
2363 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2364 (Ptr2 = Composite2->getAs<PointerType>())) {
2365 Composite1 = Ptr1->getPointeeType();
2366 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002367
2368 // If we're allowed to create a non-standard composite type, keep track
2369 // of where we need to fill in additional 'const' qualifiers.
2370 if (NonStandardCompositeType &&
2371 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2372 NeedConstBefore = QualifierUnion.size();
2373
Douglas Gregor20b3e992009-08-24 17:42:35 +00002374 QualifierUnion.push_back(
2375 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2376 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2377 continue;
2378 }
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Douglas Gregor20b3e992009-08-24 17:42:35 +00002380 const MemberPointerType *MemPtr1, *MemPtr2;
2381 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2382 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2383 Composite1 = MemPtr1->getPointeeType();
2384 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002385
2386 // If we're allowed to create a non-standard composite type, keep track
2387 // of where we need to fill in additional 'const' qualifiers.
2388 if (NonStandardCompositeType &&
2389 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2390 NeedConstBefore = QualifierUnion.size();
2391
Douglas Gregor20b3e992009-08-24 17:42:35 +00002392 QualifierUnion.push_back(
2393 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2394 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2395 MemPtr2->getClass()));
2396 continue;
2397 }
Mike Stump1eb44332009-09-09 15:08:12 +00002398
Douglas Gregor20b3e992009-08-24 17:42:35 +00002399 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Douglas Gregor20b3e992009-08-24 17:42:35 +00002401 // Cannot unwrap any more types.
2402 break;
2403 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002404
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002405 if (NeedConstBefore && NonStandardCompositeType) {
2406 // Extension: Add 'const' to qualifiers that come before the first qualifier
2407 // mismatch, so that our (non-standard!) composite type meets the
2408 // requirements of C++ [conv.qual]p4 bullet 3.
2409 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2410 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2411 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2412 *NonStandardCompositeType = true;
2413 }
2414 }
2415 }
2416
Douglas Gregor20b3e992009-08-24 17:42:35 +00002417 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002418 ContainingClassVector::reverse_iterator MOC
2419 = MemberOfClass.rbegin();
2420 for (QualifierVector::reverse_iterator
2421 I = QualifierUnion.rbegin(),
2422 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002423 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002424 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002425 if (MOC->first && MOC->second) {
2426 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002427 Composite1 = Context.getMemberPointerType(
2428 Context.getQualifiedType(Composite1, Quals),
2429 MOC->first);
2430 Composite2 = Context.getMemberPointerType(
2431 Context.getQualifiedType(Composite2, Quals),
2432 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002433 } else {
2434 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002435 Composite1
2436 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2437 Composite2
2438 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002439 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002440 }
2441
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002442 // Try to convert to the first composite pointer type.
2443 InitializedEntity Entity1
2444 = InitializedEntity::InitializeTemporary(Composite1);
2445 InitializationKind Kind
2446 = InitializationKind::CreateCopy(Loc, SourceLocation());
2447 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
2448 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002450 if (E1ToC1 && E2ToC1) {
2451 // Conversion to Composite1 is viable.
2452 if (!Context.hasSameType(Composite1, Composite2)) {
2453 // Composite2 is a different type from Composite1. Check whether
2454 // Composite2 is also viable.
2455 InitializedEntity Entity2
2456 = InitializedEntity::InitializeTemporary(Composite2);
2457 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2458 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2459 if (E1ToC2 && E2ToC2) {
2460 // Both Composite1 and Composite2 are viable and are different;
2461 // this is an ambiguity.
2462 return QualType();
2463 }
2464 }
2465
2466 // Convert E1 to Composite1
2467 OwningExprResult E1Result
2468 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E1,1));
2469 if (E1Result.isInvalid())
2470 return QualType();
2471 E1 = E1Result.takeAs<Expr>();
2472
2473 // Convert E2 to Composite1
2474 OwningExprResult E2Result
2475 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,(void**)&E2,1));
2476 if (E2Result.isInvalid())
2477 return QualType();
2478 E2 = E2Result.takeAs<Expr>();
2479
2480 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002481 }
2482
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00002483 // Check whether Composite2 is viable.
2484 InitializedEntity Entity2
2485 = InitializedEntity::InitializeTemporary(Composite2);
2486 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
2487 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
2488 if (!E1ToC2 || !E2ToC2)
2489 return QualType();
2490
2491 // Convert E1 to Composite2
2492 OwningExprResult E1Result
2493 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E1, 1));
2494 if (E1Result.isInvalid())
2495 return QualType();
2496 E1 = E1Result.takeAs<Expr>();
2497
2498 // Convert E2 to Composite2
2499 OwningExprResult E2Result
2500 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, (void**)&E2, 1));
2501 if (E2Result.isInvalid())
2502 return QualType();
2503 E2 = E2Result.takeAs<Expr>();
2504
2505 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002506}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002507
Anders Carlssondef11992009-05-30 20:36:53 +00002508Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002509 if (!Context.getLangOptions().CPlusPlus)
2510 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002511
Douglas Gregor51326552009-12-24 18:51:59 +00002512 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2513
Ted Kremenek6217b802009-07-29 21:53:49 +00002514 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002515 if (!RT)
2516 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002517
John McCall86ff3082010-02-04 22:26:26 +00002518 // If this is the result of a call expression, our source might
2519 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002520 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2521 QualType Ty = CE->getCallee()->getType();
2522 if (const PointerType *PT = Ty->getAs<PointerType>())
2523 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002524 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2525 Ty = BPT->getPointeeType();
2526
John McCall183700f2009-09-21 23:43:11 +00002527 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002528 if (FTy->getResultType()->isReferenceType())
2529 return Owned(E);
2530 }
John McCall86ff3082010-02-04 22:26:26 +00002531
2532 // That should be enough to guarantee that this type is complete.
2533 // If it has a trivial destructor, we can avoid the extra copy.
2534 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2535 if (RD->hasTrivialDestructor())
2536 return Owned(E);
2537
Mike Stump1eb44332009-09-09 15:08:12 +00002538 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002539 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002540 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002541 if (CXXDestructorDecl *Destructor =
John McCallc91cc662010-04-07 00:41:46 +00002542 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002543 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00002544 CheckDestructorAccess(E->getExprLoc(), Destructor,
2545 PDiag(diag::err_access_dtor_temp)
2546 << E->getType());
2547 }
Anders Carlssondef11992009-05-30 20:36:53 +00002548 // FIXME: Add the temporary to the temporaries vector.
2549 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2550}
2551
Anders Carlsson0ece4912009-12-15 20:51:39 +00002552Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002553 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002554
John McCall323ed742010-05-06 08:58:33 +00002555 // Check any implicit conversions within the expression.
2556 CheckImplicitConversions(SubExpr);
2557
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002558 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2559 assert(ExprTemporaries.size() >= FirstTemporary);
2560 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002561 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002563 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002564 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002565 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002566 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2567 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002568
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002569 return E;
2570}
2571
Douglas Gregor90f93822009-12-22 22:17:25 +00002572Sema::OwningExprResult
2573Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2574 if (SubExpr.isInvalid())
2575 return ExprError();
2576
2577 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2578}
2579
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002580FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2581 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2582 assert(ExprTemporaries.size() >= FirstTemporary);
2583
2584 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2585 CXXTemporary **Temporaries =
2586 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2587
2588 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2589
2590 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2591 ExprTemporaries.end());
2592
2593 return E;
2594}
2595
Mike Stump1eb44332009-09-09 15:08:12 +00002596Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002597Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002598 tok::TokenKind OpKind, TypeTy *&ObjectType,
2599 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002600 // Since this might be a postfix expression, get rid of ParenListExprs.
2601 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002602
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002603 Expr *BaseExpr = (Expr*)Base.get();
2604 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002606 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002607 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002608 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002609 // If we have a pointer to a dependent type and are using the -> operator,
2610 // the object type is the type that the pointer points to. We might still
2611 // have enough information about that type to do something useful.
2612 if (OpKind == tok::arrow)
2613 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2614 BaseType = Ptr->getPointeeType();
2615
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002616 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002617 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002618 return move(Base);
2619 }
Mike Stump1eb44332009-09-09 15:08:12 +00002620
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002621 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002622 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002623 // returned, with the original second operand.
2624 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002625 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002626 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002627 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002628 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002629
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002630 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002631 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002632 BaseExpr = (Expr*)Base.get();
2633 if (BaseExpr == NULL)
2634 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002635 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002636 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002637 BaseType = BaseExpr->getType();
2638 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002639 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002640 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002641 for (unsigned i = 0; i < Locations.size(); i++)
2642 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002643 return ExprError();
2644 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002645 }
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Douglas Gregor31658df2009-11-20 19:58:21 +00002647 if (BaseType->isPointerType())
2648 BaseType = BaseType->getPointeeType();
2649 }
Mike Stump1eb44332009-09-09 15:08:12 +00002650
2651 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002652 // vector types or Objective-C interfaces. Just return early and let
2653 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002654 if (!BaseType->isRecordType()) {
2655 // C++ [basic.lookup.classref]p2:
2656 // [...] If the type of the object expression is of pointer to scalar
2657 // type, the unqualified-id is looked up in the context of the complete
2658 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002659 //
2660 // This also indicates that we should be parsing a
2661 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002662 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002663 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002664 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002665 }
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Douglas Gregor03c57052009-11-17 05:17:33 +00002667 // The object type must be complete (or dependent).
2668 if (!BaseType->isDependentType() &&
2669 RequireCompleteType(OpLoc, BaseType,
2670 PDiag(diag::err_incomplete_member_access)))
2671 return ExprError();
2672
Douglas Gregorc68afe22009-09-03 21:38:09 +00002673 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002674 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002675 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002676 // type C (or of pointer to a class type C), the unqualified-id is looked
2677 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002678 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002679 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002680}
2681
Douglas Gregor77549082010-02-24 21:29:12 +00002682Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2683 ExprArg MemExpr) {
2684 Expr *E = (Expr *) MemExpr.get();
2685 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2686 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2687 << isa<CXXPseudoDestructorExpr>(E)
Douglas Gregor849b2432010-03-31 17:46:05 +00002688 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
Douglas Gregor77549082010-02-24 21:29:12 +00002689
2690 return ActOnCallExpr(/*Scope*/ 0,
2691 move(MemExpr),
2692 /*LPLoc*/ ExpectedLParenLoc,
2693 Sema::MultiExprArg(*this, 0, 0),
2694 /*CommaLocs*/ 0,
2695 /*RPLoc*/ ExpectedLParenLoc);
2696}
Douglas Gregord4dca082010-02-24 18:44:31 +00002697
Douglas Gregorb57fb492010-02-24 22:38:50 +00002698Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2699 SourceLocation OpLoc,
2700 tok::TokenKind OpKind,
2701 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002702 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002703 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002704 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002705 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002706 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002707 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002708
2709 // C++ [expr.pseudo]p2:
2710 // The left-hand side of the dot operator shall be of scalar type. The
2711 // left-hand side of the arrow operator shall be of pointer to scalar type.
2712 // This scalar type is the object type.
2713 Expr *BaseE = (Expr *)Base.get();
2714 QualType ObjectType = BaseE->getType();
2715 if (OpKind == tok::arrow) {
2716 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2717 ObjectType = Ptr->getPointeeType();
2718 } else if (!BaseE->isTypeDependent()) {
2719 // The user wrote "p->" when she probably meant "p."; fix it.
2720 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2721 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002722 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregorb57fb492010-02-24 22:38:50 +00002723 if (isSFINAEContext())
2724 return ExprError();
2725
2726 OpKind = tok::period;
2727 }
2728 }
2729
2730 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2731 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2732 << ObjectType << BaseE->getSourceRange();
2733 return ExprError();
2734 }
2735
2736 // C++ [expr.pseudo]p2:
2737 // [...] The cv-unqualified versions of the object type and of the type
2738 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002739 if (DestructedTypeInfo) {
2740 QualType DestructedType = DestructedTypeInfo->getType();
2741 SourceLocation DestructedTypeStart
2742 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2743 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2744 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2745 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2746 << ObjectType << DestructedType << BaseE->getSourceRange()
2747 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2748
2749 // Recover by setting the destructed type to the object type.
2750 DestructedType = ObjectType;
2751 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2752 DestructedTypeStart);
2753 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2754 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002755 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002756
Douglas Gregorb57fb492010-02-24 22:38:50 +00002757 // C++ [expr.pseudo]p2:
2758 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2759 // form
2760 //
2761 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2762 //
2763 // shall designate the same scalar type.
2764 if (ScopeTypeInfo) {
2765 QualType ScopeType = ScopeTypeInfo->getType();
2766 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2767 !Context.hasSameType(ScopeType, ObjectType)) {
2768
2769 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2770 diag::err_pseudo_dtor_type_mismatch)
2771 << ObjectType << ScopeType << BaseE->getSourceRange()
2772 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2773
2774 ScopeType = QualType();
2775 ScopeTypeInfo = 0;
2776 }
2777 }
2778
2779 OwningExprResult Result
2780 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2781 Base.takeAs<Expr>(),
2782 OpKind == tok::arrow,
2783 OpLoc,
2784 (NestedNameSpecifier *) SS.getScopeRep(),
2785 SS.getRange(),
2786 ScopeTypeInfo,
2787 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002788 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002789 Destructed));
2790
Douglas Gregorb57fb492010-02-24 22:38:50 +00002791 if (HasTrailingLParen)
2792 return move(Result);
2793
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002794 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002795}
2796
2797Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2798 SourceLocation OpLoc,
2799 tok::TokenKind OpKind,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002800 CXXScopeSpec &SS,
Douglas Gregor77549082010-02-24 21:29:12 +00002801 UnqualifiedId &FirstTypeName,
2802 SourceLocation CCLoc,
2803 SourceLocation TildeLoc,
2804 UnqualifiedId &SecondTypeName,
2805 bool HasTrailingLParen) {
2806 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2807 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2808 "Invalid first type name in pseudo-destructor");
2809 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2810 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2811 "Invalid second type name in pseudo-destructor");
2812
2813 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002814
2815 // C++ [expr.pseudo]p2:
2816 // The left-hand side of the dot operator shall be of scalar type. The
2817 // left-hand side of the arrow operator shall be of pointer to scalar type.
2818 // This scalar type is the object type.
2819 QualType ObjectType = BaseE->getType();
2820 if (OpKind == tok::arrow) {
2821 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2822 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002823 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002824 // The user wrote "p->" when she probably meant "p."; fix it.
2825 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002826 << ObjectType << true
Douglas Gregor849b2432010-03-31 17:46:05 +00002827 << FixItHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002828 if (isSFINAEContext())
2829 return ExprError();
2830
2831 OpKind = tok::period;
2832 }
2833 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002834
2835 // Compute the object type that we should use for name lookup purposes. Only
2836 // record types and dependent types matter.
2837 void *ObjectTypePtrForLookup = 0;
2838 if (!SS.isSet()) {
2839 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2840 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2841 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2842 }
Douglas Gregor77549082010-02-24 21:29:12 +00002843
Douglas Gregorb57fb492010-02-24 22:38:50 +00002844 // Convert the name of the type being destructed (following the ~) into a
2845 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002846 QualType DestructedType;
2847 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002848 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002849 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2850 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2851 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002852 S, &SS, true, ObjectTypePtrForLookup);
2853 if (!T &&
2854 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2855 (!SS.isSet() && ObjectType->isDependentType()))) {
2856 // The name of the type being destroyed is a dependent name, and we
2857 // couldn't find anything useful in scope. Just store the identifier and
2858 // it's location, and we'll perform (qualified) name lookup again at
2859 // template instantiation time.
2860 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2861 SecondTypeName.StartLocation);
2862 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002863 Diag(SecondTypeName.StartLocation,
2864 diag::err_pseudo_dtor_destructor_non_type)
2865 << SecondTypeName.Identifier << ObjectType;
2866 if (isSFINAEContext())
2867 return ExprError();
2868
2869 // Recover by assuming we had the right type all along.
2870 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002871 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002872 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002873 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002874 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002875 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002876 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2877 TemplateId->getTemplateArgs(),
2878 TemplateId->NumArgs);
2879 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2880 TemplateId->TemplateNameLoc,
2881 TemplateId->LAngleLoc,
2882 TemplateArgsPtr,
2883 TemplateId->RAngleLoc);
2884 if (T.isInvalid() || !T.get()) {
2885 // Recover by assuming we had the right type all along.
2886 DestructedType = ObjectType;
2887 } else
2888 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002889 }
2890
Douglas Gregorb57fb492010-02-24 22:38:50 +00002891 // If we've performed some kind of recovery, (re-)build the type source
2892 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002893 if (!DestructedType.isNull()) {
2894 if (!DestructedTypeInfo)
2895 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002896 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002897 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2898 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002899
2900 // Convert the name of the scope type (the type prior to '::') into a type.
2901 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002902 QualType ScopeType;
2903 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2904 FirstTypeName.Identifier) {
2905 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2906 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2907 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002908 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002909 if (!T) {
2910 Diag(FirstTypeName.StartLocation,
2911 diag::err_pseudo_dtor_destructor_non_type)
2912 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002913
Douglas Gregorb57fb492010-02-24 22:38:50 +00002914 if (isSFINAEContext())
2915 return ExprError();
2916
2917 // Just drop this type. It's unnecessary anyway.
2918 ScopeType = QualType();
2919 } else
2920 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002921 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002922 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002923 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002924 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2925 TemplateId->getTemplateArgs(),
2926 TemplateId->NumArgs);
2927 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2928 TemplateId->TemplateNameLoc,
2929 TemplateId->LAngleLoc,
2930 TemplateArgsPtr,
2931 TemplateId->RAngleLoc);
2932 if (T.isInvalid() || !T.get()) {
2933 // Recover by dropping this type.
2934 ScopeType = QualType();
2935 } else
2936 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002937 }
2938 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00002939
2940 if (!ScopeType.isNull() && !ScopeTypeInfo)
2941 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2942 FirstTypeName.StartLocation);
2943
2944
Douglas Gregorb57fb492010-02-24 22:38:50 +00002945 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002946 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002947 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00002948}
2949
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002950CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
John McCall6bb80172010-03-30 21:47:33 +00002951 NamedDecl *FoundDecl,
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002952 CXXMethodDecl *Method) {
John McCall6bb80172010-03-30 21:47:33 +00002953 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0,
2954 FoundDecl, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00002955 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2956
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002957 MemberExpr *ME =
2958 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2959 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002960 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002961 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2962 CXXMemberCallExpr *CE =
2963 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2964 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002965 return CE;
2966}
2967
Anders Carlsson165a0a02009-05-17 18:41:29 +00002968Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2969 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002970 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002971 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Douglas Gregoreecf38f2010-05-06 21:39:56 +00002972 else
2973 return ExprError();
2974
Anders Carlsson165a0a02009-05-17 18:41:29 +00002975 return Owned(FullExpr);
2976}