blob: c31d93416d7ddb75c06cad0f023316400da438fd [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,
32 Scope *S, const CXXScopeSpec &SS,
33 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
264 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr();
265 }
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
Sebastian Redlc42e1182008-11-11 11:37:55 +0000276/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
Sebastian Redlf53597f2009-03-15 17:47:39 +0000277Action::OwningExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000278Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
279 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +0000280 if (!StdNamespace)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000281 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000282
Douglas Gregorf57f2072009-12-23 20:51:04 +0000283 if (isType) {
284 // C++ [expr.typeid]p4:
285 // The top-level cv-qualifiers of the lvalue expression or the type-id
286 // that is the operand of typeid are always ignored.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000287 // FIXME: Preserve type source info.
Douglas Gregorf57f2072009-12-23 20:51:04 +0000288 // FIXME: Preserve the type before we stripped the cv-qualifiers?
Douglas Gregor765ccba2009-12-23 21:06:06 +0000289 QualType T = GetTypeFromParser(TyOrExpr);
290 if (T.isNull())
291 return ExprError();
292
293 // C++ [expr.typeid]p4:
294 // If the type of the type-id is a class type or a reference to a class
295 // type, the class shall be completely-defined.
296 QualType CheckT = T;
297 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>())
298 CheckT = RefType->getPointeeType();
299
300 if (CheckT->getAs<RecordType>() &&
301 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid))
302 return ExprError();
303
304 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr();
Douglas Gregorf57f2072009-12-23 20:51:04 +0000305 }
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000306
Chris Lattner572af492008-11-20 05:51:55 +0000307 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
John McCalla24dc2e2009-11-17 02:14:36 +0000308 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
309 LookupQualifiedName(R, StdNamespace);
John McCall1bcee0a2009-12-02 08:25:40 +0000310 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>();
Chris Lattner572af492008-11-20 05:51:55 +0000311 if (!TypeInfoRecordDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000312 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000313
314 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
315
Douglas Gregorac7610d2009-06-22 20:57:11 +0000316 if (!isType) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000317 bool isUnevaluatedOperand = true;
318 Expr *E = static_cast<Expr *>(TyOrExpr);
Douglas Gregorf57f2072009-12-23 20:51:04 +0000319 if (E && !E->isTypeDependent()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000320 QualType T = E->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000321 if (const RecordType *RecordT = T->getAs<RecordType>()) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000322 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
Douglas Gregorf57f2072009-12-23 20:51:04 +0000323 // C++ [expr.typeid]p3:
John McCall86ff3082010-02-04 22:26:26 +0000324 // [...] If the type of the expression is a class type, the class
325 // shall be completely-defined.
326 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid))
327 return ExprError();
328
329 // C++ [expr.typeid]p3:
Douglas Gregorf57f2072009-12-23 20:51:04 +0000330 // When typeid is applied to an expression other than an lvalue of a
331 // polymorphic class type [...] [the] expression is an unevaluated
332 // operand. [...]
333 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid)
Douglas Gregorac7610d2009-06-22 20:57:11 +0000334 isUnevaluatedOperand = false;
Douglas Gregorf57f2072009-12-23 20:51:04 +0000335 }
336
337 // C++ [expr.typeid]p4:
338 // [...] If the type of the type-id is a reference to a possibly
339 // cv-qualified type, the result of the typeid expression refers to a
340 // std::type_info object representing the cv-unqualified referenced
341 // type.
342 if (T.hasQualifiers()) {
343 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp,
344 E->isLvalue(Context));
345 TyOrExpr = E;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000346 }
347 }
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregor2afce722009-11-26 00:44:06 +0000349 // If this is an unevaluated operand, clear out the set of
350 // declaration references we have been computing and eliminate any
351 // temporaries introduced in its computation.
Douglas Gregorac7610d2009-06-22 20:57:11 +0000352 if (isUnevaluatedOperand)
Douglas Gregor2afce722009-11-26 00:44:06 +0000353 ExprEvalContexts.back().Context = Unevaluated;
Douglas Gregorac7610d2009-06-22 20:57:11 +0000354 }
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Sebastian Redlf53597f2009-03-15 17:47:39 +0000356 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
357 TypeInfoType.withConst(),
358 SourceRange(OpLoc, RParenLoc)));
Sebastian Redlc42e1182008-11-11 11:37:55 +0000359}
360
Steve Naroff1b273c42007-09-16 14:56:35 +0000361/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000362Action::OwningExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000363Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000364 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000366 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
367 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000368}
Chris Lattner50dd2892008-02-26 00:51:44 +0000369
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000370/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
371Action::OwningExprResult
372Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
373 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
374}
375
Chris Lattner50dd2892008-02-26 00:51:44 +0000376/// ActOnCXXThrow - Parse throw expressions.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000377Action::OwningExprResult
378Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000379 Expr *Ex = E.takeAs<Expr>();
380 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
381 return ExprError();
382 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
383}
384
385/// CheckCXXThrowOperand - Validate the operand of a throw.
386bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
387 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000388 // A throw-expression initializes a temporary object, called the exception
389 // object, the type of which is determined by removing any top-level
390 // cv-qualifiers from the static type of the operand of throw and adjusting
391 // the type from "array of T" or "function returning T" to "pointer to T"
392 // or "pointer to function returning T", [...]
393 if (E->getType().hasQualifiers())
394 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp,
395 E->isLvalue(Context) == Expr::LV_Valid);
396
Sebastian Redl972041f2009-04-27 20:27:31 +0000397 DefaultFunctionArrayConversion(E);
398
399 // If the type of the exception would be an incomplete type or a pointer
400 // to an incomplete type other than (cv) void the program is ill-formed.
401 QualType Ty = E->getType();
402 int isPointer = 0;
Ted Kremenek6217b802009-07-29 21:53:49 +0000403 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000404 Ty = Ptr->getPointeeType();
405 isPointer = 1;
406 }
407 if (!isPointer || !Ty->isVoidType()) {
408 if (RequireCompleteType(ThrowLoc, Ty,
Anders Carlssond497ba72009-08-26 22:59:12 +0000409 PDiag(isPointer ? diag::err_throw_incomplete_ptr
410 : diag::err_throw_incomplete)
411 << E->getSourceRange()))
Sebastian Redl972041f2009-04-27 20:27:31 +0000412 return true;
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000413
414 // FIXME: This is just a hack to mark the copy constructor referenced.
415 // This should go away when the next FIXME is fixed.
416 const RecordType *RT = Ty->getAs<RecordType>();
417 if (!RT)
418 return false;
419
420 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
421 if (RD->hasTrivialCopyConstructor())
422 return false;
423 CXXConstructorDecl *CopyCtor = RD->getCopyConstructor(Context, 0);
424 MarkDeclarationReferenced(ThrowLoc, CopyCtor);
Sebastian Redl972041f2009-04-27 20:27:31 +0000425 }
426
427 // FIXME: Construct a temporary here.
428 return false;
Chris Lattner50dd2892008-02-26 00:51:44 +0000429}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000430
Sebastian Redlf53597f2009-03-15 17:47:39 +0000431Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000432 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
433 /// is a non-lvalue expression whose value is the address of the object for
434 /// which the function is called.
435
Sebastian Redlf53597f2009-03-15 17:47:39 +0000436 if (!isa<FunctionDecl>(CurContext))
437 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000438
439 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
440 if (MD->isInstance())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000441 return Owned(new (Context) CXXThisExpr(ThisLoc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000442 MD->getThisType(Context),
443 /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000444
Sebastian Redlf53597f2009-03-15 17:47:39 +0000445 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000446}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000447
448/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
449/// Can be interpreted either as function-style casting ("int(x)")
450/// or class type construction ("ClassType(x,y,z)")
451/// or creation of a value-initialized type ("int()").
Sebastian Redlf53597f2009-03-15 17:47:39 +0000452Action::OwningExprResult
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000453Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
454 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000455 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000456 SourceLocation *CommaLocs,
457 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000458 if (!TypeRep)
459 return ExprError();
460
John McCall9d125032010-01-15 18:39:57 +0000461 TypeSourceInfo *TInfo;
462 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
463 if (!TInfo)
464 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000465 unsigned NumExprs = exprs.size();
466 Expr **Exprs = (Expr**)exprs.get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000467 SourceLocation TyBeginLoc = TypeRange.getBegin();
468 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
469
Sebastian Redlf53597f2009-03-15 17:47:39 +0000470 if (Ty->isDependentType() ||
Douglas Gregorba498172009-03-13 21:01:28 +0000471 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000472 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000473
474 return Owned(CXXUnresolvedConstructExpr::Create(Context,
475 TypeRange.getBegin(), Ty,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000476 LParenLoc,
477 Exprs, NumExprs,
478 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000479 }
480
Anders Carlssonbb60a502009-08-27 03:53:50 +0000481 if (Ty->isArrayType())
482 return ExprError(Diag(TyBeginLoc,
483 diag::err_value_init_for_array_type) << FullRange);
484 if (!Ty->isVoidType() &&
485 RequireCompleteType(TyBeginLoc, Ty,
486 PDiag(diag::err_invalid_incomplete_type_use)
487 << FullRange))
488 return ExprError();
Fariborz Jahanianf071e9b2009-10-23 21:01:39 +0000489
Anders Carlssonbb60a502009-08-27 03:53:50 +0000490 if (RequireNonAbstractType(TyBeginLoc, Ty,
491 diag::err_allocation_of_abstract_type))
492 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000493
494
Douglas Gregor506ae412009-01-16 18:33:17 +0000495 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000496 // If the expression list is a single expression, the type conversion
497 // expression is equivalent (in definedness, and if defined in meaning) to the
498 // corresponding cast expression.
499 //
500 if (NumExprs == 1) {
Anders Carlssoncdb61972009-08-07 22:21:05 +0000501 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000502 CXXMethodDecl *Method = 0;
503 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method,
504 /*FunctionalStyle=*/true))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000505 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +0000506
507 exprs.release();
508 if (Method) {
509 OwningExprResult CastArg
510 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(),
511 Kind, Method, Owned(Exprs[0]));
512 if (CastArg.isInvalid())
513 return ExprError();
514
515 Exprs[0] = CastArg.takeAs<Expr>();
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000516 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000517
518 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000519 TInfo, TyBeginLoc, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000520 Exprs[0], RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000521 }
522
Ted Kremenek6217b802009-07-29 21:53:49 +0000523 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregor506ae412009-01-16 18:33:17 +0000524 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +0000525
Mike Stump1eb44332009-09-09 15:08:12 +0000526 if (NumExprs > 1 || !Record->hasTrivialConstructor() ||
Anders Carlssone7624a72009-08-27 05:08:22 +0000527 !Record->hasTrivialDestructor()) {
Eli Friedman6997aae2010-01-31 20:58:15 +0000528 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
529 InitializationKind Kind
530 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(),
531 LParenLoc, RParenLoc)
532 : InitializationKind::CreateValue(TypeRange.getBegin(),
533 LParenLoc, RParenLoc);
534 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
535 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
536 move(exprs));
Douglas Gregor506ae412009-01-16 18:33:17 +0000537
Eli Friedman6997aae2010-01-31 20:58:15 +0000538 // FIXME: Improve AST representation?
539 return move(Result);
Douglas Gregor506ae412009-01-16 18:33:17 +0000540 }
541
542 // Fall through to value-initialize an object of class type that
543 // doesn't have a user-declared default constructor.
544 }
545
546 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000547 // If the expression list specifies more than a single value, the type shall
548 // be a class with a suitably declared constructor.
549 //
550 if (NumExprs > 1)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000551 return ExprError(Diag(CommaLocs[0],
552 diag::err_builtin_func_cast_more_than_one_arg)
553 << FullRange);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000554
555 assert(NumExprs == 0 && "Expected 0 expressions");
Douglas Gregor506ae412009-01-16 18:33:17 +0000556 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000557 // The expression T(), where T is a simple-type-specifier for a non-array
558 // complete object type or the (possibly cv-qualified) void type, creates an
559 // rvalue of the specified type, which is value-initialized.
560 //
Sebastian Redlf53597f2009-03-15 17:47:39 +0000561 exprs.release();
562 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000563}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000564
565
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000566/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
567/// @code new (memory) int[size][4] @endcode
568/// or
569/// @code ::new Foo(23, "hello") @endcode
570/// For the interpretation of this heap of arguments, consult the base version.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000571Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000572Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000573 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000574 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000575 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000576 MultiExprArg ConstructorArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000577 SourceLocation ConstructorRParen) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000578 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000579 // If the specified type is an array, unwrap it and save the expression.
580 if (D.getNumTypeObjects() > 0 &&
581 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
582 DeclaratorChunk &Chunk = D.getTypeObject(0);
583 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000584 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
585 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000586 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000587 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
588 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000589
590 if (ParenTypeId) {
591 // Can't have dynamic array size when the type-id is in parentheses.
592 Expr *NumElts = (Expr *)Chunk.Arr.NumElts;
593 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
594 !NumElts->isIntegerConstantExpr(Context)) {
595 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst)
596 << NumElts->getSourceRange();
597 return ExprError();
598 }
599 }
600
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000601 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000602 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000603 }
604
Douglas Gregor043cad22009-09-11 00:18:58 +0000605 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000606 if (ArraySize) {
607 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000608 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
609 break;
610
611 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
612 if (Expr *NumElts = (Expr *)Array.NumElts) {
613 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
614 !NumElts->isIntegerConstantExpr(Context)) {
615 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
616 << NumElts->getSourceRange();
617 return ExprError();
618 }
619 }
620 }
621 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000622
John McCalla93c9342009-12-07 02:54:59 +0000623 //FIXME: Store TypeSourceInfo in CXXNew expression.
624 TypeSourceInfo *TInfo = 0;
625 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo);
Chris Lattnereaaebc72009-04-25 08:06:05 +0000626 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000627 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000628
Mike Stump1eb44332009-09-09 15:08:12 +0000629 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000630 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000631 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +0000632 PlacementRParen,
633 ParenTypeId,
Mike Stump1eb44332009-09-09 15:08:12 +0000634 AllocType,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000635 D.getSourceRange().getBegin(),
636 D.getSourceRange(),
637 Owned(ArraySize),
638 ConstructorLParen,
639 move(ConstructorArgs),
640 ConstructorRParen);
641}
642
Mike Stump1eb44332009-09-09 15:08:12 +0000643Sema::OwningExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +0000644Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
645 SourceLocation PlacementLParen,
646 MultiExprArg PlacementArgs,
647 SourceLocation PlacementRParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000648 bool ParenTypeId,
Douglas Gregor3433cf72009-05-21 00:00:09 +0000649 QualType AllocType,
650 SourceLocation TypeLoc,
651 SourceRange TypeRange,
652 ExprArg ArraySizeE,
653 SourceLocation ConstructorLParen,
654 MultiExprArg ConstructorArgs,
655 SourceLocation ConstructorRParen) {
656 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000657 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000658
Douglas Gregor3433cf72009-05-21 00:00:09 +0000659 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000660
661 // That every array dimension except the first is constant was already
662 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000663
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000664 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
665 // or enumeration type with a non-negative value."
Douglas Gregor3433cf72009-05-21 00:00:09 +0000666 Expr *ArraySize = (Expr *)ArraySizeE.get();
Sebastian Redl28507842009-02-26 14:39:58 +0000667 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000668 QualType SizeType = ArraySize->getType();
669 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000670 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
671 diag::err_array_size_not_integral)
672 << SizeType << ArraySize->getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000673 // Let's see if this is a constant < 0. If so, we reject it out of hand.
674 // We don't care about special rules, so we tell the machinery it's not
675 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000676 if (!ArraySize->isValueDependent()) {
677 llvm::APSInt Value;
678 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
679 if (Value < llvm::APSInt(
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000680 llvm::APInt::getNullValue(Value.getBitWidth()),
681 Value.isUnsigned()))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000682 return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
683 diag::err_typecheck_negative_array_size)
684 << ArraySize->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +0000685 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000686 }
Anders Carlssonac18b2e2009-09-23 00:37:25 +0000687
Eli Friedman73c39ab2009-10-20 08:27:19 +0000688 ImpCastExprToType(ArraySize, Context.getSizeType(),
689 CastExpr::CK_IntegralCast);
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000690 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000691
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000692 FunctionDecl *OperatorNew = 0;
693 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000694 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
695 unsigned NumPlaceArgs = PlacementArgs.size();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000696
Sebastian Redl28507842009-02-26 14:39:58 +0000697 if (!AllocType->isDependentType() &&
698 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
699 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000700 SourceRange(PlacementLParen, PlacementRParen),
701 UseGlobal, AllocType, ArraySize, PlaceArgs,
702 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +0000703 return ExprError();
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000704 llvm::SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000705 if (OperatorNew) {
706 // Add default arguments, if any.
707 const FunctionProtoType *Proto =
708 OperatorNew->getType()->getAs<FunctionProtoType>();
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +0000709 VariadicCallType CallType =
710 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000711 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew,
712 Proto, 1, PlaceArgs, NumPlaceArgs,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +0000713 AllPlaceArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +0000714 if (Invalid)
715 return ExprError();
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000716
Fariborz Jahanian498429f2009-11-19 18:39:40 +0000717 NumPlaceArgs = AllPlaceArgs.size();
718 if (NumPlaceArgs > 0)
719 PlaceArgs = &AllPlaceArgs[0];
720 }
721
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000722 bool Init = ConstructorLParen.isValid();
723 // --- Choosing a constructor ---
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000724 CXXConstructorDecl *Constructor = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +0000725 Expr **ConsArgs = (Expr**)ConstructorArgs.get();
726 unsigned NumConsArgs = ConstructorArgs.size();
Eli Friedmana8ce9ec2009-11-08 22:15:39 +0000727 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this);
728
Douglas Gregor99a2e602009-12-16 01:38:02 +0000729 if (!AllocType->isDependentType() &&
730 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
731 // C++0x [expr.new]p15:
732 // A new-expression that creates an object of type T initializes that
733 // object as follows:
734 InitializationKind Kind
735 // - If the new-initializer is omitted, the object is default-
736 // initialized (8.5); if no initialization is performed,
737 // the object has indeterminate value
738 = !Init? InitializationKind::CreateDefault(TypeLoc)
739 // - Otherwise, the new-initializer is interpreted according to the
740 // initialization rules of 8.5 for direct-initialization.
741 : InitializationKind::CreateDirect(TypeLoc,
742 ConstructorLParen,
743 ConstructorRParen);
744
Douglas Gregor99a2e602009-12-16 01:38:02 +0000745 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +0000746 = InitializedEntity::InitializeNew(StartLoc, AllocType);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000747 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000748 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
749 move(ConstructorArgs));
750 if (FullInit.isInvalid())
751 return ExprError();
752
753 // FullInit is our initializer; walk through it to determine if it's a
754 // constructor call, which CXXNewExpr handles directly.
755 if (Expr *FullInitExpr = (Expr *)FullInit.get()) {
756 if (CXXBindTemporaryExpr *Binder
757 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
758 FullInitExpr = Binder->getSubExpr();
759 if (CXXConstructExpr *Construct
760 = dyn_cast<CXXConstructExpr>(FullInitExpr)) {
761 Constructor = Construct->getConstructor();
762 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(),
763 AEnd = Construct->arg_end();
764 A != AEnd; ++A)
765 ConvertedConstructorArgs.push_back(A->Retain());
766 } else {
767 // Take the converted initializer.
768 ConvertedConstructorArgs.push_back(FullInit.release());
769 }
770 } else {
771 // No initialization required.
772 }
773
774 // Take the converted arguments and use them for the new expression.
Douglas Gregor39da0b82009-09-09 23:08:42 +0000775 NumConsArgs = ConvertedConstructorArgs.size();
776 ConsArgs = (Expr **)ConvertedConstructorArgs.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000777 }
Douglas Gregor99a2e602009-12-16 01:38:02 +0000778
Douglas Gregor6d908702010-02-26 05:06:18 +0000779 // Mark the new and delete operators as referenced.
780 if (OperatorNew)
781 MarkDeclarationReferenced(StartLoc, OperatorNew);
782 if (OperatorDelete)
783 MarkDeclarationReferenced(StartLoc, OperatorDelete);
784
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000785 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
Douglas Gregor089407b2009-10-17 21:40:42 +0000786
Sebastian Redlf53597f2009-03-15 17:47:39 +0000787 PlacementArgs.release();
788 ConstructorArgs.release();
Douglas Gregor3433cf72009-05-21 00:00:09 +0000789 ArraySizeE.release();
Ted Kremenekad7fe862010-02-11 22:51:03 +0000790 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
791 PlaceArgs, NumPlaceArgs, ParenTypeId,
792 ArraySize, Constructor, Init,
793 ConsArgs, NumConsArgs, OperatorDelete,
794 ResultType, StartLoc,
795 Init ? ConstructorRParen :
796 SourceLocation()));
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000797}
798
799/// CheckAllocatedType - Checks that a type is suitable as the allocated type
800/// in a new-expression.
801/// dimension off and stores the size expression in ArraySize.
Douglas Gregor3433cf72009-05-21 00:00:09 +0000802bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000803 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000804 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
805 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +0000806 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000807 return Diag(Loc, diag::err_bad_new_type)
808 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000809 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +0000810 return Diag(Loc, diag::err_bad_new_type)
811 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +0000812 else if (!AllocType->isDependentType() &&
Douglas Gregor3433cf72009-05-21 00:00:09 +0000813 RequireCompleteType(Loc, AllocType,
Anders Carlssonb7906612009-08-26 23:45:07 +0000814 PDiag(diag::err_new_incomplete_type)
815 << R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000816 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +0000817 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +0000818 diag::err_allocation_of_abstract_type))
819 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000820
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000821 return false;
822}
823
Douglas Gregor6d908702010-02-26 05:06:18 +0000824/// \brief Determine whether the given function is a non-placement
825/// deallocation function.
826static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
827 if (FD->isInvalidDecl())
828 return false;
829
830 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
831 return Method->isUsualDeallocationFunction();
832
833 return ((FD->getOverloadedOperator() == OO_Delete ||
834 FD->getOverloadedOperator() == OO_Array_Delete) &&
835 FD->getNumParams() == 1);
836}
837
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000838/// FindAllocationFunctions - Finds the overloads of operator new and delete
839/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000840bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
841 bool UseGlobal, QualType AllocType,
842 bool IsArray, Expr **PlaceArgs,
843 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000844 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +0000845 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000846 // --- Choosing an allocation function ---
847 // C++ 5.3.4p8 - 14 & 18
848 // 1) If UseGlobal is true, only look in the global scope. Else, also look
849 // in the scope of the allocated class.
850 // 2) If an array size is given, look for operator new[], else look for
851 // operator new.
852 // 3) The first argument is always size_t. Append the arguments from the
853 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000854
855 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
856 // We don't care about the actual value of this argument.
857 // FIXME: Should the Sema create the expression and embed it in the syntax
858 // tree? Or should the consumer just recalculate the value?
Anders Carlssond67c4c32009-08-16 20:29:29 +0000859 IntegerLiteral Size(llvm::APInt::getNullValue(
860 Context.Target.getPointerWidth(0)),
861 Context.getSizeType(),
862 SourceLocation());
863 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000864 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
865
Douglas Gregor6d908702010-02-26 05:06:18 +0000866 // C++ [expr.new]p8:
867 // If the allocated type is a non-array type, the allocation
868 // function’s name is operator new and the deallocation function’s
869 // name is operator delete. If the allocated type is an array
870 // type, the allocation function’s name is operator new[] and the
871 // deallocation function’s name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000872 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
873 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +0000874 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
875 IsArray ? OO_Array_Delete : OO_Delete);
876
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000877 if (AllocType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +0000878 CXXRecordDecl *Record
Ted Kremenek6217b802009-07-29 21:53:49 +0000879 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +0000880 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000881 AllocArgs.size(), Record, /*AllowMissing=*/true,
882 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000883 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000884 }
885 if (!OperatorNew) {
886 // Didn't find a member overload. Look for a global one.
887 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000888 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000889 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000890 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
891 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000892 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000893 }
894
Anders Carlssond9583892009-05-31 20:26:12 +0000895 // FindAllocationOverload can change the passed in arguments, so we need to
896 // copy them back.
897 if (NumPlaceArgs > 0)
898 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Douglas Gregor6d908702010-02-26 05:06:18 +0000900 // C++ [expr.new]p19:
901 //
902 // If the new-expression begins with a unary :: operator, the
903 // deallocation function’s name is looked up in the global
904 // scope. Otherwise, if the allocated type is a class type T or an
905 // array thereof, the deallocation function’s name is looked up in
906 // the scope of T. If this lookup fails to find the name, or if
907 // the allocated type is not a class type or array thereof, the
908 // deallocation function’s name is looked up in the global scope.
909 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
910 if (AllocType->isRecordType() && !UseGlobal) {
911 CXXRecordDecl *RD
912 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
913 LookupQualifiedName(FoundDelete, RD);
914 }
John McCall90c8c572010-03-18 08:19:33 +0000915 if (FoundDelete.isAmbiguous())
916 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +0000917
918 if (FoundDelete.empty()) {
919 DeclareGlobalNewDelete();
920 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
921 }
922
923 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +0000924
925 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
926
John McCall90c8c572010-03-18 08:19:33 +0000927 if (NumPlaceArgs > 0) {
Douglas Gregor6d908702010-02-26 05:06:18 +0000928 // C++ [expr.new]p20:
929 // A declaration of a placement deallocation function matches the
930 // declaration of a placement allocation function if it has the
931 // same number of parameters and, after parameter transformations
932 // (8.3.5), all parameter types except the first are
933 // identical. [...]
934 //
935 // To perform this comparison, we compute the function type that
936 // the deallocation function should have, and use that type both
937 // for template argument deduction and for comparison purposes.
938 QualType ExpectedFunctionType;
939 {
940 const FunctionProtoType *Proto
941 = OperatorNew->getType()->getAs<FunctionProtoType>();
942 llvm::SmallVector<QualType, 4> ArgTypes;
943 ArgTypes.push_back(Context.VoidPtrTy);
944 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
945 ArgTypes.push_back(Proto->getArgType(I));
946
947 ExpectedFunctionType
948 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
949 ArgTypes.size(),
950 Proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +0000951 0, false, false, 0, 0,
952 FunctionType::ExtInfo());
Douglas Gregor6d908702010-02-26 05:06:18 +0000953 }
954
955 for (LookupResult::iterator D = FoundDelete.begin(),
956 DEnd = FoundDelete.end();
957 D != DEnd; ++D) {
958 FunctionDecl *Fn = 0;
959 if (FunctionTemplateDecl *FnTmpl
960 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
961 // Perform template argument deduction to try to match the
962 // expected function type.
963 TemplateDeductionInfo Info(Context, StartLoc);
964 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
965 continue;
966 } else
967 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
968
969 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +0000970 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +0000971 }
972 } else {
973 // C++ [expr.new]p20:
974 // [...] Any non-placement deallocation function matches a
975 // non-placement allocation function. [...]
976 for (LookupResult::iterator D = FoundDelete.begin(),
977 DEnd = FoundDelete.end();
978 D != DEnd; ++D) {
979 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
980 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +0000981 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +0000982 }
983 }
984
985 // C++ [expr.new]p20:
986 // [...] If the lookup finds a single matching deallocation
987 // function, that function will be called; otherwise, no
988 // deallocation function will be called.
989 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +0000990 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +0000991
992 // C++0x [expr.new]p20:
993 // If the lookup finds the two-parameter form of a usual
994 // deallocation function (3.7.4.2) and that function, considered
995 // as a placement deallocation function, would have been
996 // selected as a match for the allocation function, the program
997 // is ill-formed.
998 if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
999 isNonPlacementDeallocationFunction(OperatorDelete)) {
1000 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
1001 << SourceRange(PlaceArgs[0]->getLocStart(),
1002 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1003 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1004 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001005 } else {
1006 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001007 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001008 }
1009 }
1010
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001011 return false;
1012}
1013
Sebastian Redl7f662392008-12-04 22:20:51 +00001014/// FindAllocationOverload - Find an fitting overload for the allocation
1015/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001016bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1017 DeclarationName Name, Expr** Args,
1018 unsigned NumArgs, DeclContext *Ctx,
Mike Stump1eb44332009-09-09 15:08:12 +00001019 bool AllowMissing, FunctionDecl *&Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001020 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1021 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001022 if (R.empty()) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001023 if (AllowMissing)
1024 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001025 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001026 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001027 }
1028
John McCall90c8c572010-03-18 08:19:33 +00001029 if (R.isAmbiguous())
1030 return true;
1031
1032 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001033
John McCall5769d612010-02-08 23:07:23 +00001034 OverloadCandidateSet Candidates(StartLoc);
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001035 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
1036 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001037 // Even member operator new/delete are implicitly treated as
1038 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001039 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001040
John McCall9aa472c2010-03-19 07:35:19 +00001041 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1042 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001043 /*ExplicitTemplateArgs=*/0, Args, NumArgs,
1044 Candidates,
1045 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001046 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001047 }
1048
John McCall9aa472c2010-03-19 07:35:19 +00001049 FunctionDecl *Fn = cast<FunctionDecl>(D);
1050 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001051 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001052 }
1053
1054 // Do the resolution.
1055 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001056 switch(BestViableFunction(Candidates, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001057 case OR_Success: {
1058 // Got one!
1059 FunctionDecl *FnDecl = Best->Function;
1060 // The first argument is size_t, and the first parameter must be size_t,
1061 // too. This is checked on declaration and can be assumed. (It can't be
1062 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001063 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001064 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1065 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001066 OwningExprResult Result
1067 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
1068 FnDecl->getParamDecl(i)),
1069 SourceLocation(),
1070 Owned(Args[i]->Retain()));
1071 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001072 return true;
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001073
1074 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001075 }
1076 Operator = FnDecl;
John McCall9aa472c2010-03-19 07:35:19 +00001077 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001078 return false;
1079 }
1080
1081 case OR_No_Viable_Function:
Sebastian Redl7f662392008-12-04 22:20:51 +00001082 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001083 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001084 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001085 return true;
1086
1087 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +00001088 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +00001089 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001090 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs);
Sebastian Redl7f662392008-12-04 22:20:51 +00001091 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001092
1093 case OR_Deleted:
1094 Diag(StartLoc, diag::err_ovl_deleted_call)
1095 << Best->Function->isDeleted()
1096 << Name << Range;
John McCallcbce6062010-01-12 07:18:19 +00001097 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001098 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001099 }
1100 assert(false && "Unreachable, bad result from BestViableFunction");
1101 return true;
1102}
1103
1104
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001105/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1106/// delete. These are:
1107/// @code
1108/// void* operator new(std::size_t) throw(std::bad_alloc);
1109/// void* operator new[](std::size_t) throw(std::bad_alloc);
1110/// void operator delete(void *) throw();
1111/// void operator delete[](void *) throw();
1112/// @endcode
1113/// Note that the placement and nothrow forms of new are *not* implicitly
1114/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001115void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001116 if (GlobalNewDeleteDeclared)
1117 return;
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001118
1119 // C++ [basic.std.dynamic]p2:
1120 // [...] The following allocation and deallocation functions (18.4) are
1121 // implicitly declared in global scope in each translation unit of a
1122 // program
1123 //
1124 // void* operator new(std::size_t) throw(std::bad_alloc);
1125 // void* operator new[](std::size_t) throw(std::bad_alloc);
1126 // void operator delete(void*) throw();
1127 // void operator delete[](void*) throw();
1128 //
1129 // These implicit declarations introduce only the function names operator
1130 // new, operator new[], operator delete, operator delete[].
1131 //
1132 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1133 // "std" or "bad_alloc" as necessary to form the exception specification.
1134 // However, we do not make these implicit declarations visible to name
1135 // lookup.
1136 if (!StdNamespace) {
1137 // The "std" namespace has not yet been defined, so build one implicitly.
1138 StdNamespace = NamespaceDecl::Create(Context,
1139 Context.getTranslationUnitDecl(),
1140 SourceLocation(),
1141 &PP.getIdentifierTable().get("std"));
1142 StdNamespace->setImplicit(true);
1143 }
1144
1145 if (!StdBadAlloc) {
1146 // The "std::bad_alloc" class has not yet been declared, so build it
1147 // implicitly.
1148 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class,
1149 StdNamespace,
1150 SourceLocation(),
1151 &PP.getIdentifierTable().get("bad_alloc"),
1152 SourceLocation(), 0);
1153 StdBadAlloc->setImplicit(true);
1154 }
1155
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001156 GlobalNewDeleteDeclared = true;
1157
1158 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1159 QualType SizeT = Context.getSizeType();
Nuno Lopesfc284482009-12-16 16:59:22 +00001160 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001161
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001162 DeclareGlobalAllocationFunction(
1163 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001164 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001165 DeclareGlobalAllocationFunction(
1166 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001167 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001168 DeclareGlobalAllocationFunction(
1169 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1170 Context.VoidTy, VoidPtr);
1171 DeclareGlobalAllocationFunction(
1172 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1173 Context.VoidTy, VoidPtr);
1174}
1175
1176/// DeclareGlobalAllocationFunction - Declares a single implicit global
1177/// allocation function if it doesn't already exist.
1178void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001179 QualType Return, QualType Argument,
1180 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001181 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1182
1183 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001184 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001185 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001186 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001187 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001188 // Only look at non-template functions, as it is the predefined,
1189 // non-templated allocation function we are trying to declare here.
1190 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1191 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001192 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001193 Func->getParamDecl(0)->getType().getUnqualifiedType());
1194 // FIXME: Do we need to check for default arguments here?
1195 if (Func->getNumParams() == 1 && InitialParamType == Argument)
1196 return;
1197 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001198 }
1199 }
1200
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001201 QualType BadAllocType;
1202 bool HasBadAllocExceptionSpec
1203 = (Name.getCXXOverloadedOperator() == OO_New ||
1204 Name.getCXXOverloadedOperator() == OO_Array_New);
1205 if (HasBadAllocExceptionSpec) {
1206 assert(StdBadAlloc && "Must have std::bad_alloc declared");
1207 BadAllocType = Context.getTypeDeclType(StdBadAlloc);
1208 }
1209
1210 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0,
1211 true, false,
1212 HasBadAllocExceptionSpec? 1 : 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00001213 &BadAllocType,
1214 FunctionType::ExtInfo());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001215 FunctionDecl *Alloc =
1216 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
John McCalla93c9342009-12-07 02:54:59 +00001217 FnType, /*TInfo=*/0, FunctionDecl::None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001218 Alloc->setImplicit();
Nuno Lopesfc284482009-12-16 16:59:22 +00001219
1220 if (AddMallocAttr)
1221 Alloc->addAttr(::new (Context) MallocAttr());
1222
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001223 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00001224 0, Argument, /*TInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001225 VarDecl::None, 0);
Douglas Gregor838db382010-02-11 01:19:42 +00001226 Alloc->setParams(&Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001227
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001228 // FIXME: Also add this declaration to the IdentifierResolver, but
1229 // make sure it is at the end of the chain to coincide with the
1230 // global scope.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001231 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001232}
1233
Anders Carlsson78f74552009-11-15 18:45:20 +00001234bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1235 DeclarationName Name,
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00001236 FunctionDecl* &Operator) {
John McCalla24dc2e2009-11-17 02:14:36 +00001237 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001238 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001239 LookupQualifiedName(Found, RD);
Anders Carlsson78f74552009-11-15 18:45:20 +00001240
John McCalla24dc2e2009-11-17 02:14:36 +00001241 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001242 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001243
1244 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1245 F != FEnd; ++F) {
1246 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F))
1247 if (Delete->isUsualDeallocationFunction()) {
1248 Operator = Delete;
1249 return false;
1250 }
1251 }
1252
1253 // We did find operator delete/operator delete[] declarations, but
1254 // none of them were suitable.
1255 if (!Found.empty()) {
1256 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1257 << Name << RD;
1258
1259 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1260 F != FEnd; ++F) {
1261 Diag((*F)->getLocation(),
1262 diag::note_delete_member_function_declared_here)
1263 << Name;
1264 }
1265
1266 return true;
1267 }
1268
1269 // Look for a global declaration.
1270 DeclareGlobalNewDelete();
1271 DeclContext *TUDecl = Context.getTranslationUnitDecl();
1272
1273 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1274 Expr* DeallocArgs[1];
1275 DeallocArgs[0] = &Null;
1276 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
1277 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false,
1278 Operator))
1279 return true;
1280
1281 assert(Operator && "Did not find a deallocation function!");
1282 return false;
1283}
1284
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001285/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1286/// @code ::delete ptr; @endcode
1287/// or
1288/// @code delete [] ptr; @endcode
Sebastian Redlf53597f2009-03-15 17:47:39 +00001289Action::OwningExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001290Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
Mike Stump1eb44332009-09-09 15:08:12 +00001291 bool ArrayForm, ExprArg Operand) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001292 // C++ [expr.delete]p1:
1293 // The operand shall have a pointer type, or a class type having a single
1294 // conversion function to a pointer type. The result has type void.
1295 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001296 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1297
Anders Carlssond67c4c32009-08-16 20:29:29 +00001298 FunctionDecl *OperatorDelete = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Sebastian Redlf53597f2009-03-15 17:47:39 +00001300 Expr *Ex = (Expr *)Operand.get();
Sebastian Redl28507842009-02-26 14:39:58 +00001301 if (!Ex->isTypeDependent()) {
1302 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001303
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001304 if (const RecordType *Record = Type->getAs<RecordType>()) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001305 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions;
Fariborz Jahanian53462782009-09-11 21:44:33 +00001306 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00001307 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001308
John McCalleec51cf2010-01-20 00:46:10 +00001309 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001310 E = Conversions->end(); I != E; ++I) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001311 // Skip over templated conversion functions; they aren't considered.
John McCallba135432009-11-21 08:51:07 +00001312 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001313 continue;
1314
John McCallba135432009-11-21 08:51:07 +00001315 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001316
1317 QualType ConvType = Conv->getConversionType().getNonReferenceType();
1318 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
1319 if (ConvPtrType->getPointeeType()->isObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001320 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001321 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001322 if (ObjectPtrConversions.size() == 1) {
1323 // We have a single conversion to a pointer-to-object type. Perform
1324 // that conversion.
1325 Operand.release();
1326 if (!PerformImplicitConversion(Ex,
1327 ObjectPtrConversions.front()->getConversionType(),
Douglas Gregor68647482009-12-16 03:45:30 +00001328 AA_Converting)) {
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001329 Operand = Owned(Ex);
1330 Type = Ex->getType();
1331 }
1332 }
1333 else if (ObjectPtrConversions.size() > 1) {
1334 Diag(StartLoc, diag::err_ambiguous_delete_operand)
1335 << Type << Ex->getSourceRange();
1336 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) {
1337 CXXConversionDecl *Conv = ObjectPtrConversions[i];
John McCallb1622a12010-01-06 09:43:14 +00001338 NoteOverloadCandidate(Conv);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00001339 }
1340 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001341 }
Sebastian Redl28507842009-02-26 14:39:58 +00001342 }
1343
Sebastian Redlf53597f2009-03-15 17:47:39 +00001344 if (!Type->isPointerType())
1345 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1346 << Type << Ex->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00001347
Ted Kremenek6217b802009-07-29 21:53:49 +00001348 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001349 if (Pointee->isFunctionType() || Pointee->isVoidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001350 return ExprError(Diag(StartLoc, diag::err_delete_operand)
1351 << Type << Ex->getSourceRange());
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001352 else if (!Pointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001353 RequireCompleteType(StartLoc, Pointee,
Anders Carlssonb7906612009-08-26 23:45:07 +00001354 PDiag(diag::warn_delete_incomplete)
1355 << Ex->getSourceRange()))
Douglas Gregor8dcb29d2009-03-24 20:13:58 +00001356 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00001357
Douglas Gregor1070c9f2009-09-29 21:38:53 +00001358 // C++ [expr.delete]p2:
1359 // [Note: a pointer to a const type can be the operand of a
1360 // delete-expression; it is not necessary to cast away the constness
1361 // (5.2.11) of the pointer expression before it is used as the operand
1362 // of the delete-expression. ]
1363 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy),
1364 CastExpr::CK_NoOp);
1365
1366 // Update the operand.
1367 Operand.take();
1368 Operand = ExprArg(*this, Ex);
1369
Anders Carlssond67c4c32009-08-16 20:29:29 +00001370 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1371 ArrayForm ? OO_Array_Delete : OO_Delete);
1372
Anders Carlsson78f74552009-11-15 18:45:20 +00001373 if (const RecordType *RT = Pointee->getAs<RecordType>()) {
1374 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1375
1376 if (!UseGlobal &&
1377 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001378 return ExprError();
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00001379
Anders Carlsson78f74552009-11-15 18:45:20 +00001380 if (!RD->hasTrivialDestructor())
1381 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context))
Mike Stump1eb44332009-09-09 15:08:12 +00001382 MarkDeclarationReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00001383 const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssond67c4c32009-08-16 20:29:29 +00001384 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001385
Anders Carlssond67c4c32009-08-16 20:29:29 +00001386 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00001387 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00001388 DeclareGlobalNewDelete();
1389 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001390 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Douglas Gregor90916562009-09-29 18:16:17 +00001391 &Ex, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001392 OperatorDelete))
1393 return ExprError();
1394 }
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Sebastian Redl28507842009-02-26 14:39:58 +00001396 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001397 }
1398
Sebastian Redlf53597f2009-03-15 17:47:39 +00001399 Operand.release();
1400 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
Anders Carlssond67c4c32009-08-16 20:29:29 +00001401 OperatorDelete, Ex, StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001402}
1403
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001404/// \brief Check the use of the given variable as a C++ condition in an if,
1405/// while, do-while, or switch statement.
1406Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) {
1407 QualType T = ConditionVar->getType();
1408
1409 // C++ [stmt.select]p2:
1410 // The declarator shall not specify a function or an array.
1411 if (T->isFunctionType())
1412 return ExprError(Diag(ConditionVar->getLocation(),
1413 diag::err_invalid_use_of_function_type)
1414 << ConditionVar->getSourceRange());
1415 else if (T->isArrayType())
1416 return ExprError(Diag(ConditionVar->getLocation(),
1417 diag::err_invalid_use_of_array_type)
1418 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00001419
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00001420 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar,
1421 ConditionVar->getLocation(),
1422 ConditionVar->getType().getNonReferenceType()));
1423}
1424
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001425/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
1426bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
1427 // C++ 6.4p4:
1428 // The value of a condition that is an initialized declaration in a statement
1429 // other than a switch statement is the value of the declared variable
1430 // implicitly converted to type bool. If that conversion is ill-formed, the
1431 // program is ill-formed.
1432 // The value of a condition that is an expression is the value of the
1433 // expression, implicitly converted to bool.
1434 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001435 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00001436}
Douglas Gregor77a52232008-09-12 00:47:35 +00001437
1438/// Helper function to determine whether this is the (deprecated) C++
1439/// conversion from a string literal to a pointer to non-const char or
1440/// non-const wchar_t (for narrow and wide string literals,
1441/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00001442bool
Douglas Gregor77a52232008-09-12 00:47:35 +00001443Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
1444 // Look inside the implicit cast, if it exists.
1445 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
1446 From = Cast->getSubExpr();
1447
1448 // A string literal (2.13.4) that is not a wide string literal can
1449 // be converted to an rvalue of type "pointer to char"; a wide
1450 // string literal can be converted to an rvalue of type "pointer
1451 // to wchar_t" (C++ 4.2p2).
1452 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
Ted Kremenek6217b802009-07-29 21:53:49 +00001453 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001454 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00001455 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00001456 // This conversion is considered only when there is an
1457 // explicit appropriate pointer target type (C++ 4.2p2).
John McCall0953e762009-09-24 19:53:00 +00001458 if (!ToPtrType->getPointeeType().hasQualifiers() &&
Douglas Gregor77a52232008-09-12 00:47:35 +00001459 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
1460 (!StrLit->isWide() &&
1461 (ToPointeeType->getKind() == BuiltinType::Char_U ||
1462 ToPointeeType->getKind() == BuiltinType::Char_S))))
1463 return true;
1464 }
1465
1466 return false;
1467}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001468
1469/// PerformImplicitConversion - Perform an implicit conversion of the
1470/// expression From to the type ToType. Returns true if there was an
1471/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +00001472/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001473/// performing, used in the error message. If @p AllowExplicit,
Sebastian Redle2b68332009-04-12 17:16:29 +00001474/// explicit user-defined conversions are permitted. @p Elidable should be true
1475/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
1476/// resolution works differently in that case.
1477bool
Douglas Gregor45920e82008-12-19 17:40:08 +00001478Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001479 AssignmentAction Action, bool AllowExplicit,
Mike Stump1eb44332009-09-09 15:08:12 +00001480 bool Elidable) {
Sebastian Redle2b68332009-04-12 17:16:29 +00001481 ImplicitConversionSequence ICS;
Douglas Gregor68647482009-12-16 03:45:30 +00001482 return PerformImplicitConversion(From, ToType, Action, AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001483 Elidable, ICS);
1484}
1485
1486bool
1487Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001488 AssignmentAction Action, bool AllowExplicit,
Fariborz Jahanian51bebc82009-09-23 20:55:32 +00001489 bool Elidable,
1490 ImplicitConversionSequence& ICS) {
John McCallb1bdc622010-02-25 01:37:24 +00001491 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redle2b68332009-04-12 17:16:29 +00001492 if (Elidable && getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00001493 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001494 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00001495 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001496 /*ForceRValue=*/true,
1497 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001498 }
John McCall1d318332010-01-12 00:44:57 +00001499 if (ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001500 ICS = TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00001501 /*SuppressUserConversions=*/false,
1502 AllowExplicit,
Anders Carlsson08972922009-08-28 15:33:32 +00001503 /*ForceRValue=*/false,
1504 /*InOverloadResolution=*/false);
Sebastian Redle2b68332009-04-12 17:16:29 +00001505 }
Douglas Gregor68647482009-12-16 03:45:30 +00001506 return PerformImplicitConversion(From, ToType, ICS, Action);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001507}
1508
1509/// PerformImplicitConversion - Perform an implicit conversion of the
1510/// expression From to the type ToType using the pre-computed implicit
1511/// conversion sequence ICS. Returns true if there was an error, false
1512/// otherwise. The expression From is replaced with the converted
Douglas Gregor68647482009-12-16 03:45:30 +00001513/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001514/// used in the error message.
1515bool
1516Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
1517 const ImplicitConversionSequence &ICS,
Douglas Gregor68647482009-12-16 03:45:30 +00001518 AssignmentAction Action, bool IgnoreBaseAccess) {
John McCall1d318332010-01-12 00:44:57 +00001519 switch (ICS.getKind()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001520 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor68647482009-12-16 03:45:30 +00001521 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001522 IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001523 return true;
1524 break;
1525
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001526 case ImplicitConversionSequence::UserDefinedConversion: {
1527
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001528 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
1529 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001530 QualType BeforeToType;
1531 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00001532 CastKind = CastExpr::CK_UserDefinedConversion;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001533
1534 // If the user-defined conversion is specified by a conversion function,
1535 // the initial standard conversion sequence converts the source type to
1536 // the implicit object parameter of the conversion function.
1537 BeforeToType = Context.getTagDeclType(Conv->getParent());
1538 } else if (const CXXConstructorDecl *Ctor =
1539 dyn_cast<CXXConstructorDecl>(FD)) {
Anders Carlsson0aebc812009-09-09 21:33:21 +00001540 CastKind = CastExpr::CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001541 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00001542 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001543 // If the user-defined conversion is specified by a constructor, the
1544 // initial standard conversion sequence converts the source type to the
1545 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00001546 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
1547 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001548 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00001549 else
1550 assert(0 && "Unknown conversion function kind!");
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001551 // Whatch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00001552 if (!ICS.UserDefined.EllipsisConversion) {
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001553 if (PerformImplicitConversion(From, BeforeToType,
Douglas Gregor68647482009-12-16 03:45:30 +00001554 ICS.UserDefined.Before, AA_Converting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001555 IgnoreBaseAccess))
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001556 return true;
1557 }
Anders Carlssonf6c213a2009-09-15 06:28:28 +00001558
Anders Carlsson0aebc812009-09-09 21:33:21 +00001559 OwningExprResult CastArg
1560 = BuildCXXCastArgument(From->getLocStart(),
1561 ToType.getNonReferenceType(),
1562 CastKind, cast<CXXMethodDecl>(FD),
1563 Owned(From));
1564
1565 if (CastArg.isInvalid())
1566 return true;
Eli Friedmand8889622009-11-27 04:41:50 +00001567
1568 From = CastArg.takeAs<Expr>();
1569
Eli Friedmand8889622009-11-27 04:41:50 +00001570 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
Douglas Gregor68647482009-12-16 03:45:30 +00001571 AA_Converting, IgnoreBaseAccess);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001572 }
John McCall1d318332010-01-12 00:44:57 +00001573
1574 case ImplicitConversionSequence::AmbiguousConversion:
1575 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(),
1576 PDiag(diag::err_typecheck_ambiguous_condition)
1577 << From->getSourceRange());
1578 return true;
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00001579
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001580 case ImplicitConversionSequence::EllipsisConversion:
1581 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001582 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001583
1584 case ImplicitConversionSequence::BadConversion:
1585 return true;
1586 }
1587
1588 // Everything went well.
1589 return false;
1590}
1591
1592/// PerformImplicitConversion - Perform an implicit conversion of the
1593/// expression From to the type ToType by following the standard
1594/// conversion sequence SCS. Returns true if there was an error, false
1595/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00001596/// expression. Flavor is the context in which we're performing this
1597/// conversion, for use in error messages.
Mike Stump1eb44332009-09-09 15:08:12 +00001598bool
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001599Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00001600 const StandardConversionSequence& SCS,
Douglas Gregor68647482009-12-16 03:45:30 +00001601 AssignmentAction Action, bool IgnoreBaseAccess) {
Mike Stump390b4cc2009-05-16 07:39:55 +00001602 // Overall FIXME: we are recomputing too many types here and doing far too
1603 // much extra work. What this means is that we need to keep track of more
1604 // information that is computed when we try the implicit conversion initially,
1605 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001606 QualType FromType = From->getType();
1607
Douglas Gregor225c41e2008-11-03 19:09:14 +00001608 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00001609 // FIXME: When can ToType be a reference type?
1610 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00001611 if (SCS.Second == ICK_Derived_To_Base) {
1612 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
1613 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
1614 MultiExprArg(*this, (void **)&From, 1),
1615 /*FIXME:ConstructLoc*/SourceLocation(),
1616 ConstructorArgs))
1617 return true;
1618 OwningExprResult FromResult =
1619 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1620 ToType, SCS.CopyConstructor,
1621 move_arg(ConstructorArgs));
1622 if (FromResult.isInvalid())
1623 return true;
1624 From = FromResult.takeAs<Expr>();
1625 return false;
1626 }
Mike Stump1eb44332009-09-09 15:08:12 +00001627 OwningExprResult FromResult =
1628 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
1629 ToType, SCS.CopyConstructor,
Anders Carlssonf47511a2009-09-07 22:23:31 +00001630 MultiExprArg(*this, (void**)&From, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001632 if (FromResult.isInvalid())
1633 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Anders Carlssonda3f4e22009-08-25 05:12:04 +00001635 From = FromResult.takeAs<Expr>();
Douglas Gregor225c41e2008-11-03 19:09:14 +00001636 return false;
1637 }
1638
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001639 // Perform the first implicit conversion.
1640 switch (SCS.First) {
1641 case ICK_Identity:
1642 case ICK_Lvalue_To_Rvalue:
1643 // Nothing to do.
1644 break;
1645
1646 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001647 FromType = Context.getArrayDecayedType(FromType);
Anders Carlsson82495762009-08-08 21:04:35 +00001648 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001649 break;
1650
1651 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +00001652 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001653 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
1654 if (!Fn)
1655 return true;
1656
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001657 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
1658 return true;
1659
Anders Carlsson96ad5332009-10-21 17:16:23 +00001660 From = FixOverloadedFunctionReference(From, Fn);
Douglas Gregor904eed32008-11-10 20:40:00 +00001661 FromType = From->getType();
Anders Carlsson96ad5332009-10-21 17:16:23 +00001662
Sebastian Redl759986e2009-10-17 20:50:27 +00001663 // If there's already an address-of operator in the expression, we have
1664 // the right type already, and the code below would just introduce an
1665 // invalid additional pointer level.
Anders Carlsson96ad5332009-10-21 17:16:23 +00001666 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType())
Sebastian Redl759986e2009-10-17 20:50:27 +00001667 break;
Douglas Gregor904eed32008-11-10 20:40:00 +00001668 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001669 FromType = Context.getPointerType(FromType);
Anders Carlssonb633c4e2009-09-01 20:37:18 +00001670 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001671 break;
1672
1673 default:
1674 assert(false && "Improper first standard conversion");
1675 break;
1676 }
1677
1678 // Perform the second implicit conversion
1679 switch (SCS.Second) {
1680 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001681 // If both sides are functions (or pointers/references to them), there could
1682 // be incompatible exception declarations.
1683 if (CheckExceptionSpecCompatibility(From, ToType))
1684 return true;
1685 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001686 break;
1687
Douglas Gregor43c79c22009-12-09 00:47:37 +00001688 case ICK_NoReturn_Adjustment:
1689 // If both sides are functions (or pointers/references to them), there could
1690 // be incompatible exception declarations.
1691 if (CheckExceptionSpecCompatibility(From, ToType))
1692 return true;
1693
1694 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false),
1695 CastExpr::CK_NoOp);
1696 break;
1697
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001698 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001699 case ICK_Integral_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001700 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast);
1701 break;
1702
1703 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001704 case ICK_Floating_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001705 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast);
1706 break;
1707
1708 case ICK_Complex_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001709 case ICK_Complex_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001710 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1711 break;
1712
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001713 case ICK_Floating_Integral:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001714 if (ToType->isFloatingType())
1715 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating);
1716 else
1717 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral);
1718 break;
1719
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001720 case ICK_Complex_Real:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001721 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown);
1722 break;
1723
Douglas Gregorf9201e02009-02-11 23:02:49 +00001724 case ICK_Compatible_Conversion:
Eli Friedman73c39ab2009-10-20 08:27:19 +00001725 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001726 break;
1727
Anders Carlsson61faec12009-09-12 04:46:44 +00001728 case ICK_Pointer_Conversion: {
Douglas Gregor45920e82008-12-19 17:40:08 +00001729 if (SCS.IncompatibleObjC) {
1730 // Diagnose incompatible Objective-C conversions
Mike Stump1eb44332009-09-09 15:08:12 +00001731 Diag(From->getSourceRange().getBegin(),
Douglas Gregor45920e82008-12-19 17:40:08 +00001732 diag::ext_typecheck_convert_incompatible_pointer)
Douglas Gregor68647482009-12-16 03:45:30 +00001733 << From->getType() << ToType << Action
Douglas Gregor45920e82008-12-19 17:40:08 +00001734 << From->getSourceRange();
1735 }
1736
Anders Carlsson61faec12009-09-12 04:46:44 +00001737
1738 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001739 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001740 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001741 ImpCastExprToType(From, ToType, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001742 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00001743 }
1744
1745 case ICK_Pointer_Member: {
1746 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001747 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001748 return true;
Sebastian Redl2c7588f2009-10-10 12:04:10 +00001749 if (CheckExceptionSpecCompatibility(From, ToType))
1750 return true;
Anders Carlsson61faec12009-09-12 04:46:44 +00001751 ImpCastExprToType(From, ToType, Kind);
1752 break;
1753 }
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001754 case ICK_Boolean_Conversion: {
1755 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
1756 if (FromType->isMemberPointerType())
1757 Kind = CastExpr::CK_MemberPointerToBoolean;
1758
1759 ImpCastExprToType(From, Context.BoolTy, Kind);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001760 break;
Anders Carlssonbc0e0782009-11-23 20:04:44 +00001761 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001762
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001763 case ICK_Derived_To_Base:
1764 if (CheckDerivedToBaseConversion(From->getType(),
1765 ToType.getNonReferenceType(),
1766 From->getLocStart(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001767 From->getSourceRange(),
1768 IgnoreBaseAccess))
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001769 return true;
1770 ImpCastExprToType(From, ToType.getNonReferenceType(),
1771 CastExpr::CK_DerivedToBase);
1772 break;
1773
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001774 default:
1775 assert(false && "Improper second standard conversion");
1776 break;
1777 }
1778
1779 switch (SCS.Third) {
1780 case ICK_Identity:
1781 // Nothing to do.
1782 break;
1783
1784 case ICK_Qualification:
Mike Stump390b4cc2009-05-16 07:39:55 +00001785 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1786 // references.
Mike Stump1eb44332009-09-09 15:08:12 +00001787 ImpCastExprToType(From, ToType.getNonReferenceType(),
Eli Friedman73c39ab2009-10-20 08:27:19 +00001788 CastExpr::CK_NoOp,
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001789 ToType->isLValueReferenceType());
Douglas Gregora9bff302010-02-28 18:30:25 +00001790
1791 if (SCS.DeprecatedStringLiteralToCharPtr)
1792 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
1793 << ToType.getNonReferenceType();
1794
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001795 break;
Douglas Gregorb7a86f52009-11-06 01:02:41 +00001796
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001797 default:
1798 assert(false && "Improper second standard conversion");
1799 break;
1800 }
1801
1802 return false;
1803}
1804
Sebastian Redl64b45f72009-01-05 20:52:13 +00001805Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1806 SourceLocation KWLoc,
1807 SourceLocation LParen,
1808 TypeTy *Ty,
1809 SourceLocation RParen) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001810 QualType T = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001812 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1813 // all traits except __is_class, __is_enum and __is_union require a the type
1814 // to be complete.
1815 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
Mike Stump1eb44332009-09-09 15:08:12 +00001816 if (RequireCompleteType(KWLoc, T,
Anders Carlssond497ba72009-08-26 22:59:12 +00001817 diag::err_incomplete_type_used_in_type_trait_expr))
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001818 return ExprError();
1819 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00001820
1821 // There is no point in eagerly computing the value. The traits are designed
1822 // to be used from type trait templates, so Ty will be a template parameter
1823 // 99% of the time.
Anders Carlsson3292d5c2009-07-07 19:06:02 +00001824 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1825 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00001826}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001827
1828QualType Sema::CheckPointerToMemberOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00001829 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001830 const char *OpSpelling = isIndirect ? "->*" : ".*";
1831 // C++ 5.5p2
1832 // The binary operator .* [p3: ->*] binds its second operand, which shall
1833 // be of type "pointer to member of T" (where T is a completely-defined
1834 // class type) [...]
1835 QualType RType = rex->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001836 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00001837 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001838 Diag(Loc, diag::err_bad_memptr_rhs)
1839 << OpSpelling << RType << rex->getSourceRange();
1840 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00001841 }
Douglas Gregore7450f52009-03-24 19:52:54 +00001842
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001843 QualType Class(MemPtr->getClass(), 0);
1844
1845 // C++ 5.5p2
1846 // [...] to its first operand, which shall be of class T or of a class of
1847 // which T is an unambiguous and accessible base class. [p3: a pointer to
1848 // such a class]
1849 QualType LType = lex->getType();
1850 if (isIndirect) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001851 if (const PointerType *Ptr = LType->getAs<PointerType>())
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001852 LType = Ptr->getPointeeType().getNonReferenceType();
1853 else {
1854 Diag(Loc, diag::err_bad_memptr_lhs)
Fariborz Jahanianef78ac62009-10-26 20:45:27 +00001855 << OpSpelling << 1 << LType
1856 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001857 return QualType();
1858 }
1859 }
1860
Douglas Gregora4923eb2009-11-16 21:35:15 +00001861 if (!Context.hasSameUnqualifiedType(Class, LType)) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001862 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1863 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00001864 // FIXME: Would it be useful to print full ambiguity paths, or is that
1865 // overkill?
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001866 if (!IsDerivedFrom(LType, Class, Paths) ||
1867 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1868 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Eli Friedman3005efe2010-01-16 00:00:48 +00001869 << (int)isIndirect << lex->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001870 return QualType();
1871 }
Eli Friedman3005efe2010-01-16 00:00:48 +00001872 // Cast LHS to type of use.
1873 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
1874 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid;
1875 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001876 }
1877
Fariborz Jahanian19d70732009-11-18 22:16:17 +00001878 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00001879 // Diagnose use of pointer-to-member type which when used as
1880 // the functional cast in a pointer-to-member expression.
1881 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
1882 return QualType();
1883 }
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001884 // C++ 5.5p2
1885 // The result is an object or a function of the type specified by the
1886 // second operand.
1887 // The cv qualifiers are the union of those in the pointer and the left side,
1888 // in accordance with 5.5p5 and 5.2.5.
1889 // FIXME: This returns a dereferenced member function pointer as a normal
1890 // function type. However, the only operation valid on such functions is
Mike Stump390b4cc2009-05-16 07:39:55 +00001891 // calling them. There's also a GCC extension to get a function pointer to the
1892 // thing, which is another complication, because this type - unlike the type
1893 // that is the result of this expression - takes the class as the first
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001894 // argument.
1895 // We probably need a "MemberFunctionClosureType" or something like that.
1896 QualType Result = MemPtr->getPointeeType();
John McCall0953e762009-09-24 19:53:00 +00001897 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers());
Sebastian Redl7c8bd602009-02-07 20:10:22 +00001898 return Result;
1899}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001900
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001901/// \brief Try to convert a type to another according to C++0x 5.16p3.
1902///
1903/// This is part of the parameter validation for the ? operator. If either
1904/// value operand is a class type, the two operands are attempted to be
1905/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001906/// It returns true if the program is ill-formed and has already been diagnosed
1907/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001908static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1909 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00001910 bool &HaveConversion,
1911 QualType &ToType) {
1912 HaveConversion = false;
1913 ToType = To->getType();
1914
1915 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
1916 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001917 // C++0x 5.16p3
1918 // The process for determining whether an operand expression E1 of type T1
1919 // can be converted to match an operand expression E2 of type T2 is defined
1920 // as follows:
1921 // -- If E2 is an lvalue:
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00001922 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid);
1923 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001924 // E1 can be converted to match E2 if E1 can be implicitly converted to
1925 // type "lvalue reference to T2", subject to the constraint that in the
1926 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00001927 QualType T = Self.Context.getLValueReferenceType(ToType);
1928 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
1929
1930 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1931 if (InitSeq.isDirectReferenceBinding()) {
1932 ToType = T;
1933 HaveConversion = true;
1934 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001935 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00001936
1937 if (InitSeq.isAmbiguous())
1938 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001939 }
John McCallb1bdc622010-02-25 01:37:24 +00001940
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001941 // -- If E2 is an rvalue, or if the conversion above cannot be done:
1942 // -- if E1 and E2 have class type, and the underlying class types are
1943 // the same or one is a base class of the other:
1944 QualType FTy = From->getType();
1945 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001946 const RecordType *FRec = FTy->getAs<RecordType>();
1947 const RecordType *TRec = TTy->getAs<RecordType>();
Douglas Gregorb70cf442010-03-26 20:14:36 +00001948 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
1949 Self.IsDerivedFrom(FTy, TTy);
1950 if (FRec && TRec &&
1951 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001952 // E1 can be converted to match E2 if the class of T2 is the
1953 // same type as, or a base class of, the class of T1, and
1954 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00001955 if (FRec == TRec || FDerivedFromT) {
1956 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00001957 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1958 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1959 if (InitSeq.getKind() != InitializationSequence::FailedSequence) {
1960 HaveConversion = true;
1961 return false;
1962 }
1963
1964 if (InitSeq.isAmbiguous())
1965 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1966 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001967 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00001968
1969 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001970 }
Douglas Gregorb70cf442010-03-26 20:14:36 +00001971
1972 // -- Otherwise: E1 can be converted to match E2 if E1 can be
1973 // implicitly converted to the type that expression E2 would have
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00001974 // if E2 were converted to an rvalue (or the type it has, if E2 is
1975 // an rvalue).
1976 //
1977 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
1978 // to the array-to-pointer or function-to-pointer conversions.
1979 if (!TTy->getAs<TagType>())
1980 TTy = TTy.getUnqualifiedType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00001981
1982 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
1983 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
1984 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence;
1985 ToType = TTy;
1986 if (InitSeq.isAmbiguous())
1987 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
1988
Sebastian Redl3201f6b2009-04-16 17:51:27 +00001989 return false;
1990}
1991
1992/// \brief Try to find a common type for two according to C++0x 5.16p5.
1993///
1994/// This is part of the parameter validation for the ? operator. If either
1995/// value operand is a class type, overload resolution is used to find a
1996/// conversion to a common type.
1997static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1998 SourceLocation Loc) {
1999 Expr *Args[2] = { LHS, RHS };
John McCall5769d612010-02-08 23:07:23 +00002000 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002001 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002002
2003 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002004 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002005 case OR_Success:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002006 // We found a match. Perform the conversions on the arguments and move on.
2007 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00002008 Best->Conversions[0], Sema::AA_Converting) ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002009 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00002010 Best->Conversions[1], Sema::AA_Converting))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002011 break;
2012 return false;
2013
Douglas Gregor20093b42009-12-09 23:02:17 +00002014 case OR_No_Viable_Function:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002015 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
2016 << LHS->getType() << RHS->getType()
2017 << LHS->getSourceRange() << RHS->getSourceRange();
2018 return true;
2019
Douglas Gregor20093b42009-12-09 23:02:17 +00002020 case OR_Ambiguous:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002021 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
2022 << LHS->getType() << RHS->getType()
2023 << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00002024 // FIXME: Print the possible common types by printing the return types of
2025 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002026 break;
2027
Douglas Gregor20093b42009-12-09 23:02:17 +00002028 case OR_Deleted:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002029 assert(false && "Conditional operator has only built-in overloads");
2030 break;
2031 }
2032 return true;
2033}
2034
Sebastian Redl76458502009-04-17 16:30:52 +00002035/// \brief Perform an "extended" implicit conversion as returned by
2036/// TryClassUnification.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002037static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) {
2038 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
2039 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(),
2040 SourceLocation());
2041 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1);
2042 Sema::OwningExprResult Result = InitSeq.Perform(Self, Entity, Kind,
2043 Sema::MultiExprArg(Self, (void **)&E, 1));
2044 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00002045 return true;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002046
2047 E = Result.takeAs<Expr>();
Sebastian Redl76458502009-04-17 16:30:52 +00002048 return false;
2049}
2050
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002051/// \brief Check the operands of ?: under C++ semantics.
2052///
2053/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
2054/// extension. In this case, LHS == Cond. (But they're not aliases.)
2055QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2056 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00002057 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
2058 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002059
2060 // C++0x 5.16p1
2061 // The first expression is contextually converted to bool.
2062 if (!Cond->isTypeDependent()) {
2063 if (CheckCXXBooleanCondition(Cond))
2064 return QualType();
2065 }
2066
2067 // Either of the arguments dependent?
2068 if (LHS->isTypeDependent() || RHS->isTypeDependent())
2069 return Context.DependentTy;
2070
John McCalld1b47bf2010-03-11 19:43:18 +00002071 CheckSignCompare(LHS, RHS, QuestionLoc);
John McCallb13c87f2009-11-05 09:23:39 +00002072
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002073 // C++0x 5.16p2
2074 // If either the second or the third operand has type (cv) void, ...
2075 QualType LTy = LHS->getType();
2076 QualType RTy = RHS->getType();
2077 bool LVoid = LTy->isVoidType();
2078 bool RVoid = RTy->isVoidType();
2079 if (LVoid || RVoid) {
2080 // ... then the [l2r] conversions are performed on the second and third
2081 // operands ...
Douglas Gregora873dfc2010-02-03 00:27:59 +00002082 DefaultFunctionArrayLvalueConversion(LHS);
2083 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002084 LTy = LHS->getType();
2085 RTy = RHS->getType();
2086
2087 // ... and one of the following shall hold:
2088 // -- The second or the third operand (but not both) is a throw-
2089 // expression; the result is of the type of the other and is an rvalue.
2090 bool LThrow = isa<CXXThrowExpr>(LHS);
2091 bool RThrow = isa<CXXThrowExpr>(RHS);
2092 if (LThrow && !RThrow)
2093 return RTy;
2094 if (RThrow && !LThrow)
2095 return LTy;
2096
2097 // -- Both the second and third operands have type void; the result is of
2098 // type void and is an rvalue.
2099 if (LVoid && RVoid)
2100 return Context.VoidTy;
2101
2102 // Neither holds, error.
2103 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
2104 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
2105 << LHS->getSourceRange() << RHS->getSourceRange();
2106 return QualType();
2107 }
2108
2109 // Neither is void.
2110
2111 // C++0x 5.16p3
2112 // Otherwise, if the second and third operand have different types, and
2113 // either has (cv) class type, and attempt is made to convert each of those
2114 // operands to the other.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002115 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002116 (LTy->isRecordType() || RTy->isRecordType())) {
2117 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
2118 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00002119 QualType L2RType, R2LType;
2120 bool HaveL2R, HaveR2L;
2121 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002122 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002123 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002124 return QualType();
Douglas Gregorb70cf442010-03-26 20:14:36 +00002125
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002126 // If both can be converted, [...] the program is ill-formed.
2127 if (HaveL2R && HaveR2L) {
2128 Diag(QuestionLoc, diag::err_conditional_ambiguous)
2129 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
2130 return QualType();
2131 }
2132
2133 // If exactly one conversion is possible, that conversion is applied to
2134 // the chosen operand and the converted operands are used in place of the
2135 // original operands for the remainder of this section.
2136 if (HaveL2R) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002137 if (ConvertForConditional(*this, LHS, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002138 return QualType();
2139 LTy = LHS->getType();
2140 } else if (HaveR2L) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00002141 if (ConvertForConditional(*this, RHS, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002142 return QualType();
2143 RTy = RHS->getType();
2144 }
2145 }
2146
2147 // C++0x 5.16p4
2148 // If the second and third operands are lvalues and have the same type,
2149 // the result is of that type [...]
2150 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
2151 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
2152 RHS->isLvalue(Context) == Expr::LV_Valid)
2153 return LTy;
2154
2155 // C++0x 5.16p5
2156 // Otherwise, the result is an rvalue. If the second and third operands
2157 // do not have the same type, and either has (cv) class type, ...
2158 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
2159 // ... overload resolution is used to determine the conversions (if any)
2160 // to be applied to the operands. If the overload resolution fails, the
2161 // program is ill-formed.
2162 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
2163 return QualType();
2164 }
2165
2166 // C++0x 5.16p6
2167 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
2168 // conversions are performed on the second and third operands.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002169 DefaultFunctionArrayLvalueConversion(LHS);
2170 DefaultFunctionArrayLvalueConversion(RHS);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002171 LTy = LHS->getType();
2172 RTy = RHS->getType();
2173
2174 // After those conversions, one of the following shall hold:
2175 // -- The second and third operands have the same type; the result
2176 // is of that type.
2177 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
2178 return LTy;
2179
2180 // -- The second and third operands have arithmetic or enumeration type;
2181 // the usual arithmetic conversions are performed to bring them to a
2182 // common type, and the result is of that type.
2183 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
2184 UsualArithmeticConversions(LHS, RHS);
2185 return LHS->getType();
2186 }
2187
2188 // -- The second and third operands have pointer type, or one has pointer
2189 // type and the other is a null pointer constant; pointer conversions
2190 // and qualification conversions are performed to bring them to their
2191 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00002192 // -- The second and third operands have pointer to member type, or one has
2193 // pointer to member type and the other is a null pointer constant;
2194 // pointer to member conversions and qualification conversions are
2195 // performed to bring them to a common type, whose cv-qualification
2196 // shall match the cv-qualification of either the second or the third
2197 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002198 bool NonStandardCompositeType = false;
2199 QualType Composite = FindCompositePointerType(LHS, RHS,
2200 isSFINAEContext()? 0 : &NonStandardCompositeType);
2201 if (!Composite.isNull()) {
2202 if (NonStandardCompositeType)
2203 Diag(QuestionLoc,
2204 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
2205 << LTy << RTy << Composite
2206 << LHS->getSourceRange() << RHS->getSourceRange();
2207
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002208 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002209 }
Fariborz Jahanian55016362009-12-10 20:46:08 +00002210
2211 // Similarly, attempt to find composite type of twp objective-c pointers.
2212 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
2213 if (!Composite.isNull())
2214 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002215
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002216 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2217 << LHS->getType() << RHS->getType()
2218 << LHS->getSourceRange() << RHS->getSourceRange();
2219 return QualType();
2220}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002221
2222/// \brief Find a merged pointer type and convert the two expressions to it.
2223///
Douglas Gregor20b3e992009-08-24 17:42:35 +00002224/// This finds the composite pointer type (or member pointer type) for @p E1
2225/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
2226/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002227/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002228///
2229/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
2230/// a non-standard (but still sane) composite type to which both expressions
2231/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
2232/// will be set true.
2233QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2,
2234 bool *NonStandardCompositeType) {
2235 if (NonStandardCompositeType)
2236 *NonStandardCompositeType = false;
2237
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002238 assert(getLangOptions().CPlusPlus && "This function assumes C++");
2239 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00002241 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
2242 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00002243 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002244
2245 // C++0x 5.9p2
2246 // Pointer conversions and qualification conversions are performed on
2247 // pointer operands to bring them to their composite pointer type. If
2248 // one operand is a null pointer constant, the composite pointer type is
2249 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00002250 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002251 if (T2->isMemberPointerType())
2252 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer);
2253 else
2254 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002255 return T2;
2256 }
Douglas Gregorce940492009-09-25 04:25:58 +00002257 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00002258 if (T1->isMemberPointerType())
2259 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer);
2260 else
2261 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer);
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002262 return T1;
2263 }
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Douglas Gregor20b3e992009-08-24 17:42:35 +00002265 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002266 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
2267 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002268 return QualType();
2269
2270 // Otherwise, of one of the operands has type "pointer to cv1 void," then
2271 // the other has type "pointer to cv2 T" and the composite pointer type is
2272 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
2273 // Otherwise, the composite pointer type is a pointer type similar to the
2274 // type of one of the operands, with a cv-qualification signature that is
2275 // the union of the cv-qualification signatures of the operand types.
2276 // In practice, the first part here is redundant; it's subsumed by the second.
2277 // What we do here is, we build the two possible composite types, and try the
2278 // conversions in both directions. If only one works, or if the two composite
2279 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00002280 // FIXME: extended qualifiers?
Sebastian Redla439e6f2009-11-16 21:03:45 +00002281 typedef llvm::SmallVector<unsigned, 4> QualifierVector;
2282 QualifierVector QualifierUnion;
2283 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4>
2284 ContainingClassVector;
2285 ContainingClassVector MemberOfClass;
2286 QualType Composite1 = Context.getCanonicalType(T1),
2287 Composite2 = Context.getCanonicalType(T2);
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002288 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00002289 do {
2290 const PointerType *Ptr1, *Ptr2;
2291 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
2292 (Ptr2 = Composite2->getAs<PointerType>())) {
2293 Composite1 = Ptr1->getPointeeType();
2294 Composite2 = Ptr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002295
2296 // If we're allowed to create a non-standard composite type, keep track
2297 // of where we need to fill in additional 'const' qualifiers.
2298 if (NonStandardCompositeType &&
2299 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2300 NeedConstBefore = QualifierUnion.size();
2301
Douglas Gregor20b3e992009-08-24 17:42:35 +00002302 QualifierUnion.push_back(
2303 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2304 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
2305 continue;
2306 }
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Douglas Gregor20b3e992009-08-24 17:42:35 +00002308 const MemberPointerType *MemPtr1, *MemPtr2;
2309 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
2310 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
2311 Composite1 = MemPtr1->getPointeeType();
2312 Composite2 = MemPtr2->getPointeeType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002313
2314 // If we're allowed to create a non-standard composite type, keep track
2315 // of where we need to fill in additional 'const' qualifiers.
2316 if (NonStandardCompositeType &&
2317 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
2318 NeedConstBefore = QualifierUnion.size();
2319
Douglas Gregor20b3e992009-08-24 17:42:35 +00002320 QualifierUnion.push_back(
2321 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
2322 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
2323 MemPtr2->getClass()));
2324 continue;
2325 }
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Douglas Gregor20b3e992009-08-24 17:42:35 +00002327 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Douglas Gregor20b3e992009-08-24 17:42:35 +00002329 // Cannot unwrap any more types.
2330 break;
2331 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00002332
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00002333 if (NeedConstBefore && NonStandardCompositeType) {
2334 // Extension: Add 'const' to qualifiers that come before the first qualifier
2335 // mismatch, so that our (non-standard!) composite type meets the
2336 // requirements of C++ [conv.qual]p4 bullet 3.
2337 for (unsigned I = 0; I != NeedConstBefore; ++I) {
2338 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
2339 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
2340 *NonStandardCompositeType = true;
2341 }
2342 }
2343 }
2344
Douglas Gregor20b3e992009-08-24 17:42:35 +00002345 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00002346 ContainingClassVector::reverse_iterator MOC
2347 = MemberOfClass.rbegin();
2348 for (QualifierVector::reverse_iterator
2349 I = QualifierUnion.rbegin(),
2350 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00002351 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00002352 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002353 if (MOC->first && MOC->second) {
2354 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00002355 Composite1 = Context.getMemberPointerType(
2356 Context.getQualifiedType(Composite1, Quals),
2357 MOC->first);
2358 Composite2 = Context.getMemberPointerType(
2359 Context.getQualifiedType(Composite2, Quals),
2360 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00002361 } else {
2362 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00002363 Composite1
2364 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
2365 Composite2
2366 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00002367 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002368 }
2369
Mike Stump1eb44332009-09-09 15:08:12 +00002370 ImplicitConversionSequence E1ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002371 TryImplicitConversion(E1, Composite1,
2372 /*SuppressUserConversions=*/false,
2373 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002374 /*ForceRValue=*/false,
2375 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002376 ImplicitConversionSequence E2ToC1 =
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002377 TryImplicitConversion(E2, Composite1,
2378 /*SuppressUserConversions=*/false,
2379 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002380 /*ForceRValue=*/false,
2381 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002382
John McCallb1bdc622010-02-25 01:37:24 +00002383 bool ToC2Viable = false;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002384 ImplicitConversionSequence E1ToC2, E2ToC2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002385 if (Context.getCanonicalType(Composite1) !=
2386 Context.getCanonicalType(Composite2)) {
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002387 E1ToC2 = TryImplicitConversion(E1, Composite2,
2388 /*SuppressUserConversions=*/false,
2389 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002390 /*ForceRValue=*/false,
2391 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002392 E2ToC2 = TryImplicitConversion(E2, Composite2,
2393 /*SuppressUserConversions=*/false,
2394 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002395 /*ForceRValue=*/false,
2396 /*InOverloadResolution=*/false);
John McCallb1bdc622010-02-25 01:37:24 +00002397 ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002398 }
2399
John McCall1d318332010-01-12 00:44:57 +00002400 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002401 if (ToC1Viable && !ToC2Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002402 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) &&
2403 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002404 return Composite1;
2405 }
2406 if (ToC2Viable && !ToC1Viable) {
Douglas Gregor68647482009-12-16 03:45:30 +00002407 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) &&
2408 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00002409 return Composite2;
2410 }
2411 return QualType();
2412}
Anders Carlsson165a0a02009-05-17 18:41:29 +00002413
Anders Carlssondef11992009-05-30 20:36:53 +00002414Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002415 if (!Context.getLangOptions().CPlusPlus)
2416 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002417
Douglas Gregor51326552009-12-24 18:51:59 +00002418 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
2419
Ted Kremenek6217b802009-07-29 21:53:49 +00002420 const RecordType *RT = E->getType()->getAs<RecordType>();
Anders Carlssondef11992009-05-30 20:36:53 +00002421 if (!RT)
2422 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002423
John McCall86ff3082010-02-04 22:26:26 +00002424 // If this is the result of a call expression, our source might
2425 // actually be a reference, in which case we shouldn't bind.
Anders Carlsson283e4d52009-09-14 01:30:44 +00002426 if (CallExpr *CE = dyn_cast<CallExpr>(E)) {
2427 QualType Ty = CE->getCallee()->getType();
2428 if (const PointerType *PT = Ty->getAs<PointerType>())
2429 Ty = PT->getPointeeType();
Fariborz Jahanianb372b0f2010-02-18 20:31:02 +00002430 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>())
2431 Ty = BPT->getPointeeType();
2432
John McCall183700f2009-09-21 23:43:11 +00002433 const FunctionType *FTy = Ty->getAs<FunctionType>();
Anders Carlsson283e4d52009-09-14 01:30:44 +00002434 if (FTy->getResultType()->isReferenceType())
2435 return Owned(E);
2436 }
John McCall86ff3082010-02-04 22:26:26 +00002437
2438 // That should be enough to guarantee that this type is complete.
2439 // If it has a trivial destructor, we can avoid the extra copy.
2440 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2441 if (RD->hasTrivialDestructor())
2442 return Owned(E);
2443
Mike Stump1eb44332009-09-09 15:08:12 +00002444 CXXTemporary *Temp = CXXTemporary::Create(Context,
Anders Carlssondef11992009-05-30 20:36:53 +00002445 RD->getDestructor(Context));
Anders Carlsson860306e2009-05-30 21:21:49 +00002446 ExprTemporaries.push_back(Temp);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002447 if (CXXDestructorDecl *Destructor =
2448 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
2449 MarkDeclarationReferenced(E->getExprLoc(), Destructor);
Anders Carlssondef11992009-05-30 20:36:53 +00002450 // FIXME: Add the temporary to the temporaries vector.
2451 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
2452}
2453
Anders Carlsson0ece4912009-12-15 20:51:39 +00002454Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) {
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002455 assert(SubExpr && "sub expression can't be null!");
Mike Stump1eb44332009-09-09 15:08:12 +00002456
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002457 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2458 assert(ExprTemporaries.size() >= FirstTemporary);
2459 if (ExprTemporaries.size() == FirstTemporary)
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002460 return SubExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002462 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002463 &ExprTemporaries[FirstTemporary],
Anders Carlsson0ece4912009-12-15 20:51:39 +00002464 ExprTemporaries.size() - FirstTemporary);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +00002465 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2466 ExprTemporaries.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002467
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002468 return E;
2469}
2470
Douglas Gregor90f93822009-12-22 22:17:25 +00002471Sema::OwningExprResult
2472Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) {
2473 if (SubExpr.isInvalid())
2474 return ExprError();
2475
2476 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>()));
2477}
2478
Anders Carlsson5ee56e92009-12-16 02:09:40 +00002479FullExpr Sema::CreateFullExpr(Expr *SubExpr) {
2480 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries;
2481 assert(ExprTemporaries.size() >= FirstTemporary);
2482
2483 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary;
2484 CXXTemporary **Temporaries =
2485 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary];
2486
2487 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries);
2488
2489 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
2490 ExprTemporaries.end());
2491
2492 return E;
2493}
2494
Mike Stump1eb44332009-09-09 15:08:12 +00002495Sema::OwningExprResult
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002496Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00002497 tok::TokenKind OpKind, TypeTy *&ObjectType,
2498 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002499 // Since this might be a postfix expression, get rid of ParenListExprs.
2500 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002502 Expr *BaseExpr = (Expr*)Base.get();
2503 assert(BaseExpr && "no record expansion");
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002505 QualType BaseType = BaseExpr->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00002506 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002507 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00002508 // If we have a pointer to a dependent type and are using the -> operator,
2509 // the object type is the type that the pointer points to. We might still
2510 // have enough information about that type to do something useful.
2511 if (OpKind == tok::arrow)
2512 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2513 BaseType = Ptr->getPointeeType();
2514
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002515 ObjectType = BaseType.getAsOpaquePtr();
Douglas Gregord4dca082010-02-24 18:44:31 +00002516 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002517 return move(Base);
2518 }
Mike Stump1eb44332009-09-09 15:08:12 +00002519
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002520 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00002521 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002522 // returned, with the original second operand.
2523 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00002524 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00002525 llvm::SmallPtrSet<CanQualType,8> CTypes;
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002526 llvm::SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00002527 CTypes.insert(Context.getCanonicalType(BaseType));
John McCallc4e83212009-09-30 01:01:30 +00002528
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002529 while (BaseType->isRecordType()) {
Anders Carlsson15ea3782009-10-13 22:43:21 +00002530 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002531 BaseExpr = (Expr*)Base.get();
2532 if (BaseExpr == NULL)
2533 return ExprError();
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002534 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr))
Anders Carlssonde699e52009-10-13 22:55:59 +00002535 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallc4e83212009-09-30 01:01:30 +00002536 BaseType = BaseExpr->getType();
2537 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00002538 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002539 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00002540 for (unsigned i = 0; i < Locations.size(); i++)
2541 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00002542 return ExprError();
2543 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002544 }
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Douglas Gregor31658df2009-11-20 19:58:21 +00002546 if (BaseType->isPointerType())
2547 BaseType = BaseType->getPointeeType();
2548 }
Mike Stump1eb44332009-09-09 15:08:12 +00002549
2550 // We could end up with various non-record types here, such as extended
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002551 // vector types or Objective-C interfaces. Just return early and let
2552 // ActOnMemberReferenceExpr do the work.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002553 if (!BaseType->isRecordType()) {
2554 // C++ [basic.lookup.classref]p2:
2555 // [...] If the type of the object expression is of pointer to scalar
2556 // type, the unqualified-id is looked up in the context of the complete
2557 // postfix-expression.
Douglas Gregord4dca082010-02-24 18:44:31 +00002558 //
2559 // This also indicates that we should be parsing a
2560 // pseudo-destructor-name.
Douglas Gregorc68afe22009-09-03 21:38:09 +00002561 ObjectType = 0;
Douglas Gregord4dca082010-02-24 18:44:31 +00002562 MayBePseudoDestructor = true;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002563 return move(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00002564 }
Mike Stump1eb44332009-09-09 15:08:12 +00002565
Douglas Gregor03c57052009-11-17 05:17:33 +00002566 // The object type must be complete (or dependent).
2567 if (!BaseType->isDependentType() &&
2568 RequireCompleteType(OpLoc, BaseType,
2569 PDiag(diag::err_incomplete_member_access)))
2570 return ExprError();
2571
Douglas Gregorc68afe22009-09-03 21:38:09 +00002572 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002573 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00002574 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00002575 // type C (or of pointer to a class type C), the unqualified-id is looked
2576 // up in the scope of class C. [...]
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002577 ObjectType = BaseType.getAsOpaquePtr();
Mike Stump1eb44332009-09-09 15:08:12 +00002578 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00002579}
2580
Douglas Gregor77549082010-02-24 21:29:12 +00002581Sema::OwningExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
2582 ExprArg MemExpr) {
2583 Expr *E = (Expr *) MemExpr.get();
2584 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
2585 Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2586 << isa<CXXPseudoDestructorExpr>(E)
2587 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2588
2589 return ActOnCallExpr(/*Scope*/ 0,
2590 move(MemExpr),
2591 /*LPLoc*/ ExpectedLParenLoc,
2592 Sema::MultiExprArg(*this, 0, 0),
2593 /*CommaLocs*/ 0,
2594 /*RPLoc*/ ExpectedLParenLoc);
2595}
Douglas Gregord4dca082010-02-24 18:44:31 +00002596
Douglas Gregorb57fb492010-02-24 22:38:50 +00002597Sema::OwningExprResult Sema::BuildPseudoDestructorExpr(ExprArg Base,
2598 SourceLocation OpLoc,
2599 tok::TokenKind OpKind,
2600 const CXXScopeSpec &SS,
Douglas Gregor26d4ac92010-02-24 23:40:28 +00002601 TypeSourceInfo *ScopeTypeInfo,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002602 SourceLocation CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002603 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002604 PseudoDestructorTypeStorage Destructed,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002605 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002606 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
Douglas Gregorb57fb492010-02-24 22:38:50 +00002607
2608 // C++ [expr.pseudo]p2:
2609 // The left-hand side of the dot operator shall be of scalar type. The
2610 // left-hand side of the arrow operator shall be of pointer to scalar type.
2611 // This scalar type is the object type.
2612 Expr *BaseE = (Expr *)Base.get();
2613 QualType ObjectType = BaseE->getType();
2614 if (OpKind == tok::arrow) {
2615 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2616 ObjectType = Ptr->getPointeeType();
2617 } else if (!BaseE->isTypeDependent()) {
2618 // The user wrote "p->" when she probably meant "p."; fix it.
2619 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2620 << ObjectType << true
2621 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2622 if (isSFINAEContext())
2623 return ExprError();
2624
2625 OpKind = tok::period;
2626 }
2627 }
2628
2629 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
2630 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2631 << ObjectType << BaseE->getSourceRange();
2632 return ExprError();
2633 }
2634
2635 // C++ [expr.pseudo]p2:
2636 // [...] The cv-unqualified versions of the object type and of the type
2637 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002638 if (DestructedTypeInfo) {
2639 QualType DestructedType = DestructedTypeInfo->getType();
2640 SourceLocation DestructedTypeStart
2641 = DestructedTypeInfo->getTypeLoc().getSourceRange().getBegin();
2642 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() &&
2643 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
2644 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
2645 << ObjectType << DestructedType << BaseE->getSourceRange()
2646 << DestructedTypeInfo->getTypeLoc().getSourceRange();
2647
2648 // Recover by setting the destructed type to the object type.
2649 DestructedType = ObjectType;
2650 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
2651 DestructedTypeStart);
2652 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2653 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002654 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002655
Douglas Gregorb57fb492010-02-24 22:38:50 +00002656 // C++ [expr.pseudo]p2:
2657 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
2658 // form
2659 //
2660 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
2661 //
2662 // shall designate the same scalar type.
2663 if (ScopeTypeInfo) {
2664 QualType ScopeType = ScopeTypeInfo->getType();
2665 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
2666 !Context.hasSameType(ScopeType, ObjectType)) {
2667
2668 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
2669 diag::err_pseudo_dtor_type_mismatch)
2670 << ObjectType << ScopeType << BaseE->getSourceRange()
2671 << ScopeTypeInfo->getTypeLoc().getSourceRange();
2672
2673 ScopeType = QualType();
2674 ScopeTypeInfo = 0;
2675 }
2676 }
2677
2678 OwningExprResult Result
2679 = Owned(new (Context) CXXPseudoDestructorExpr(Context,
2680 Base.takeAs<Expr>(),
2681 OpKind == tok::arrow,
2682 OpLoc,
2683 (NestedNameSpecifier *) SS.getScopeRep(),
2684 SS.getRange(),
2685 ScopeTypeInfo,
2686 CCLoc,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002687 TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002688 Destructed));
2689
Douglas Gregorb57fb492010-02-24 22:38:50 +00002690 if (HasTrailingLParen)
2691 return move(Result);
2692
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002693 return DiagnoseDtorReference(Destructed.getLocation(), move(Result));
Douglas Gregor77549082010-02-24 21:29:12 +00002694}
2695
2696Sema::OwningExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, ExprArg Base,
2697 SourceLocation OpLoc,
2698 tok::TokenKind OpKind,
2699 const CXXScopeSpec &SS,
2700 UnqualifiedId &FirstTypeName,
2701 SourceLocation CCLoc,
2702 SourceLocation TildeLoc,
2703 UnqualifiedId &SecondTypeName,
2704 bool HasTrailingLParen) {
2705 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2706 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2707 "Invalid first type name in pseudo-destructor");
2708 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2709 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
2710 "Invalid second type name in pseudo-destructor");
2711
2712 Expr *BaseE = (Expr *)Base.get();
Douglas Gregor77549082010-02-24 21:29:12 +00002713
2714 // C++ [expr.pseudo]p2:
2715 // The left-hand side of the dot operator shall be of scalar type. The
2716 // left-hand side of the arrow operator shall be of pointer to scalar type.
2717 // This scalar type is the object type.
2718 QualType ObjectType = BaseE->getType();
2719 if (OpKind == tok::arrow) {
2720 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
2721 ObjectType = Ptr->getPointeeType();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002722 } else if (!ObjectType->isDependentType()) {
Douglas Gregor77549082010-02-24 21:29:12 +00002723 // The user wrote "p->" when she probably meant "p."; fix it.
2724 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002725 << ObjectType << true
2726 << CodeModificationHint::CreateReplacement(OpLoc, ".");
Douglas Gregor77549082010-02-24 21:29:12 +00002727 if (isSFINAEContext())
2728 return ExprError();
2729
2730 OpKind = tok::period;
2731 }
2732 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002733
2734 // Compute the object type that we should use for name lookup purposes. Only
2735 // record types and dependent types matter.
2736 void *ObjectTypePtrForLookup = 0;
2737 if (!SS.isSet()) {
2738 ObjectTypePtrForLookup = (void *)ObjectType->getAs<RecordType>();
2739 if (!ObjectTypePtrForLookup && ObjectType->isDependentType())
2740 ObjectTypePtrForLookup = Context.DependentTy.getAsOpaquePtr();
2741 }
Douglas Gregor77549082010-02-24 21:29:12 +00002742
Douglas Gregorb57fb492010-02-24 22:38:50 +00002743 // Convert the name of the type being destructed (following the ~) into a
2744 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00002745 QualType DestructedType;
2746 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002747 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00002748 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2749 TypeTy *T = getTypeName(*SecondTypeName.Identifier,
2750 SecondTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002751 S, &SS, true, ObjectTypePtrForLookup);
2752 if (!T &&
2753 ((SS.isSet() && !computeDeclContext(SS, false)) ||
2754 (!SS.isSet() && ObjectType->isDependentType()))) {
2755 // The name of the type being destroyed is a dependent name, and we
2756 // couldn't find anything useful in scope. Just store the identifier and
2757 // it's location, and we'll perform (qualified) name lookup again at
2758 // template instantiation time.
2759 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
2760 SecondTypeName.StartLocation);
2761 } else if (!T) {
Douglas Gregor77549082010-02-24 21:29:12 +00002762 Diag(SecondTypeName.StartLocation,
2763 diag::err_pseudo_dtor_destructor_non_type)
2764 << SecondTypeName.Identifier << ObjectType;
2765 if (isSFINAEContext())
2766 return ExprError();
2767
2768 // Recover by assuming we had the right type all along.
2769 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002770 } else
Douglas Gregor77549082010-02-24 21:29:12 +00002771 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002772 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002773 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002774 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002775 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2776 TemplateId->getTemplateArgs(),
2777 TemplateId->NumArgs);
2778 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2779 TemplateId->TemplateNameLoc,
2780 TemplateId->LAngleLoc,
2781 TemplateArgsPtr,
2782 TemplateId->RAngleLoc);
2783 if (T.isInvalid() || !T.get()) {
2784 // Recover by assuming we had the right type all along.
2785 DestructedType = ObjectType;
2786 } else
2787 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002788 }
2789
Douglas Gregorb57fb492010-02-24 22:38:50 +00002790 // If we've performed some kind of recovery, (re-)build the type source
2791 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002792 if (!DestructedType.isNull()) {
2793 if (!DestructedTypeInfo)
2794 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00002795 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002796 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
2797 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00002798
2799 // Convert the name of the scope type (the type prior to '::') into a type.
2800 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00002801 QualType ScopeType;
2802 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
2803 FirstTypeName.Identifier) {
2804 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
2805 TypeTy *T = getTypeName(*FirstTypeName.Identifier,
2806 FirstTypeName.StartLocation,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002807 S, &SS, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00002808 if (!T) {
2809 Diag(FirstTypeName.StartLocation,
2810 diag::err_pseudo_dtor_destructor_non_type)
2811 << FirstTypeName.Identifier << ObjectType;
Douglas Gregor77549082010-02-24 21:29:12 +00002812
Douglas Gregorb57fb492010-02-24 22:38:50 +00002813 if (isSFINAEContext())
2814 return ExprError();
2815
2816 // Just drop this type. It's unnecessary anyway.
2817 ScopeType = QualType();
2818 } else
2819 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002820 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00002821 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00002822 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00002823 ASTTemplateArgsPtr TemplateArgsPtr(*this,
2824 TemplateId->getTemplateArgs(),
2825 TemplateId->NumArgs);
2826 TypeResult T = ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
2827 TemplateId->TemplateNameLoc,
2828 TemplateId->LAngleLoc,
2829 TemplateArgsPtr,
2830 TemplateId->RAngleLoc);
2831 if (T.isInvalid() || !T.get()) {
2832 // Recover by dropping this type.
2833 ScopeType = QualType();
2834 } else
2835 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00002836 }
2837 }
Douglas Gregorb4a418f2010-02-24 23:02:30 +00002838
2839 if (!ScopeType.isNull() && !ScopeTypeInfo)
2840 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
2841 FirstTypeName.StartLocation);
2842
2843
Douglas Gregorb57fb492010-02-24 22:38:50 +00002844 return BuildPseudoDestructorExpr(move(Base), OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00002845 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00002846 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00002847}
2848
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002849CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp,
2850 CXXMethodDecl *Method) {
Douglas Gregor5fccd362010-03-03 23:55:11 +00002851 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, Method))
Eli Friedman772fffa2009-12-09 04:53:56 +00002852 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?");
2853
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002854 MemberExpr *ME =
2855 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method,
2856 SourceLocation(), Method->getType());
Eli Friedman772fffa2009-12-09 04:53:56 +00002857 QualType ResultType = Method->getResultType().getNonReferenceType();
Douglas Gregor7edfb692009-11-23 12:27:39 +00002858 MarkDeclarationReferenced(Exp->getLocStart(), Method);
2859 CXXMemberCallExpr *CE =
2860 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType,
2861 Exp->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002862 return CE;
2863}
2864
Anders Carlsson0aebc812009-09-09 21:33:21 +00002865Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc,
2866 QualType Ty,
2867 CastExpr::CastKind Kind,
2868 CXXMethodDecl *Method,
2869 ExprArg Arg) {
2870 Expr *From = Arg.takeAs<Expr>();
2871
2872 switch (Kind) {
2873 default: assert(0 && "Unhandled cast kind!");
2874 case CastExpr::CK_ConstructorConversion: {
Douglas Gregor39da0b82009-09-09 23:08:42 +00002875 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this);
2876
2877 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method),
2878 MultiExprArg(*this, (void **)&From, 1),
2879 CastLoc, ConstructorArgs))
2880 return ExprError();
Anders Carlsson4fa26842009-10-18 21:20:14 +00002881
2882 OwningExprResult Result =
2883 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2884 move_arg(ConstructorArgs));
2885 if (Result.isInvalid())
2886 return ExprError();
2887
2888 return MaybeBindToTemporary(Result.takeAs<Expr>());
Anders Carlsson0aebc812009-09-09 21:33:21 +00002889 }
2890
2891 case CastExpr::CK_UserDefinedConversion: {
Anders Carlssonaac6e3a2009-09-15 07:42:44 +00002892 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
Eli Friedman772fffa2009-12-09 04:53:56 +00002893
Fariborz Jahanianb7400232009-09-28 23:23:40 +00002894 // Create an implicit call expr that calls it.
2895 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method);
Anders Carlsson4fa26842009-10-18 21:20:14 +00002896 return MaybeBindToTemporary(CE);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002897 }
Anders Carlsson0aebc812009-09-09 21:33:21 +00002898 }
2899}
2900
Anders Carlsson165a0a02009-05-17 18:41:29 +00002901Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
2902 Expr *FullExpr = Arg.takeAs<Expr>();
Anders Carlsson99ba36d2009-06-05 15:38:08 +00002903 if (FullExpr)
Anders Carlsson0ece4912009-12-15 20:51:39 +00002904 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr);
Anders Carlssonec773872009-08-25 23:46:41 +00002905
Anders Carlsson165a0a02009-05-17 18:41:29 +00002906 return Owned(FullExpr);
2907}