blob: 1cecb5dc70b9005133bb5ca8b97734b63418a35b [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"
15#include "clang/AST/ExprCXX.h"
Steve Naroff210679c2007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000017#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000018#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000019#include "clang/Basic/Diagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000020#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22
Douglas Gregor487a75a2008-11-19 19:09:45 +000023/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000024/// name (e.g., operator void const *) as an expression. This is
25/// very similar to ActOnIdentifierExpr, except that instead of
26/// providing an identifier the parser provides the type of the
27/// conversion function.
Douglas Gregor487a75a2008-11-19 19:09:45 +000028Sema::ExprResult
29Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
30 TypeTy *Ty, bool HasTrailingLParen,
31 const CXXScopeSpec &SS) {
Douglas Gregor2def4832008-11-17 20:34:05 +000032 QualType ConvType = QualType::getFromOpaquePtr(Ty);
33 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
34 DeclarationName ConvName
35 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Douglas Gregor10c42622008-11-18 15:03:34 +000036 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor487a75a2008-11-19 19:09:45 +000037 &SS);
Douglas Gregor2def4832008-11-17 20:34:05 +000038}
Sebastian Redlc42e1182008-11-11 11:37:55 +000039
Douglas Gregor487a75a2008-11-19 19:09:45 +000040/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000041/// name (e.g., @c operator+ ) as an expression. This is very
42/// similar to ActOnIdentifierExpr, except that instead of providing
43/// an identifier the parser provides the kind of overloaded
44/// operator that was parsed.
Douglas Gregor487a75a2008-11-19 19:09:45 +000045Sema::ExprResult
46Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
47 OverloadedOperatorKind Op,
48 bool HasTrailingLParen,
49 const CXXScopeSpec &SS) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000050 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor487a75a2008-11-19 19:09:45 +000051 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000052}
53
Sebastian Redlc42e1182008-11-11 11:37:55 +000054/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
55Action::ExprResult
56Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
57 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
58 const NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000059 if (!StdNs)
60 return Diag(OpLoc, diag::err_need_header_before_typeid);
61
62 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
63 Decl *TypeInfoDecl = LookupDecl(TypeInfoII,
Sebastian Redlc42e1182008-11-11 11:37:55 +000064 Decl::IDNS_Tag | Decl::IDNS_Ordinary,
65 0, StdNs, /*createBuiltins=*/false);
66 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000067 if (!TypeInfoRecordDecl)
68 return Diag(OpLoc, diag::err_need_header_before_typeid);
Sebastian Redlc42e1182008-11-11 11:37:55 +000069
70 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
71
72 return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
73 SourceRange(OpLoc, RParenLoc));
74}
75
Steve Naroff1b273c42007-09-16 14:56:35 +000076/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Reid Spencer5f016e22007-07-11 17:01:13 +000077Action::ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000078Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000079 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000080 "Unknown C++ Boolean value!");
Steve Naroff210679c2007-08-25 14:02:58 +000081 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000082}
Chris Lattner50dd2892008-02-26 00:51:44 +000083
84/// ActOnCXXThrow - Parse throw expressions.
85Action::ExprResult
86Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
87 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
88}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000089
90Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
91 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
92 /// is a non-lvalue expression whose value is the address of the object for
93 /// which the function is called.
94
95 if (!isa<FunctionDecl>(CurContext)) {
96 Diag(ThisLoc, diag::err_invalid_this_use);
97 return ExprResult(true);
98 }
99
100 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
101 if (MD->isInstance())
Douglas Gregor796da182008-11-04 14:32:21 +0000102 return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000103
104 return Diag(ThisLoc, diag::err_invalid_this_use);
105}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000106
107/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
108/// Can be interpreted either as function-style casting ("int(x)")
109/// or class type construction ("ClassType(x,y,z)")
110/// or creation of a value-initialized type ("int()").
111Action::ExprResult
112Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
113 SourceLocation LParenLoc,
114 ExprTy **ExprTys, unsigned NumExprs,
115 SourceLocation *CommaLocs,
116 SourceLocation RParenLoc) {
117 assert(TypeRep && "Missing type!");
118 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
119 Expr **Exprs = (Expr**)ExprTys;
120 SourceLocation TyBeginLoc = TypeRange.getBegin();
121 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
122
123 if (const RecordType *RT = Ty->getAsRecordType()) {
124 // C++ 5.2.3p1:
125 // If the simple-type-specifier specifies a class type, the class type shall
126 // be complete.
127 //
128 if (!RT->getDecl()->isDefinition())
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000129 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use)
Chris Lattnerd1625842008-11-24 06:25:27 +0000130 << Ty << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000131
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +0000132 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
133 "class constructors are not supported yet");
134 return Diag(TyBeginLoc, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000135 }
136
137 // C++ 5.2.3p1:
138 // If the expression list is a single expression, the type conversion
139 // expression is equivalent (in definedness, and if defined in meaning) to the
140 // corresponding cast expression.
141 //
142 if (NumExprs == 1) {
143 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
144 return true;
Douglas Gregor49badde2008-10-27 19:41:14 +0000145 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
146 Exprs[0], RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000147 }
148
149 // C++ 5.2.3p1:
150 // If the expression list specifies more than a single value, the type shall
151 // be a class with a suitably declared constructor.
152 //
153 if (NumExprs > 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000154 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg)
155 << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000156
157 assert(NumExprs == 0 && "Expected 0 expressions");
158
159 // C++ 5.2.3p2:
160 // The expression T(), where T is a simple-type-specifier for a non-array
161 // complete object type or the (possibly cv-qualified) void type, creates an
162 // rvalue of the specified type, which is value-initialized.
163 //
164 if (Ty->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000165 return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000166 if (Ty->isIncompleteType() && !Ty->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000167 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use)
Chris Lattnerd1625842008-11-24 06:25:27 +0000168 << Ty << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000169
170 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
171}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000172
173
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000174/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
175/// @code new (memory) int[size][4] @endcode
176/// or
177/// @code ::new Foo(23, "hello") @endcode
178/// For the interpretation of this heap of arguments, consult the base version.
179Action::ExprResult
180Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
181 SourceLocation PlacementLParen,
182 ExprTy **PlacementArgs, unsigned NumPlaceArgs,
183 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000184 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000185 ExprTy **ConstructorArgs, unsigned NumConsArgs,
186 SourceLocation ConstructorRParen)
187{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000188 // FIXME: Throughout this function, we have rather bad location information.
189 // Implementing Declarator::getSourceRange() would go a long way toward
190 // fixing that.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000191
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000192 Expr *ArraySize = 0;
193 unsigned Skip = 0;
194 // If the specified type is an array, unwrap it and save the expression.
195 if (D.getNumTypeObjects() > 0 &&
196 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
197 DeclaratorChunk &Chunk = D.getTypeObject(0);
198 if (Chunk.Arr.hasStatic)
199 return Diag(Chunk.Loc, diag::err_static_illegal_in_new);
200 if (!Chunk.Arr.NumElts)
201 return Diag(Chunk.Loc, diag::err_array_new_needs_size);
202 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
203 Skip = 1;
204 }
205
206 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
207 if (D.getInvalidType())
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000208 return true;
209
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000210 if (CheckAllocatedType(AllocType, D))
211 return true;
212
213 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000214
215 // That every array dimension except the first is constant was already
216 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000217
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000218 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
219 // or enumeration type with a non-negative value."
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000220 if (ArraySize) {
221 QualType SizeType = ArraySize->getType();
222 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
223 return Diag(ArraySize->getSourceRange().getBegin(),
224 diag::err_array_size_not_integral)
225 << SizeType << ArraySize->getSourceRange();
226 // Let's see if this is a constant < 0. If so, we reject it out of hand.
227 // We don't care about special rules, so we tell the machinery it's not
228 // evaluated - it gives us a result in more cases.
229 llvm::APSInt Value;
230 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
231 if (Value < llvm::APSInt(
232 llvm::APInt::getNullValue(Value.getBitWidth()), false))
233 return Diag(ArraySize->getSourceRange().getBegin(),
234 diag::err_typecheck_negative_array_size)
235 << ArraySize->getSourceRange();
236 }
237 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000238
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000239 FunctionDecl *OperatorNew = 0;
240 FunctionDecl *OperatorDelete = 0;
241 Expr **PlaceArgs = (Expr**)PlacementArgs;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000242 if (FindAllocationFunctions(StartLoc, UseGlobal, AllocType, ArraySize,
243 PlaceArgs, NumPlaceArgs, OperatorNew,
244 OperatorDelete))
245 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000246
247 bool Init = ConstructorLParen.isValid();
248 // --- Choosing a constructor ---
249 // C++ 5.3.4p15
250 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
251 // the object is not initialized. If the object, or any part of it, is
252 // const-qualified, it's an error.
253 // 2) If T is a POD and there's an empty initializer, the object is value-
254 // initialized.
255 // 3) If T is a POD and there's one initializer argument, the object is copy-
256 // constructed.
257 // 4) If T is a POD and there's more initializer arguments, it's an error.
258 // 5) If T is not a POD, the initializer arguments are used as constructor
259 // arguments.
260 //
261 // Or by the C++0x formulation:
262 // 1) If there's no initializer, the object is default-initialized according
263 // to C++0x rules.
264 // 2) Otherwise, the object is direct-initialized.
265 CXXConstructorDecl *Constructor = 0;
266 Expr **ConsArgs = (Expr**)ConstructorArgs;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000267 if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000268 // FIXME: This is incorrect for when there is an empty initializer and
269 // no user-defined constructor. Must zero-initialize, not default-construct.
270 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000271 AllocType, ConsArgs, NumConsArgs,
272 D.getDeclSpec().getSourceRange().getBegin(),
273 SourceRange(D.getDeclSpec().getSourceRange().getBegin(),
274 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000275 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000276 NumConsArgs != 0 ? IK_Direct : IK_Default);
277 if (!Constructor)
278 return true;
279 } else {
280 if (!Init) {
281 // FIXME: Check that no subpart is const.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000282 if (AllocType.isConstQualified()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000283 Diag(StartLoc, diag::err_new_uninitialized_const)
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000284 << D.getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000285 return true;
286 }
287 } else if (NumConsArgs == 0) {
288 // Object is value-initialized. Do nothing.
289 } else if (NumConsArgs == 1) {
290 // Object is direct-initialized.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000291 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000292 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
293 DeclarationName() /*AllocType.getAsString()*/))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000294 return true;
295 } else {
296 Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg)
297 << SourceRange(ConstructorLParen, ConstructorRParen);
298 }
299 }
300
301 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
302
303 return new CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000304 ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000305 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000306 StartLoc, Init ? ConstructorRParen : SourceLocation());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000307}
308
309/// CheckAllocatedType - Checks that a type is suitable as the allocated type
310/// in a new-expression.
311/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000312bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000313{
314 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
315 // abstract class type or array thereof.
316 // FIXME: We don't have abstract types yet.
317 // FIXME: Under C++ semantics, an incomplete object type is still an object
318 // type. This code assumes the C semantics, where it's not.
319 if (!AllocType->isObjectType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000320 unsigned type; // For the select in the message.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000321 if (AllocType->isFunctionType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000322 type = 0;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000323 } else if(AllocType->isIncompleteType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000324 type = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000325 } else {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000326 assert(AllocType->isReferenceType() && "What else could it be?");
327 type = 2;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000328 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000329 SourceRange TyR = D.getDeclSpec().getSourceRange();
330 // FIXME: This is very much a guess and won't work for, e.g., pointers.
331 if (D.getNumTypeObjects() > 0)
332 TyR.setEnd(D.getTypeObject(0).Loc);
333 Diag(TyR.getBegin(), diag::err_bad_new_type)
334 << AllocType.getAsString() << type << TyR;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000335 return true;
336 }
337
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000338 // Every dimension shall be of constant size.
339 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000340 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
341 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000342 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
343 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000344 return true;
345 }
346 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000347 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000348 }
349
350 return false;
351}
352
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000353/// FindAllocationFunctions - Finds the overloads of operator new and delete
354/// that are appropriate for the allocation.
355bool Sema::FindAllocationFunctions(SourceLocation StartLoc, bool UseGlobal,
356 QualType AllocType, bool IsArray,
357 Expr **PlaceArgs, unsigned NumPlaceArgs,
358 FunctionDecl *&OperatorNew,
359 FunctionDecl *&OperatorDelete)
360{
361 // --- Choosing an allocation function ---
362 // C++ 5.3.4p8 - 14 & 18
363 // 1) If UseGlobal is true, only look in the global scope. Else, also look
364 // in the scope of the allocated class.
365 // 2) If an array size is given, look for operator new[], else look for
366 // operator new.
367 // 3) The first argument is always size_t. Append the arguments from the
368 // placement form.
369 // FIXME: Also find the appropriate delete operator.
370
371 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
372 // We don't care about the actual value of this argument.
373 // FIXME: Should the Sema create the expression and embed it in the syntax
374 // tree? Or should the consumer just recalculate the value?
375 AllocArgs[0] = new IntegerLiteral(llvm::APInt::getNullValue(
376 Context.Target.getPointerWidth(0)),
377 Context.getSizeType(),
378 SourceLocation());
379 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
380
381 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
382 IsArray ? OO_Array_New : OO_New);
383 if (AllocType->isRecordType() && !UseGlobal) {
384 OverloadCandidateSet MemberNewCandidates;
385 const CXXRecordType *Record = cast<CXXRecordType>(
386 AllocType->getAsRecordType());
387 IdentifierResolver::iterator I =
388 IdResolver.begin(NewName, Record->getDecl(), /*LookInParentCtx=*/false);
389 NamedDecl *Decl = (I == IdResolver.end()) ? 0 : *I;
390 // Member operator new is implicitly treated as static, so don't use
391 // AddMemberCandidate.
392 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl))
393 AddOverloadCandidate(Method, &AllocArgs[0], AllocArgs.size(),
394 MemberNewCandidates,
395 /*SuppressUserConversions=*/false);
396 else if (OverloadedFunctionDecl *Ovl
397 = dyn_cast_or_null<OverloadedFunctionDecl>(Decl)) {
398 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
399 FEnd = Ovl->function_end();
400 F != FEnd; ++F) {
401 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
402 AddOverloadCandidate(Method, &AllocArgs[0], AllocArgs.size(),
403 MemberNewCandidates,
404 /*SuppressUserConversions=*/false);
405 }
406 }
407
408 // Do the resolution.
409 OverloadCandidateSet::iterator Best;
410 switch (BestViableFunction(MemberNewCandidates, Best)) {
411 case OR_Success: {
412 // Got one!
413 FunctionDecl *FnDecl = Best->Function;
414 // The first argument is size_t, and the first parameter must be size_t,
415 // too.
416 for (unsigned i = 1; i < AllocArgs.size(); ++i) {
417 // FIXME: Passing word to diagnostic.
418 // This might modify the argument expression, so pass the one in
419 // PlaceArgs.
420 if (PerformCopyInitialization(PlaceArgs[i-1],
421 FnDecl->getParamDecl(i)->getType(),
422 "passing"))
423 return true;
424 }
425 OperatorNew = FnDecl;
426 break;
427 }
428
429 case OR_No_Viable_Function:
430 // No viable function; look something up in the global scope instead.
431 break;
432
433 case OR_Ambiguous:
434 // FIXME: Bad location information.
435 Diag(StartLoc, diag::err_ovl_ambiguous_oper) << NewName;
436 PrintOverloadCandidates(MemberNewCandidates, /*OnlyViable=*/true);
437 return true;
438 }
439 }
440 if (!OperatorNew) {
441 // Didn't find a member overload. Look for a global one.
442 DeclareGlobalNewDelete();
443 OverloadCandidateSet GlobalNewCandidates;
444 IdentifierResolver::iterator I =
445 IdResolver.begin(NewName, Context.getTranslationUnitDecl(),
446 /*LookInParentCtx=*/false);
447 NamedDecl *Decl = (I == IdResolver.end()) ? 0 : *I;
448 if (FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Decl))
449 AddOverloadCandidate(Fn, &AllocArgs[0], AllocArgs.size(),
450 GlobalNewCandidates,
451 /*SuppressUserConversions=*/false);
452 else if (OverloadedFunctionDecl *Ovl
453 = dyn_cast_or_null<OverloadedFunctionDecl>(Decl)) {
454 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
455 FEnd = Ovl->function_end();
456 F != FEnd; ++F) {
457 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*F))
458 AddOverloadCandidate(Fn, &AllocArgs[0], AllocArgs.size(),
459 GlobalNewCandidates,
460 /*SuppressUserConversions=*/false);
461 }
462 }
463
464 // Do the resolution.
465 OverloadCandidateSet::iterator Best;
466 switch (BestViableFunction(GlobalNewCandidates, Best)) {
467 case OR_Success: {
468 // Got one!
469 FunctionDecl *FnDecl = Best->Function;
470 // The first argument is size_t, and the first parameter must be size_t,
471 // too. This is checked on declaration and can be assumed.
472 for (unsigned i = 1; i < AllocArgs.size(); ++i) {
473 // FIXME: Passing word to diagnostic.
474 // This might modify the argument expression, so pass the one in
475 // PlaceArgs.
476 if (PerformCopyInitialization(PlaceArgs[i-1],
477 FnDecl->getParamDecl(i)->getType(),
478 "passing"))
479 return true;
480 }
481 OperatorNew = FnDecl;
482 break;
483 }
484
485 case OR_No_Viable_Function:
486 // FIXME: Bad location information.
487 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
488 << NewName << (unsigned)GlobalNewCandidates.size();
489 PrintOverloadCandidates(GlobalNewCandidates, /*OnlyViable=*/false);
490 return true;
491
492 case OR_Ambiguous:
493 // FIXME: Bad location information.
494 Diag(StartLoc, diag::err_ovl_ambiguous_oper) << NewName;
495 PrintOverloadCandidates(GlobalNewCandidates, /*OnlyViable=*/true);
496 return true;
497 }
498 }
499
500 AllocArgs[0]->Destroy(Context);
501 return false;
502}
503
504/// DeclareGlobalNewDelete - Declare the global forms of operator new and
505/// delete. These are:
506/// @code
507/// void* operator new(std::size_t) throw(std::bad_alloc);
508/// void* operator new[](std::size_t) throw(std::bad_alloc);
509/// void operator delete(void *) throw();
510/// void operator delete[](void *) throw();
511/// @endcode
512/// Note that the placement and nothrow forms of new are *not* implicitly
513/// declared. Their use requires including \<new\>.
514void Sema::DeclareGlobalNewDelete()
515{
516 if (GlobalNewDeleteDeclared)
517 return;
518 GlobalNewDeleteDeclared = true;
519
520 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
521 QualType SizeT = Context.getSizeType();
522
523 // FIXME: Exception specifications are not added.
524 DeclareGlobalAllocationFunction(
525 Context.DeclarationNames.getCXXOperatorName(OO_New),
526 VoidPtr, SizeT);
527 DeclareGlobalAllocationFunction(
528 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
529 VoidPtr, SizeT);
530 DeclareGlobalAllocationFunction(
531 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
532 Context.VoidTy, VoidPtr);
533 DeclareGlobalAllocationFunction(
534 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
535 Context.VoidTy, VoidPtr);
536}
537
538/// DeclareGlobalAllocationFunction - Declares a single implicit global
539/// allocation function if it doesn't already exist.
540void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
541 QualType Return, QualType Argument)
542{
543 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
544
545 // Check if this function is already declared.
546 IdentifierResolver::iterator I = IdResolver.begin(Name, GlobalCtx,
547 /*CheckParent=*/false);
548
549 if (I != IdResolver.end()) {
550 NamedDecl *Decl = *I;
551 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(Decl)) {
552 // The return type fits. This is checked when the function is declared.
553 if (Fn->getNumParams() == 1 &&
554 Context.getCanonicalType(Fn->getParamDecl(0)->getType()) == Argument)
555 return;
556 } else if(OverloadedFunctionDecl *Ovl =
557 dyn_cast<OverloadedFunctionDecl>(Decl)) {
558 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
559 FEnd = Ovl->function_end();
560 F != FEnd; ++F) {
561 if ((*F)->getNumParams() == 1 &&
562 Context.getCanonicalType((*F)->getParamDecl(0)->getType())
563 == Argument)
564 return;
565 }
566 }
567 }
568
569 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
570 FunctionDecl *Alloc =
571 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
572 FnType, FunctionDecl::None, false, 0,
573 SourceLocation());
574 Alloc->setImplicit();
575 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
576 0, Argument, VarDecl::None, 0, 0);
577 Alloc->setParams(&Param, 1);
578
579 PushOnScopeChains(Alloc, TUScope);
580}
581
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000582/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
583/// @code ::delete ptr; @endcode
584/// or
585/// @code delete [] ptr; @endcode
586Action::ExprResult
587Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
588 bool ArrayForm, ExprTy *Operand)
589{
590 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
591 // having a single conversion function to a pointer type. The result has
592 // type void."
593 // DR599 amends "pointer type" to "pointer to object type" in both cases.
594
595 Expr *Ex = (Expr *)Operand;
596 QualType Type = Ex->getType();
597
598 if (Type->isRecordType()) {
599 // FIXME: Find that one conversion function and amend the type.
600 }
601
602 if (!Type->isPointerType()) {
Chris Lattnerd1625842008-11-24 06:25:27 +0000603 Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000604 return true;
605 }
606
607 QualType Pointee = Type->getAsPointerType()->getPointeeType();
608 if (Pointee->isIncompleteType() && !Pointee->isVoidType())
609 Diag(StartLoc, diag::warn_delete_incomplete)
Chris Lattnerd1625842008-11-24 06:25:27 +0000610 << Pointee << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000611 else if (!Pointee->isObjectType()) {
612 Diag(StartLoc, diag::err_delete_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +0000613 << Type << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000614 return true;
615 }
616
617 // FIXME: Look up the correct operator delete overload and pass a pointer
618 // along.
619 // FIXME: Check access and ambiguity of operator delete and destructor.
620
621 return new CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0, Ex,
622 StartLoc);
623}
624
625
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000626/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
627/// C++ if/switch/while/for statement.
628/// e.g: "if (int x = f()) {...}"
629Action::ExprResult
630Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
631 Declarator &D,
632 SourceLocation EqualLoc,
633 ExprTy *AssignExprVal) {
634 assert(AssignExprVal && "Null assignment expression");
635
636 // C++ 6.4p2:
637 // The declarator shall not specify a function or an array.
638 // The type-specifier-seq shall not contain typedef and shall not declare a
639 // new class or enumeration.
640
641 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
642 "Parser allowed 'typedef' as storage class of condition decl.");
643
644 QualType Ty = GetTypeForDeclarator(D, S);
645
646 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
647 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
648 // would be created and CXXConditionDeclExpr wants a VarDecl.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000649 return Diag(StartLoc, diag::err_invalid_use_of_function_type)
650 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000651 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000652 Diag(StartLoc, diag::err_invalid_use_of_array_type)
653 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000654 } else if (const RecordType *RT = Ty->getAsRecordType()) {
655 RecordDecl *RD = RT->getDecl();
656 // The type-specifier-seq shall not declare a new class...
657 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
658 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
659 } else if (const EnumType *ET = Ty->getAsEnumType()) {
660 EnumDecl *ED = ET->getDecl();
661 // ...or enumeration.
662 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
663 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
664 }
665
666 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
667 if (!Dcl)
668 return true;
669 AddInitializerToDecl(Dcl, AssignExprVal);
670
671 return new CXXConditionDeclExpr(StartLoc, EqualLoc,
672 cast<VarDecl>(static_cast<Decl *>(Dcl)));
673}
674
675/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
676bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
677 // C++ 6.4p4:
678 // The value of a condition that is an initialized declaration in a statement
679 // other than a switch statement is the value of the declared variable
680 // implicitly converted to type bool. If that conversion is ill-formed, the
681 // program is ill-formed.
682 // The value of a condition that is an expression is the value of the
683 // expression, implicitly converted to bool.
684 //
685 QualType Ty = CondExpr->getType(); // Save the type.
686 AssignConvertType
687 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
688 if (ConvTy == Incompatible)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000689 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition)
Chris Lattnerd1625842008-11-24 06:25:27 +0000690 << Ty << CondExpr->getSourceRange();
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000691 return false;
692}
Douglas Gregor77a52232008-09-12 00:47:35 +0000693
694/// Helper function to determine whether this is the (deprecated) C++
695/// conversion from a string literal to a pointer to non-const char or
696/// non-const wchar_t (for narrow and wide string literals,
697/// respectively).
698bool
699Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
700 // Look inside the implicit cast, if it exists.
701 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
702 From = Cast->getSubExpr();
703
704 // A string literal (2.13.4) that is not a wide string literal can
705 // be converted to an rvalue of type "pointer to char"; a wide
706 // string literal can be converted to an rvalue of type "pointer
707 // to wchar_t" (C++ 4.2p2).
708 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
709 if (const PointerType *ToPtrType = ToType->getAsPointerType())
710 if (const BuiltinType *ToPointeeType
711 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
712 // This conversion is considered only when there is an
713 // explicit appropriate pointer target type (C++ 4.2p2).
714 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
715 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
716 (!StrLit->isWide() &&
717 (ToPointeeType->getKind() == BuiltinType::Char_U ||
718 ToPointeeType->getKind() == BuiltinType::Char_S))))
719 return true;
720 }
721
722 return false;
723}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000724
725/// PerformImplicitConversion - Perform an implicit conversion of the
726/// expression From to the type ToType. Returns true if there was an
727/// error, false otherwise. The expression From is replaced with the
728/// converted expression.
729bool
730Sema::PerformImplicitConversion(Expr *&From, QualType ToType)
731{
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000732 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000733 switch (ICS.ConversionKind) {
734 case ImplicitConversionSequence::StandardConversion:
735 if (PerformImplicitConversion(From, ToType, ICS.Standard))
736 return true;
737 break;
738
739 case ImplicitConversionSequence::UserDefinedConversion:
740 // FIXME: This is, of course, wrong. We'll need to actually call
741 // the constructor or conversion operator, and then cope with the
742 // standard conversions.
743 ImpCastExprToType(From, ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000744 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000745
746 case ImplicitConversionSequence::EllipsisConversion:
747 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000748 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000749
750 case ImplicitConversionSequence::BadConversion:
751 return true;
752 }
753
754 // Everything went well.
755 return false;
756}
757
758/// PerformImplicitConversion - Perform an implicit conversion of the
759/// expression From to the type ToType by following the standard
760/// conversion sequence SCS. Returns true if there was an error, false
761/// otherwise. The expression From is replaced with the converted
762/// expression.
763bool
764Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
765 const StandardConversionSequence& SCS)
766{
767 // Overall FIXME: we are recomputing too many types here and doing
768 // far too much extra work. What this means is that we need to keep
769 // track of more information that is computed when we try the
770 // implicit conversion initially, so that we don't need to recompute
771 // anything here.
772 QualType FromType = From->getType();
773
Douglas Gregor225c41e2008-11-03 19:09:14 +0000774 if (SCS.CopyConstructor) {
775 // FIXME: Create a temporary object by calling the copy
776 // constructor.
777 ImpCastExprToType(From, ToType);
778 return false;
779 }
780
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000781 // Perform the first implicit conversion.
782 switch (SCS.First) {
783 case ICK_Identity:
784 case ICK_Lvalue_To_Rvalue:
785 // Nothing to do.
786 break;
787
788 case ICK_Array_To_Pointer:
Douglas Gregor904eed32008-11-10 20:40:00 +0000789 if (FromType->isOverloadType()) {
790 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
791 if (!Fn)
792 return true;
793
794 FixOverloadedFunctionReference(From, Fn);
795 FromType = From->getType();
796 } else {
797 FromType = Context.getArrayDecayedType(FromType);
798 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000799 ImpCastExprToType(From, FromType);
800 break;
801
802 case ICK_Function_To_Pointer:
803 FromType = Context.getPointerType(FromType);
804 ImpCastExprToType(From, FromType);
805 break;
806
807 default:
808 assert(false && "Improper first standard conversion");
809 break;
810 }
811
812 // Perform the second implicit conversion
813 switch (SCS.Second) {
814 case ICK_Identity:
815 // Nothing to do.
816 break;
817
818 case ICK_Integral_Promotion:
819 case ICK_Floating_Promotion:
820 case ICK_Integral_Conversion:
821 case ICK_Floating_Conversion:
822 case ICK_Floating_Integral:
823 FromType = ToType.getUnqualifiedType();
824 ImpCastExprToType(From, FromType);
825 break;
826
827 case ICK_Pointer_Conversion:
828 if (CheckPointerConversion(From, ToType))
829 return true;
830 ImpCastExprToType(From, ToType);
831 break;
832
833 case ICK_Pointer_Member:
834 // FIXME: Implement pointer-to-member conversions.
835 assert(false && "Pointer-to-member conversions are unsupported");
836 break;
837
838 case ICK_Boolean_Conversion:
839 FromType = Context.BoolTy;
840 ImpCastExprToType(From, FromType);
841 break;
842
843 default:
844 assert(false && "Improper second standard conversion");
845 break;
846 }
847
848 switch (SCS.Third) {
849 case ICK_Identity:
850 // Nothing to do.
851 break;
852
853 case ICK_Qualification:
854 ImpCastExprToType(From, ToType);
855 break;
856
857 default:
858 assert(false && "Improper second standard conversion");
859 break;
860 }
861
862 return false;
863}
864