blob: 1e9b945a181bf9854854a81513e319f6943bd9fd [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) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000384 CXXRecordDecl *Record = cast<CXXRecordType>(AllocType->getAsRecordType())
385 ->getDecl();
386 // FIXME: We fail to find inherited overloads.
387 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
388 AllocArgs.size(), Record, /*AllowMissing=*/true,
389 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000390 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000391 }
392 if (!OperatorNew) {
393 // Didn't find a member overload. Look for a global one.
394 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000395 DeclContext *TUDecl = Context.getTranslationUnitDecl();
396 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
397 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
398 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000399 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000400 }
401
Sebastian Redl7f662392008-12-04 22:20:51 +0000402 // FIXME: This is leaked on error. But so much is currently in Sema that it's
403 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000404 AllocArgs[0]->Destroy(Context);
405 return false;
406}
407
Sebastian Redl7f662392008-12-04 22:20:51 +0000408/// FindAllocationOverload - Find an fitting overload for the allocation
409/// function in the specified scope.
410bool Sema::FindAllocationOverload(SourceLocation StartLoc, DeclarationName Name,
411 Expr** Args, unsigned NumArgs,
412 DeclContext *Ctx, bool AllowMissing,
413 FunctionDecl *&Operator)
414{
415 IdentifierResolver::iterator I =
416 IdResolver.begin(Name, Ctx, /*LookInParentCtx=*/false);
417 if (I == IdResolver.end()) {
418 if (AllowMissing)
419 return false;
420 // FIXME: Bad location information.
421 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
422 << Name << 0;
423 }
424
425 OverloadCandidateSet Candidates;
426 NamedDecl *Decl = *I;
427 // Even member operator new/delete are implicitly treated as static, so don't
428 // use AddMemberCandidate.
429 if (FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Decl))
430 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
431 /*SuppressUserConversions=*/false);
432 else if (OverloadedFunctionDecl *Ovl
433 = dyn_cast_or_null<OverloadedFunctionDecl>(Decl)) {
434 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
435 FEnd = Ovl->function_end();
436 F != FEnd; ++F) {
437 if (FunctionDecl *Fn = *F)
438 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
439 /*SuppressUserConversions=*/false);
440 }
441 }
442
443 // Do the resolution.
444 OverloadCandidateSet::iterator Best;
445 switch(BestViableFunction(Candidates, Best)) {
446 case OR_Success: {
447 // Got one!
448 FunctionDecl *FnDecl = Best->Function;
449 // The first argument is size_t, and the first parameter must be size_t,
450 // too. This is checked on declaration and can be assumed. (It can't be
451 // asserted on, though, since invalid decls are left in there.)
452 for (unsigned i = 1; i < NumArgs; ++i) {
453 // FIXME: Passing word to diagnostic.
454 if (PerformCopyInitialization(Args[i-1],
455 FnDecl->getParamDecl(i)->getType(),
456 "passing"))
457 return true;
458 }
459 Operator = FnDecl;
460 return false;
461 }
462
463 case OR_No_Viable_Function:
464 if (AllowMissing)
465 return false;
466 // FIXME: Bad location information.
467 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
468 << Name << (unsigned)Candidates.size();
469 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
470 return true;
471
472 case OR_Ambiguous:
473 // FIXME: Bad location information.
474 Diag(StartLoc, diag::err_ovl_ambiguous_call)
475 << Name;
476 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
477 return true;
478 }
479 assert(false && "Unreachable, bad result from BestViableFunction");
480 return true;
481}
482
483
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000484/// DeclareGlobalNewDelete - Declare the global forms of operator new and
485/// delete. These are:
486/// @code
487/// void* operator new(std::size_t) throw(std::bad_alloc);
488/// void* operator new[](std::size_t) throw(std::bad_alloc);
489/// void operator delete(void *) throw();
490/// void operator delete[](void *) throw();
491/// @endcode
492/// Note that the placement and nothrow forms of new are *not* implicitly
493/// declared. Their use requires including \<new\>.
494void Sema::DeclareGlobalNewDelete()
495{
496 if (GlobalNewDeleteDeclared)
497 return;
498 GlobalNewDeleteDeclared = true;
499
500 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
501 QualType SizeT = Context.getSizeType();
502
503 // FIXME: Exception specifications are not added.
504 DeclareGlobalAllocationFunction(
505 Context.DeclarationNames.getCXXOperatorName(OO_New),
506 VoidPtr, SizeT);
507 DeclareGlobalAllocationFunction(
508 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
509 VoidPtr, SizeT);
510 DeclareGlobalAllocationFunction(
511 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
512 Context.VoidTy, VoidPtr);
513 DeclareGlobalAllocationFunction(
514 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
515 Context.VoidTy, VoidPtr);
516}
517
518/// DeclareGlobalAllocationFunction - Declares a single implicit global
519/// allocation function if it doesn't already exist.
520void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
521 QualType Return, QualType Argument)
522{
523 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
524
525 // Check if this function is already declared.
526 IdentifierResolver::iterator I = IdResolver.begin(Name, GlobalCtx,
527 /*CheckParent=*/false);
528
529 if (I != IdResolver.end()) {
530 NamedDecl *Decl = *I;
531 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(Decl)) {
532 // The return type fits. This is checked when the function is declared.
533 if (Fn->getNumParams() == 1 &&
534 Context.getCanonicalType(Fn->getParamDecl(0)->getType()) == Argument)
535 return;
536 } else if(OverloadedFunctionDecl *Ovl =
537 dyn_cast<OverloadedFunctionDecl>(Decl)) {
538 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
539 FEnd = Ovl->function_end();
540 F != FEnd; ++F) {
541 if ((*F)->getNumParams() == 1 &&
542 Context.getCanonicalType((*F)->getParamDecl(0)->getType())
543 == Argument)
544 return;
545 }
546 }
547 }
548
549 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
550 FunctionDecl *Alloc =
551 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
552 FnType, FunctionDecl::None, false, 0,
553 SourceLocation());
554 Alloc->setImplicit();
555 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
556 0, Argument, VarDecl::None, 0, 0);
557 Alloc->setParams(&Param, 1);
558
559 PushOnScopeChains(Alloc, TUScope);
560}
561
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000562/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
563/// @code ::delete ptr; @endcode
564/// or
565/// @code delete [] ptr; @endcode
566Action::ExprResult
567Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
568 bool ArrayForm, ExprTy *Operand)
569{
570 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
571 // having a single conversion function to a pointer type. The result has
572 // type void."
573 // DR599 amends "pointer type" to "pointer to object type" in both cases.
574
575 Expr *Ex = (Expr *)Operand;
576 QualType Type = Ex->getType();
577
578 if (Type->isRecordType()) {
579 // FIXME: Find that one conversion function and amend the type.
580 }
581
582 if (!Type->isPointerType()) {
Chris Lattnerd1625842008-11-24 06:25:27 +0000583 Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000584 return true;
585 }
586
587 QualType Pointee = Type->getAsPointerType()->getPointeeType();
588 if (Pointee->isIncompleteType() && !Pointee->isVoidType())
589 Diag(StartLoc, diag::warn_delete_incomplete)
Chris Lattnerd1625842008-11-24 06:25:27 +0000590 << Pointee << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000591 else if (!Pointee->isObjectType()) {
592 Diag(StartLoc, diag::err_delete_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +0000593 << Type << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000594 return true;
595 }
596
597 // FIXME: Look up the correct operator delete overload and pass a pointer
598 // along.
599 // FIXME: Check access and ambiguity of operator delete and destructor.
600
601 return new CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0, Ex,
602 StartLoc);
603}
604
605
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000606/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
607/// C++ if/switch/while/for statement.
608/// e.g: "if (int x = f()) {...}"
609Action::ExprResult
610Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
611 Declarator &D,
612 SourceLocation EqualLoc,
613 ExprTy *AssignExprVal) {
614 assert(AssignExprVal && "Null assignment expression");
615
616 // C++ 6.4p2:
617 // The declarator shall not specify a function or an array.
618 // The type-specifier-seq shall not contain typedef and shall not declare a
619 // new class or enumeration.
620
621 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
622 "Parser allowed 'typedef' as storage class of condition decl.");
623
624 QualType Ty = GetTypeForDeclarator(D, S);
625
626 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
627 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
628 // would be created and CXXConditionDeclExpr wants a VarDecl.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000629 return Diag(StartLoc, diag::err_invalid_use_of_function_type)
630 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000631 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000632 Diag(StartLoc, diag::err_invalid_use_of_array_type)
633 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000634 } else if (const RecordType *RT = Ty->getAsRecordType()) {
635 RecordDecl *RD = RT->getDecl();
636 // The type-specifier-seq shall not declare a new class...
637 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
638 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
639 } else if (const EnumType *ET = Ty->getAsEnumType()) {
640 EnumDecl *ED = ET->getDecl();
641 // ...or enumeration.
642 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
643 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
644 }
645
646 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
647 if (!Dcl)
648 return true;
649 AddInitializerToDecl(Dcl, AssignExprVal);
650
651 return new CXXConditionDeclExpr(StartLoc, EqualLoc,
652 cast<VarDecl>(static_cast<Decl *>(Dcl)));
653}
654
655/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
656bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
657 // C++ 6.4p4:
658 // The value of a condition that is an initialized declaration in a statement
659 // other than a switch statement is the value of the declared variable
660 // implicitly converted to type bool. If that conversion is ill-formed, the
661 // program is ill-formed.
662 // The value of a condition that is an expression is the value of the
663 // expression, implicitly converted to bool.
664 //
665 QualType Ty = CondExpr->getType(); // Save the type.
666 AssignConvertType
667 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
668 if (ConvTy == Incompatible)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000669 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition)
Chris Lattnerd1625842008-11-24 06:25:27 +0000670 << Ty << CondExpr->getSourceRange();
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000671 return false;
672}
Douglas Gregor77a52232008-09-12 00:47:35 +0000673
674/// Helper function to determine whether this is the (deprecated) C++
675/// conversion from a string literal to a pointer to non-const char or
676/// non-const wchar_t (for narrow and wide string literals,
677/// respectively).
678bool
679Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
680 // Look inside the implicit cast, if it exists.
681 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
682 From = Cast->getSubExpr();
683
684 // A string literal (2.13.4) that is not a wide string literal can
685 // be converted to an rvalue of type "pointer to char"; a wide
686 // string literal can be converted to an rvalue of type "pointer
687 // to wchar_t" (C++ 4.2p2).
688 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
689 if (const PointerType *ToPtrType = ToType->getAsPointerType())
690 if (const BuiltinType *ToPointeeType
691 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
692 // This conversion is considered only when there is an
693 // explicit appropriate pointer target type (C++ 4.2p2).
694 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
695 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
696 (!StrLit->isWide() &&
697 (ToPointeeType->getKind() == BuiltinType::Char_U ||
698 ToPointeeType->getKind() == BuiltinType::Char_S))))
699 return true;
700 }
701
702 return false;
703}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000704
705/// PerformImplicitConversion - Perform an implicit conversion of the
706/// expression From to the type ToType. Returns true if there was an
707/// error, false otherwise. The expression From is replaced with the
708/// converted expression.
709bool
710Sema::PerformImplicitConversion(Expr *&From, QualType ToType)
711{
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000712 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000713 switch (ICS.ConversionKind) {
714 case ImplicitConversionSequence::StandardConversion:
715 if (PerformImplicitConversion(From, ToType, ICS.Standard))
716 return true;
717 break;
718
719 case ImplicitConversionSequence::UserDefinedConversion:
720 // FIXME: This is, of course, wrong. We'll need to actually call
721 // the constructor or conversion operator, and then cope with the
722 // standard conversions.
723 ImpCastExprToType(From, ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000724 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000725
726 case ImplicitConversionSequence::EllipsisConversion:
727 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000728 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000729
730 case ImplicitConversionSequence::BadConversion:
731 return true;
732 }
733
734 // Everything went well.
735 return false;
736}
737
738/// PerformImplicitConversion - Perform an implicit conversion of the
739/// expression From to the type ToType by following the standard
740/// conversion sequence SCS. Returns true if there was an error, false
741/// otherwise. The expression From is replaced with the converted
742/// expression.
743bool
744Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
745 const StandardConversionSequence& SCS)
746{
747 // Overall FIXME: we are recomputing too many types here and doing
748 // far too much extra work. What this means is that we need to keep
749 // track of more information that is computed when we try the
750 // implicit conversion initially, so that we don't need to recompute
751 // anything here.
752 QualType FromType = From->getType();
753
Douglas Gregor225c41e2008-11-03 19:09:14 +0000754 if (SCS.CopyConstructor) {
755 // FIXME: Create a temporary object by calling the copy
756 // constructor.
757 ImpCastExprToType(From, ToType);
758 return false;
759 }
760
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000761 // Perform the first implicit conversion.
762 switch (SCS.First) {
763 case ICK_Identity:
764 case ICK_Lvalue_To_Rvalue:
765 // Nothing to do.
766 break;
767
768 case ICK_Array_To_Pointer:
Douglas Gregor904eed32008-11-10 20:40:00 +0000769 if (FromType->isOverloadType()) {
770 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
771 if (!Fn)
772 return true;
773
774 FixOverloadedFunctionReference(From, Fn);
775 FromType = From->getType();
776 } else {
777 FromType = Context.getArrayDecayedType(FromType);
778 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000779 ImpCastExprToType(From, FromType);
780 break;
781
782 case ICK_Function_To_Pointer:
783 FromType = Context.getPointerType(FromType);
784 ImpCastExprToType(From, FromType);
785 break;
786
787 default:
788 assert(false && "Improper first standard conversion");
789 break;
790 }
791
792 // Perform the second implicit conversion
793 switch (SCS.Second) {
794 case ICK_Identity:
795 // Nothing to do.
796 break;
797
798 case ICK_Integral_Promotion:
799 case ICK_Floating_Promotion:
800 case ICK_Integral_Conversion:
801 case ICK_Floating_Conversion:
802 case ICK_Floating_Integral:
803 FromType = ToType.getUnqualifiedType();
804 ImpCastExprToType(From, FromType);
805 break;
806
807 case ICK_Pointer_Conversion:
808 if (CheckPointerConversion(From, ToType))
809 return true;
810 ImpCastExprToType(From, ToType);
811 break;
812
813 case ICK_Pointer_Member:
814 // FIXME: Implement pointer-to-member conversions.
815 assert(false && "Pointer-to-member conversions are unsupported");
816 break;
817
818 case ICK_Boolean_Conversion:
819 FromType = Context.BoolTy;
820 ImpCastExprToType(From, FromType);
821 break;
822
823 default:
824 assert(false && "Improper second standard conversion");
825 break;
826 }
827
828 switch (SCS.Third) {
829 case ICK_Identity:
830 // Nothing to do.
831 break;
832
833 case ICK_Qualification:
834 ImpCastExprToType(From, ToType);
835 break;
836
837 default:
838 assert(false && "Improper second standard conversion");
839 break;
840 }
841
842 return false;
843}
844