blob: eb2e647f0134bf1a58afcca6a3290484219f6e40 [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"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000021#include "llvm/ADT/STLExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Douglas Gregor487a75a2008-11-19 19:09:45 +000024/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
Douglas Gregor2def4832008-11-17 20:34:05 +000025/// name (e.g., operator void const *) as an expression. This is
26/// very similar to ActOnIdentifierExpr, except that instead of
27/// providing an identifier the parser provides the type of the
28/// conversion function.
Douglas Gregor487a75a2008-11-19 19:09:45 +000029Sema::ExprResult
30Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
32 const CXXScopeSpec &SS) {
Douglas Gregor2def4832008-11-17 20:34:05 +000033 QualType ConvType = QualType::getFromOpaquePtr(Ty);
34 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
35 DeclarationName ConvName
36 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Douglas Gregor10c42622008-11-18 15:03:34 +000037 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor487a75a2008-11-19 19:09:45 +000038 &SS);
Douglas Gregor2def4832008-11-17 20:34:05 +000039}
Sebastian Redlc42e1182008-11-11 11:37:55 +000040
Douglas Gregor487a75a2008-11-19 19:09:45 +000041/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000042/// name (e.g., @c operator+ ) as an expression. This is very
43/// similar to ActOnIdentifierExpr, except that instead of providing
44/// an identifier the parser provides the kind of overloaded
45/// operator that was parsed.
Douglas Gregor487a75a2008-11-19 19:09:45 +000046Sema::ExprResult
47Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
48 OverloadedOperatorKind Op,
49 bool HasTrailingLParen,
50 const CXXScopeSpec &SS) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000051 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor487a75a2008-11-19 19:09:45 +000052 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000053}
54
Sebastian Redlc42e1182008-11-11 11:37:55 +000055/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
56Action::ExprResult
57Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
58 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
59 const NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000060 if (!StdNs)
61 return Diag(OpLoc, diag::err_need_header_before_typeid);
62
63 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
64 Decl *TypeInfoDecl = LookupDecl(TypeInfoII,
Sebastian Redlc42e1182008-11-11 11:37:55 +000065 Decl::IDNS_Tag | Decl::IDNS_Ordinary,
66 0, StdNs, /*createBuiltins=*/false);
67 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000068 if (!TypeInfoRecordDecl)
69 return Diag(OpLoc, diag::err_need_header_before_typeid);
Sebastian Redlc42e1182008-11-11 11:37:55 +000070
71 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
72
73 return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
74 SourceRange(OpLoc, RParenLoc));
75}
76
Steve Naroff1b273c42007-09-16 14:56:35 +000077/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Reid Spencer5f016e22007-07-11 17:01:13 +000078Action::ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000079Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000080 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000081 "Unknown C++ Boolean value!");
Steve Naroff210679c2007-08-25 14:02:58 +000082 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000083}
Chris Lattner50dd2892008-02-26 00:51:44 +000084
85/// ActOnCXXThrow - Parse throw expressions.
86Action::ExprResult
87Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
88 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
89}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000090
91Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
92 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
93 /// is a non-lvalue expression whose value is the address of the object for
94 /// which the function is called.
95
96 if (!isa<FunctionDecl>(CurContext)) {
97 Diag(ThisLoc, diag::err_invalid_this_use);
98 return ExprResult(true);
99 }
100
101 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
102 if (MD->isInstance())
Douglas Gregor796da182008-11-04 14:32:21 +0000103 return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000104
105 return Diag(ThisLoc, diag::err_invalid_this_use);
106}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000107
108/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
109/// Can be interpreted either as function-style casting ("int(x)")
110/// or class type construction ("ClassType(x,y,z)")
111/// or creation of a value-initialized type ("int()").
112Action::ExprResult
113Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
114 SourceLocation LParenLoc,
115 ExprTy **ExprTys, unsigned NumExprs,
116 SourceLocation *CommaLocs,
117 SourceLocation RParenLoc) {
118 assert(TypeRep && "Missing type!");
119 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
120 Expr **Exprs = (Expr**)ExprTys;
121 SourceLocation TyBeginLoc = TypeRange.getBegin();
122 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
123
124 if (const RecordType *RT = Ty->getAsRecordType()) {
125 // C++ 5.2.3p1:
126 // If the simple-type-specifier specifies a class type, the class type shall
127 // be complete.
128 //
129 if (!RT->getDecl()->isDefinition())
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000130 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use)
Chris Lattnerd1625842008-11-24 06:25:27 +0000131 << Ty << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000132
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +0000133 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
134 "class constructors are not supported yet");
135 return Diag(TyBeginLoc, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000136 }
137
138 // C++ 5.2.3p1:
139 // If the expression list is a single expression, the type conversion
140 // expression is equivalent (in definedness, and if defined in meaning) to the
141 // corresponding cast expression.
142 //
143 if (NumExprs == 1) {
144 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
145 return true;
Douglas Gregor49badde2008-10-27 19:41:14 +0000146 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
147 Exprs[0], RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000148 }
149
150 // C++ 5.2.3p1:
151 // If the expression list specifies more than a single value, the type shall
152 // be a class with a suitably declared constructor.
153 //
154 if (NumExprs > 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000155 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg)
156 << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000157
158 assert(NumExprs == 0 && "Expected 0 expressions");
159
160 // C++ 5.2.3p2:
161 // The expression T(), where T is a simple-type-specifier for a non-array
162 // complete object type or the (possibly cv-qualified) void type, creates an
163 // rvalue of the specified type, which is value-initialized.
164 //
165 if (Ty->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000166 return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange;
Douglas Gregor898574e2008-12-05 23:32:09 +0000167 if (!Ty->isDependentType() && Ty->isIncompleteType() && !Ty->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000168 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use)
Douglas Gregor898574e2008-12-05 23:32:09 +0000169 << Ty << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000170
171 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
172}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000173
174
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000175/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
176/// @code new (memory) int[size][4] @endcode
177/// or
178/// @code ::new Foo(23, "hello") @endcode
179/// For the interpretation of this heap of arguments, consult the base version.
180Action::ExprResult
181Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
182 SourceLocation PlacementLParen,
183 ExprTy **PlacementArgs, unsigned NumPlaceArgs,
184 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000185 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000186 ExprTy **ConstructorArgs, unsigned NumConsArgs,
187 SourceLocation ConstructorRParen)
188{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000189 // FIXME: Throughout this function, we have rather bad location information.
190 // Implementing Declarator::getSourceRange() would go a long way toward
191 // fixing that.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000192
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000193 Expr *ArraySize = 0;
194 unsigned Skip = 0;
195 // If the specified type is an array, unwrap it and save the expression.
196 if (D.getNumTypeObjects() > 0 &&
197 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
198 DeclaratorChunk &Chunk = D.getTypeObject(0);
199 if (Chunk.Arr.hasStatic)
200 return Diag(Chunk.Loc, diag::err_static_illegal_in_new);
201 if (!Chunk.Arr.NumElts)
202 return Diag(Chunk.Loc, diag::err_array_new_needs_size);
203 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
204 Skip = 1;
205 }
206
207 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
208 if (D.getInvalidType())
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000209 return true;
210
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000211 if (CheckAllocatedType(AllocType, D))
212 return true;
213
214 QualType ResultType = Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000215
216 // That every array dimension except the first is constant was already
217 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000218
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000219 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
220 // or enumeration type with a non-negative value."
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000221 if (ArraySize) {
222 QualType SizeType = ArraySize->getType();
223 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
224 return Diag(ArraySize->getSourceRange().getBegin(),
225 diag::err_array_size_not_integral)
226 << SizeType << ArraySize->getSourceRange();
227 // Let's see if this is a constant < 0. If so, we reject it out of hand.
228 // We don't care about special rules, so we tell the machinery it's not
229 // evaluated - it gives us a result in more cases.
230 llvm::APSInt Value;
231 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
232 if (Value < llvm::APSInt(
233 llvm::APInt::getNullValue(Value.getBitWidth()), false))
234 return Diag(ArraySize->getSourceRange().getBegin(),
235 diag::err_typecheck_negative_array_size)
236 << ArraySize->getSourceRange();
237 }
238 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000239
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000240 FunctionDecl *OperatorNew = 0;
241 FunctionDecl *OperatorDelete = 0;
242 Expr **PlaceArgs = (Expr**)PlacementArgs;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000243 if (FindAllocationFunctions(StartLoc, UseGlobal, AllocType, ArraySize,
244 PlaceArgs, NumPlaceArgs, OperatorNew,
245 OperatorDelete))
246 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000247
248 bool Init = ConstructorLParen.isValid();
249 // --- Choosing a constructor ---
250 // C++ 5.3.4p15
251 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
252 // the object is not initialized. If the object, or any part of it, is
253 // const-qualified, it's an error.
254 // 2) If T is a POD and there's an empty initializer, the object is value-
255 // initialized.
256 // 3) If T is a POD and there's one initializer argument, the object is copy-
257 // constructed.
258 // 4) If T is a POD and there's more initializer arguments, it's an error.
259 // 5) If T is not a POD, the initializer arguments are used as constructor
260 // arguments.
261 //
262 // Or by the C++0x formulation:
263 // 1) If there's no initializer, the object is default-initialized according
264 // to C++0x rules.
265 // 2) Otherwise, the object is direct-initialized.
266 CXXConstructorDecl *Constructor = 0;
267 Expr **ConsArgs = (Expr**)ConstructorArgs;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000268 if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000269 // FIXME: This is incorrect for when there is an empty initializer and
270 // no user-defined constructor. Must zero-initialize, not default-construct.
271 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000272 AllocType, ConsArgs, NumConsArgs,
273 D.getDeclSpec().getSourceRange().getBegin(),
274 SourceRange(D.getDeclSpec().getSourceRange().getBegin(),
275 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000276 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000277 NumConsArgs != 0 ? IK_Direct : IK_Default);
278 if (!Constructor)
279 return true;
280 } else {
281 if (!Init) {
282 // FIXME: Check that no subpart is const.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000283 if (AllocType.isConstQualified()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000284 Diag(StartLoc, diag::err_new_uninitialized_const)
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000285 << D.getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000286 return true;
287 }
288 } else if (NumConsArgs == 0) {
289 // Object is value-initialized. Do nothing.
290 } else if (NumConsArgs == 1) {
291 // Object is direct-initialized.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000292 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000293 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
294 DeclarationName() /*AllocType.getAsString()*/))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000295 return true;
296 } else {
297 Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg)
298 << SourceRange(ConstructorLParen, ConstructorRParen);
299 }
300 }
301
302 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
303
304 return new CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000305 ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000306 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000307 StartLoc, Init ? ConstructorRParen : SourceLocation());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000308}
309
310/// CheckAllocatedType - Checks that a type is suitable as the allocated type
311/// in a new-expression.
312/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000313bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000314{
315 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
316 // abstract class type or array thereof.
317 // FIXME: We don't have abstract types yet.
318 // FIXME: Under C++ semantics, an incomplete object type is still an object
319 // type. This code assumes the C semantics, where it's not.
320 if (!AllocType->isObjectType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000321 unsigned type; // For the select in the message.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000322 if (AllocType->isFunctionType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000323 type = 0;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000324 } else if(AllocType->isIncompleteType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000325 type = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000326 } else {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000327 assert(AllocType->isReferenceType() && "What else could it be?");
328 type = 2;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000329 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000330 SourceRange TyR = D.getDeclSpec().getSourceRange();
331 // FIXME: This is very much a guess and won't work for, e.g., pointers.
332 if (D.getNumTypeObjects() > 0)
333 TyR.setEnd(D.getTypeObject(0).Loc);
334 Diag(TyR.getBegin(), diag::err_bad_new_type)
335 << AllocType.getAsString() << type << TyR;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000336 return true;
337 }
338
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000339 // Every dimension shall be of constant size.
340 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000341 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
342 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000343 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
344 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000345 return true;
346 }
347 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000348 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000349 }
350
351 return false;
352}
353
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000354/// FindAllocationFunctions - Finds the overloads of operator new and delete
355/// that are appropriate for the allocation.
356bool Sema::FindAllocationFunctions(SourceLocation StartLoc, bool UseGlobal,
357 QualType AllocType, bool IsArray,
358 Expr **PlaceArgs, unsigned NumPlaceArgs,
359 FunctionDecl *&OperatorNew,
360 FunctionDecl *&OperatorDelete)
361{
362 // --- Choosing an allocation function ---
363 // C++ 5.3.4p8 - 14 & 18
364 // 1) If UseGlobal is true, only look in the global scope. Else, also look
365 // in the scope of the allocated class.
366 // 2) If an array size is given, look for operator new[], else look for
367 // operator new.
368 // 3) The first argument is always size_t. Append the arguments from the
369 // placement form.
370 // FIXME: Also find the appropriate delete operator.
371
372 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
373 // We don't care about the actual value of this argument.
374 // FIXME: Should the Sema create the expression and embed it in the syntax
375 // tree? Or should the consumer just recalculate the value?
376 AllocArgs[0] = new IntegerLiteral(llvm::APInt::getNullValue(
377 Context.Target.getPointerWidth(0)),
378 Context.getSizeType(),
379 SourceLocation());
380 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
381
382 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
383 IsArray ? OO_Array_New : OO_New);
384 if (AllocType->isRecordType() && !UseGlobal) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000385 CXXRecordDecl *Record = cast<CXXRecordType>(AllocType->getAsRecordType())
386 ->getDecl();
387 // FIXME: We fail to find inherited overloads.
388 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
389 AllocArgs.size(), Record, /*AllowMissing=*/true,
390 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000391 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000392 }
393 if (!OperatorNew) {
394 // Didn't find a member overload. Look for a global one.
395 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000396 DeclContext *TUDecl = Context.getTranslationUnitDecl();
397 if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
398 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
399 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000400 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000401 }
402
Sebastian Redl7f662392008-12-04 22:20:51 +0000403 // FIXME: This is leaked on error. But so much is currently in Sema that it's
404 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000405 AllocArgs[0]->Destroy(Context);
406 return false;
407}
408
Sebastian Redl7f662392008-12-04 22:20:51 +0000409/// FindAllocationOverload - Find an fitting overload for the allocation
410/// function in the specified scope.
411bool Sema::FindAllocationOverload(SourceLocation StartLoc, DeclarationName Name,
412 Expr** Args, unsigned NumArgs,
413 DeclContext *Ctx, bool AllowMissing,
414 FunctionDecl *&Operator)
415{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000416 DeclContext::lookup_iterator Alloc, AllocEnd;
417 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Context, Name);
418 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000419 if (AllowMissing)
420 return false;
421 // FIXME: Bad location information.
422 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
423 << Name << 0;
424 }
425
426 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000427 for (; Alloc != AllocEnd; ++Alloc) {
428 // Even member operator new/delete are implicitly treated as
429 // static, so don't use AddMemberCandidate.
430 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
431 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
432 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000433 }
434
435 // Do the resolution.
436 OverloadCandidateSet::iterator Best;
437 switch(BestViableFunction(Candidates, Best)) {
438 case OR_Success: {
439 // Got one!
440 FunctionDecl *FnDecl = Best->Function;
441 // The first argument is size_t, and the first parameter must be size_t,
442 // too. This is checked on declaration and can be assumed. (It can't be
443 // asserted on, though, since invalid decls are left in there.)
444 for (unsigned i = 1; i < NumArgs; ++i) {
445 // FIXME: Passing word to diagnostic.
446 if (PerformCopyInitialization(Args[i-1],
447 FnDecl->getParamDecl(i)->getType(),
448 "passing"))
449 return true;
450 }
451 Operator = FnDecl;
452 return false;
453 }
454
455 case OR_No_Viable_Function:
456 if (AllowMissing)
457 return false;
458 // FIXME: Bad location information.
459 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
460 << Name << (unsigned)Candidates.size();
461 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
462 return true;
463
464 case OR_Ambiguous:
465 // FIXME: Bad location information.
466 Diag(StartLoc, diag::err_ovl_ambiguous_call)
467 << Name;
468 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
469 return true;
470 }
471 assert(false && "Unreachable, bad result from BestViableFunction");
472 return true;
473}
474
475
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000476/// DeclareGlobalNewDelete - Declare the global forms of operator new and
477/// delete. These are:
478/// @code
479/// void* operator new(std::size_t) throw(std::bad_alloc);
480/// void* operator new[](std::size_t) throw(std::bad_alloc);
481/// void operator delete(void *) throw();
482/// void operator delete[](void *) throw();
483/// @endcode
484/// Note that the placement and nothrow forms of new are *not* implicitly
485/// declared. Their use requires including \<new\>.
486void Sema::DeclareGlobalNewDelete()
487{
488 if (GlobalNewDeleteDeclared)
489 return;
490 GlobalNewDeleteDeclared = true;
491
492 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
493 QualType SizeT = Context.getSizeType();
494
495 // FIXME: Exception specifications are not added.
496 DeclareGlobalAllocationFunction(
497 Context.DeclarationNames.getCXXOperatorName(OO_New),
498 VoidPtr, SizeT);
499 DeclareGlobalAllocationFunction(
500 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
501 VoidPtr, SizeT);
502 DeclareGlobalAllocationFunction(
503 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
504 Context.VoidTy, VoidPtr);
505 DeclareGlobalAllocationFunction(
506 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
507 Context.VoidTy, VoidPtr);
508}
509
510/// DeclareGlobalAllocationFunction - Declares a single implicit global
511/// allocation function if it doesn't already exist.
512void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
513 QualType Return, QualType Argument)
514{
515 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
516
517 // Check if this function is already declared.
518 IdentifierResolver::iterator I = IdResolver.begin(Name, GlobalCtx,
519 /*CheckParent=*/false);
520
521 if (I != IdResolver.end()) {
522 NamedDecl *Decl = *I;
523 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(Decl)) {
524 // The return type fits. This is checked when the function is declared.
525 if (Fn->getNumParams() == 1 &&
526 Context.getCanonicalType(Fn->getParamDecl(0)->getType()) == Argument)
527 return;
528 } else if(OverloadedFunctionDecl *Ovl =
529 dyn_cast<OverloadedFunctionDecl>(Decl)) {
530 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
531 FEnd = Ovl->function_end();
532 F != FEnd; ++F) {
533 if ((*F)->getNumParams() == 1 &&
534 Context.getCanonicalType((*F)->getParamDecl(0)->getType())
535 == Argument)
536 return;
537 }
538 }
539 }
540
541 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
542 FunctionDecl *Alloc =
543 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
544 FnType, FunctionDecl::None, false, 0,
545 SourceLocation());
546 Alloc->setImplicit();
547 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
548 0, Argument, VarDecl::None, 0, 0);
549 Alloc->setParams(&Param, 1);
550
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000551 ((DeclContext *)TUScope->getEntity())->addDecl(Context, Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000552}
553
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000554/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
555/// @code ::delete ptr; @endcode
556/// or
557/// @code delete [] ptr; @endcode
558Action::ExprResult
559Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
560 bool ArrayForm, ExprTy *Operand)
561{
562 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
563 // having a single conversion function to a pointer type. The result has
564 // type void."
565 // DR599 amends "pointer type" to "pointer to object type" in both cases.
566
567 Expr *Ex = (Expr *)Operand;
568 QualType Type = Ex->getType();
569
570 if (Type->isRecordType()) {
571 // FIXME: Find that one conversion function and amend the type.
572 }
573
574 if (!Type->isPointerType()) {
Chris Lattnerd1625842008-11-24 06:25:27 +0000575 Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000576 return true;
577 }
578
579 QualType Pointee = Type->getAsPointerType()->getPointeeType();
580 if (Pointee->isIncompleteType() && !Pointee->isVoidType())
581 Diag(StartLoc, diag::warn_delete_incomplete)
Chris Lattnerd1625842008-11-24 06:25:27 +0000582 << Pointee << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000583 else if (!Pointee->isObjectType()) {
584 Diag(StartLoc, diag::err_delete_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +0000585 << Type << Ex->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000586 return true;
587 }
588
589 // FIXME: Look up the correct operator delete overload and pass a pointer
590 // along.
591 // FIXME: Check access and ambiguity of operator delete and destructor.
592
593 return new CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0, Ex,
594 StartLoc);
595}
596
597
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000598/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
599/// C++ if/switch/while/for statement.
600/// e.g: "if (int x = f()) {...}"
601Action::ExprResult
602Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
603 Declarator &D,
604 SourceLocation EqualLoc,
605 ExprTy *AssignExprVal) {
606 assert(AssignExprVal && "Null assignment expression");
607
608 // C++ 6.4p2:
609 // The declarator shall not specify a function or an array.
610 // The type-specifier-seq shall not contain typedef and shall not declare a
611 // new class or enumeration.
612
613 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
614 "Parser allowed 'typedef' as storage class of condition decl.");
615
616 QualType Ty = GetTypeForDeclarator(D, S);
617
618 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
619 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
620 // would be created and CXXConditionDeclExpr wants a VarDecl.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000621 return Diag(StartLoc, diag::err_invalid_use_of_function_type)
622 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000623 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000624 Diag(StartLoc, diag::err_invalid_use_of_array_type)
625 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000626 } else if (const RecordType *RT = Ty->getAsRecordType()) {
627 RecordDecl *RD = RT->getDecl();
628 // The type-specifier-seq shall not declare a new class...
629 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
630 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
631 } else if (const EnumType *ET = Ty->getAsEnumType()) {
632 EnumDecl *ED = ET->getDecl();
633 // ...or enumeration.
634 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
635 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
636 }
637
638 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
639 if (!Dcl)
640 return true;
Sebastian Redl798d1192008-12-13 16:23:55 +0000641 AddInitializerToDecl(Dcl, ExprArg(*this, AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000642
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000643 // Mark this variable as one that is declared within a conditional.
644 if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl))
645 VD->setDeclaredInCondition(true);
646
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000647 return new CXXConditionDeclExpr(StartLoc, EqualLoc,
648 cast<VarDecl>(static_cast<Decl *>(Dcl)));
649}
650
651/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
652bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
653 // C++ 6.4p4:
654 // The value of a condition that is an initialized declaration in a statement
655 // other than a switch statement is the value of the declared variable
656 // implicitly converted to type bool. If that conversion is ill-formed, the
657 // program is ill-formed.
658 // The value of a condition that is an expression is the value of the
659 // expression, implicitly converted to bool.
660 //
661 QualType Ty = CondExpr->getType(); // Save the type.
662 AssignConvertType
663 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
664 if (ConvTy == Incompatible)
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000665 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition)
Chris Lattnerd1625842008-11-24 06:25:27 +0000666 << Ty << CondExpr->getSourceRange();
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000667 return false;
668}
Douglas Gregor77a52232008-09-12 00:47:35 +0000669
670/// Helper function to determine whether this is the (deprecated) C++
671/// conversion from a string literal to a pointer to non-const char or
672/// non-const wchar_t (for narrow and wide string literals,
673/// respectively).
674bool
675Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
676 // Look inside the implicit cast, if it exists.
677 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
678 From = Cast->getSubExpr();
679
680 // A string literal (2.13.4) that is not a wide string literal can
681 // be converted to an rvalue of type "pointer to char"; a wide
682 // string literal can be converted to an rvalue of type "pointer
683 // to wchar_t" (C++ 4.2p2).
684 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
685 if (const PointerType *ToPtrType = ToType->getAsPointerType())
686 if (const BuiltinType *ToPointeeType
687 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
688 // This conversion is considered only when there is an
689 // explicit appropriate pointer target type (C++ 4.2p2).
690 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
691 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
692 (!StrLit->isWide() &&
693 (ToPointeeType->getKind() == BuiltinType::Char_U ||
694 ToPointeeType->getKind() == BuiltinType::Char_S))))
695 return true;
696 }
697
698 return false;
699}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000700
701/// PerformImplicitConversion - Perform an implicit conversion of the
702/// expression From to the type ToType. Returns true if there was an
703/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000704/// converted expression. Flavor is the kind of conversion we're
705/// performing, used in the error message.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000706bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000707Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
708 const char *Flavor)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000709{
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000710 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000711 switch (ICS.ConversionKind) {
712 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000713 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000714 return true;
715 break;
716
717 case ImplicitConversionSequence::UserDefinedConversion:
718 // FIXME: This is, of course, wrong. We'll need to actually call
719 // the constructor or conversion operator, and then cope with the
720 // standard conversions.
721 ImpCastExprToType(From, ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000722 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000723
724 case ImplicitConversionSequence::EllipsisConversion:
725 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000726 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000727
728 case ImplicitConversionSequence::BadConversion:
729 return true;
730 }
731
732 // Everything went well.
733 return false;
734}
735
736/// PerformImplicitConversion - Perform an implicit conversion of the
737/// expression From to the type ToType by following the standard
738/// conversion sequence SCS. Returns true if there was an error, false
739/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000740/// expression. Flavor is the context in which we're performing this
741/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000742bool
743Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000744 const StandardConversionSequence& SCS,
745 const char *Flavor)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000746{
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:
Douglas Gregor45920e82008-12-19 17:40:08 +0000808 if (SCS.IncompatibleObjC) {
809 // Diagnose incompatible Objective-C conversions
810 Diag(From->getSourceRange().getBegin(),
811 diag::ext_typecheck_convert_incompatible_pointer)
812 << From->getType() << ToType << Flavor
813 << From->getSourceRange();
814 }
815
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000816 if (CheckPointerConversion(From, ToType))
817 return true;
818 ImpCastExprToType(From, ToType);
819 break;
820
821 case ICK_Pointer_Member:
822 // FIXME: Implement pointer-to-member conversions.
823 assert(false && "Pointer-to-member conversions are unsupported");
824 break;
825
826 case ICK_Boolean_Conversion:
827 FromType = Context.BoolTy;
828 ImpCastExprToType(From, FromType);
829 break;
830
831 default:
832 assert(false && "Improper second standard conversion");
833 break;
834 }
835
836 switch (SCS.Third) {
837 case ICK_Identity:
838 // Nothing to do.
839 break;
840
841 case ICK_Qualification:
842 ImpCastExprToType(From, ToType);
843 break;
844
845 default:
846 assert(false && "Improper second standard conversion");
847 break;
848 }
849
850 return false;
851}
852