blob: e5a252043ed9f3a1f484193be582fcf9995be7b2 [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
Sebastian Redl7c8bd602009-02-07 20:10:22 +000014#include "SemaInherit.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "Sema.h"
16#include "clang/AST/ExprCXX.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000018#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000019#include "clang/Lex/Preprocessor.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.
Sebastian Redlcd965b92009-01-18 18:53:16 +000029Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000030Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31 TypeTy *Ty, bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000032 const CXXScopeSpec &SS,
33 bool isAddressOfOperand) {
Douglas Gregor2def4832008-11-17 20:34:05 +000034 QualType ConvType = QualType::getFromOpaquePtr(Ty);
35 QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36 DeclarationName ConvName
37 = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
Sebastian Redlcd965b92009-01-18 18:53:16 +000038 return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +000039 &SS, isAddressOfOperand);
Douglas Gregor2def4832008-11-17 20:34:05 +000040}
Sebastian Redlc42e1182008-11-11 11:37:55 +000041
Douglas Gregor487a75a2008-11-19 19:09:45 +000042/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
Douglas Gregore94ca9e42008-11-18 14:39:36 +000043/// name (e.g., @c operator+ ) as an expression. This is very
44/// similar to ActOnIdentifierExpr, except that instead of providing
45/// an identifier the parser provides the kind of overloaded
46/// operator that was parsed.
Sebastian Redlcd965b92009-01-18 18:53:16 +000047Sema::OwningExprResult
Douglas Gregor487a75a2008-11-19 19:09:45 +000048Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49 OverloadedOperatorKind Op,
50 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +000051 const CXXScopeSpec &SS,
52 bool isAddressOfOperand) {
Douglas Gregore94ca9e42008-11-18 14:39:36 +000053 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
Sebastian Redlebc07d52009-02-03 20:19:35 +000054 return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
Douglas Gregor17330012009-02-04 15:01:18 +000055 isAddressOfOperand);
Douglas Gregore94ca9e42008-11-18 14:39:36 +000056}
57
Sebastian Redlc42e1182008-11-11 11:37:55 +000058/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
59Action::ExprResult
60Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +000062 NamespaceDecl *StdNs = GetStdNamespace();
Chris Lattner572af492008-11-20 05:51:55 +000063 if (!StdNs)
64 return Diag(OpLoc, diag::err_need_header_before_typeid);
65
66 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
Douglas Gregor4c921ae2009-01-30 01:04:22 +000067 Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
Sebastian Redlc42e1182008-11-11 11:37:55 +000068 RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
Chris Lattner572af492008-11-20 05:51:55 +000069 if (!TypeInfoRecordDecl)
70 return Diag(OpLoc, diag::err_need_header_before_typeid);
Sebastian Redlc42e1182008-11-11 11:37:55 +000071
72 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
Ted Kremenek8189cde2009-02-07 01:47:29 +000074 return new (Context) CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
75 SourceRange(OpLoc, RParenLoc));
Sebastian Redlc42e1182008-11-11 11:37:55 +000076}
77
Steve Naroff1b273c42007-09-16 14:56:35 +000078/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Reid Spencer5f016e22007-07-11 17:01:13 +000079Action::ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000080Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +000081 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +000082 "Unknown C++ Boolean value!");
Ted Kremenek8189cde2009-02-07 01:47:29 +000083 return new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000084}
Chris Lattner50dd2892008-02-26 00:51:44 +000085
86/// ActOnCXXThrow - Parse throw expressions.
87Action::ExprResult
88Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
Ted Kremenek8189cde2009-02-07 01:47:29 +000089 return new (Context) CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
Chris Lattner50dd2892008-02-26 00:51:44 +000090}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000091
92Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
93 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
94 /// is a non-lvalue expression whose value is the address of the object for
95 /// which the function is called.
96
97 if (!isa<FunctionDecl>(CurContext)) {
98 Diag(ThisLoc, diag::err_invalid_this_use);
99 return ExprResult(true);
100 }
101
102 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
103 if (MD->isInstance())
Ted Kremenek8189cde2009-02-07 01:47:29 +0000104 return new (Context) CXXThisExpr(ThisLoc, MD->getThisType(Context));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000105
106 return Diag(ThisLoc, diag::err_invalid_this_use);
107}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000108
109/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
110/// Can be interpreted either as function-style casting ("int(x)")
111/// or class type construction ("ClassType(x,y,z)")
112/// or creation of a value-initialized type ("int()").
113Action::ExprResult
114Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
115 SourceLocation LParenLoc,
116 ExprTy **ExprTys, unsigned NumExprs,
117 SourceLocation *CommaLocs,
118 SourceLocation RParenLoc) {
119 assert(TypeRep && "Missing type!");
120 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
121 Expr **Exprs = (Expr**)ExprTys;
122 SourceLocation TyBeginLoc = TypeRange.getBegin();
123 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
124
Douglas Gregorba498172009-03-13 21:01:28 +0000125 if (Ty->isDependentType() ||
126 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
127 return new (Context) CXXTemporaryObjectExpr(0, Ty, TyBeginLoc,
128 Exprs, NumExprs, RParenLoc);
129 }
130
131
Douglas Gregor506ae412009-01-16 18:33:17 +0000132 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000133 // If the expression list is a single expression, the type conversion
134 // expression is equivalent (in definedness, and if defined in meaning) to the
135 // corresponding cast expression.
136 //
137 if (NumExprs == 1) {
138 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
139 return true;
Ted Kremenek8189cde2009-02-07 01:47:29 +0000140 return new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty,
141 TyBeginLoc, Exprs[0], RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000142 }
143
Douglas Gregor506ae412009-01-16 18:33:17 +0000144 if (const RecordType *RT = Ty->getAsRecordType()) {
145 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
146
147 if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
148 CXXConstructorDecl *Constructor
149 = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
150 TypeRange.getBegin(),
151 SourceRange(TypeRange.getBegin(),
152 RParenLoc),
153 DeclarationName(),
154 IK_Direct);
155
156 if (!Constructor)
157 return true;
158
Ted Kremenek8189cde2009-02-07 01:47:29 +0000159 return new (Context) CXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
Douglas Gregor506ae412009-01-16 18:33:17 +0000160 Exprs, NumExprs, RParenLoc);
161 }
162
163 // Fall through to value-initialize an object of class type that
164 // doesn't have a user-declared default constructor.
165 }
166
167 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000168 // If the expression list specifies more than a single value, the type shall
169 // be a class with a suitably declared constructor.
170 //
171 if (NumExprs > 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000172 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg)
173 << FullRange;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000174
175 assert(NumExprs == 0 && "Expected 0 expressions");
176
Douglas Gregor506ae412009-01-16 18:33:17 +0000177 // C++ [expr.type.conv]p2:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000178 // The expression T(), where T is a simple-type-specifier for a non-array
179 // complete object type or the (possibly cv-qualified) void type, creates an
180 // rvalue of the specified type, which is value-initialized.
181 //
182 if (Ty->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000183 return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange;
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000184 if (!Ty->isDependentType() && !Ty->isVoidType() &&
Douglas Gregor86447ec2009-03-09 16:13:40 +0000185 RequireCompleteType(TyBeginLoc, Ty,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000186 diag::err_invalid_incomplete_type_use, FullRange))
187 return true;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000188
Ted Kremenek8189cde2009-02-07 01:47:29 +0000189 return new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000190}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000191
192
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000193/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
194/// @code new (memory) int[size][4] @endcode
195/// or
196/// @code ::new Foo(23, "hello") @endcode
197/// For the interpretation of this heap of arguments, consult the base version.
198Action::ExprResult
199Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
200 SourceLocation PlacementLParen,
201 ExprTy **PlacementArgs, unsigned NumPlaceArgs,
202 SourceLocation PlacementRParen, bool ParenTypeId,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000203 Declarator &D, SourceLocation ConstructorLParen,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000204 ExprTy **ConstructorArgs, unsigned NumConsArgs,
205 SourceLocation ConstructorRParen)
206{
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000207 Expr *ArraySize = 0;
208 unsigned Skip = 0;
209 // If the specified type is an array, unwrap it and save the expression.
210 if (D.getNumTypeObjects() > 0 &&
211 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
212 DeclaratorChunk &Chunk = D.getTypeObject(0);
213 if (Chunk.Arr.hasStatic)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000214 return Diag(Chunk.Loc, diag::err_static_illegal_in_new)
215 << D.getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000216 if (!Chunk.Arr.NumElts)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000217 return Diag(Chunk.Loc, diag::err_array_new_needs_size)
218 << D.getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000219 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
220 Skip = 1;
221 }
222
223 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
224 if (D.getInvalidType())
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000225 return true;
226
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000227 if (CheckAllocatedType(AllocType, D))
228 return true;
229
Sebastian Redl28507842009-02-26 14:39:58 +0000230 QualType ResultType = AllocType->isDependentType()
231 ? Context.DependentTy
232 : Context.getPointerType(AllocType);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000233
234 // That every array dimension except the first is constant was already
235 // checked by the type check above.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000236
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000237 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
238 // or enumeration type with a non-negative value."
Sebastian Redl28507842009-02-26 14:39:58 +0000239 if (ArraySize && !ArraySize->isTypeDependent()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000240 QualType SizeType = ArraySize->getType();
241 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
242 return Diag(ArraySize->getSourceRange().getBegin(),
243 diag::err_array_size_not_integral)
244 << SizeType << ArraySize->getSourceRange();
245 // Let's see if this is a constant < 0. If so, we reject it out of hand.
246 // We don't care about special rules, so we tell the machinery it's not
247 // evaluated - it gives us a result in more cases.
Sebastian Redl28507842009-02-26 14:39:58 +0000248 if (!ArraySize->isValueDependent()) {
249 llvm::APSInt Value;
250 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
251 if (Value < llvm::APSInt(
252 llvm::APInt::getNullValue(Value.getBitWidth()), false))
253 return Diag(ArraySize->getSourceRange().getBegin(),
254 diag::err_typecheck_negative_array_size)
255 << ArraySize->getSourceRange();
256 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000257 }
258 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000259
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000260 FunctionDecl *OperatorNew = 0;
261 FunctionDecl *OperatorDelete = 0;
262 Expr **PlaceArgs = (Expr**)PlacementArgs;
Sebastian Redl28507842009-02-26 14:39:58 +0000263 if (!AllocType->isDependentType() &&
264 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
265 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000266 SourceRange(PlacementLParen, PlacementRParen),
267 UseGlobal, AllocType, ArraySize, PlaceArgs,
268 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000269 return true;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000270
271 bool Init = ConstructorLParen.isValid();
272 // --- Choosing a constructor ---
273 // C++ 5.3.4p15
274 // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
275 // the object is not initialized. If the object, or any part of it, is
276 // const-qualified, it's an error.
277 // 2) If T is a POD and there's an empty initializer, the object is value-
278 // initialized.
279 // 3) If T is a POD and there's one initializer argument, the object is copy-
280 // constructed.
281 // 4) If T is a POD and there's more initializer arguments, it's an error.
282 // 5) If T is not a POD, the initializer arguments are used as constructor
283 // arguments.
284 //
285 // Or by the C++0x formulation:
286 // 1) If there's no initializer, the object is default-initialized according
287 // to C++0x rules.
288 // 2) Otherwise, the object is direct-initialized.
289 CXXConstructorDecl *Constructor = 0;
290 Expr **ConsArgs = (Expr**)ConstructorArgs;
Sebastian Redl28507842009-02-26 14:39:58 +0000291 if (AllocType->isDependentType()) {
292 // Skip all the checks.
293 }
Sebastian Redl00e68e22009-02-09 18:24:27 +0000294 // FIXME: Should check for primitive/aggregate here, not record.
Sebastian Redl28507842009-02-26 14:39:58 +0000295 else if (const RecordType *RT = AllocType->getAsRecordType()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000296 // FIXME: This is incorrect for when there is an empty initializer and
297 // no user-defined constructor. Must zero-initialize, not default-construct.
298 Constructor = PerformInitializationByConstructor(
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000299 AllocType, ConsArgs, NumConsArgs,
Sebastian Redl00e68e22009-02-09 18:24:27 +0000300 D.getSourceRange().getBegin(),
301 SourceRange(D.getSourceRange().getBegin(),
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000302 ConstructorRParen),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000303 RT->getDecl()->getDeclName(),
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000304 NumConsArgs != 0 ? IK_Direct : IK_Default);
305 if (!Constructor)
306 return true;
307 } else {
308 if (!Init) {
309 // FIXME: Check that no subpart is const.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000310 if (AllocType.isConstQualified()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000311 Diag(StartLoc, diag::err_new_uninitialized_const)
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000312 << D.getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000313 return true;
314 }
315 } else if (NumConsArgs == 0) {
316 // Object is value-initialized. Do nothing.
317 } else if (NumConsArgs == 1) {
318 // Object is direct-initialized.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000319 // FIXME: WHAT DeclarationName do we pass in here?
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000320 if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000321 DeclarationName() /*AllocType.getAsString()*/,
322 /*DirectInit=*/true))
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000323 return true;
324 } else {
325 Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg)
326 << SourceRange(ConstructorLParen, ConstructorRParen);
327 }
328 }
329
330 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
331
Ted Kremenek8189cde2009-02-07 01:47:29 +0000332 return new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
333 NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000334 ConsArgs, NumConsArgs, OperatorDelete, ResultType,
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000335 StartLoc, Init ? ConstructorRParen : SourceLocation());
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000336}
337
338/// CheckAllocatedType - Checks that a type is suitable as the allocated type
339/// in a new-expression.
340/// dimension off and stores the size expression in ArraySize.
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000341bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000342{
343 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
344 // abstract class type or array thereof.
345 // FIXME: We don't have abstract types yet.
346 // FIXME: Under C++ semantics, an incomplete object type is still an object
347 // type. This code assumes the C semantics, where it's not.
348 if (!AllocType->isObjectType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000349 unsigned type; // For the select in the message.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000350 if (AllocType->isFunctionType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000351 type = 0;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000352 } else if(AllocType->isIncompleteType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000353 type = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000354 } else {
Sebastian Redl00e68e22009-02-09 18:24:27 +0000355 assert(AllocType->isReferenceType() && "Unhandled non-object type.");
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000356 type = 2;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000357 }
Sebastian Redl00e68e22009-02-09 18:24:27 +0000358 Diag(D.getSourceRange().getBegin(), diag::err_bad_new_type)
359 << AllocType << type << D.getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000360 return true;
361 }
362
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000363 // Every dimension shall be of constant size.
364 unsigned i = 1;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000365 while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
366 if (!Array->isConstantArrayType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000367 Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
368 << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000369 return true;
370 }
371 AllocType = Array->getElementType();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000372 ++i;
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000373 }
374
375 return false;
376}
377
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000378/// FindAllocationFunctions - Finds the overloads of operator new and delete
379/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000380bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
381 bool UseGlobal, QualType AllocType,
382 bool IsArray, Expr **PlaceArgs,
383 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000384 FunctionDecl *&OperatorNew,
385 FunctionDecl *&OperatorDelete)
386{
387 // --- Choosing an allocation function ---
388 // C++ 5.3.4p8 - 14 & 18
389 // 1) If UseGlobal is true, only look in the global scope. Else, also look
390 // in the scope of the allocated class.
391 // 2) If an array size is given, look for operator new[], else look for
392 // operator new.
393 // 3) The first argument is always size_t. Append the arguments from the
394 // placement form.
395 // FIXME: Also find the appropriate delete operator.
396
397 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
398 // We don't care about the actual value of this argument.
399 // FIXME: Should the Sema create the expression and embed it in the syntax
400 // tree? Or should the consumer just recalculate the value?
Ted Kremenek8189cde2009-02-07 01:47:29 +0000401 AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000402 Context.Target.getPointerWidth(0)),
403 Context.getSizeType(),
404 SourceLocation());
405 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
406
407 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
408 IsArray ? OO_Array_New : OO_New);
409 if (AllocType->isRecordType() && !UseGlobal) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +0000410 CXXRecordDecl *Record
411 = cast<CXXRecordDecl>(AllocType->getAsRecordType()->getDecl());
Sebastian Redl7f662392008-12-04 22:20:51 +0000412 // FIXME: We fail to find inherited overloads.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000413 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000414 AllocArgs.size(), Record, /*AllowMissing=*/true,
415 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000416 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000417 }
418 if (!OperatorNew) {
419 // Didn't find a member overload. Look for a global one.
420 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +0000421 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +0000422 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +0000423 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
424 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000425 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000426 }
427
Sebastian Redl7f662392008-12-04 22:20:51 +0000428 // FIXME: This is leaked on error. But so much is currently in Sema that it's
429 // easier to clean it in one go.
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000430 AllocArgs[0]->Destroy(Context);
431 return false;
432}
433
Sebastian Redl7f662392008-12-04 22:20:51 +0000434/// FindAllocationOverload - Find an fitting overload for the allocation
435/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +0000436bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
437 DeclarationName Name, Expr** Args,
438 unsigned NumArgs, DeclContext *Ctx,
439 bool AllowMissing, FunctionDecl *&Operator)
Sebastian Redl7f662392008-12-04 22:20:51 +0000440{
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000441 DeclContext::lookup_iterator Alloc, AllocEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000442 llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000443 if (Alloc == AllocEnd) {
Sebastian Redl7f662392008-12-04 22:20:51 +0000444 if (AllowMissing)
445 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000446 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000447 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000448 }
449
450 OverloadCandidateSet Candidates;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000451 for (; Alloc != AllocEnd; ++Alloc) {
452 // Even member operator new/delete are implicitly treated as
453 // static, so don't use AddMemberCandidate.
454 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
455 AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
456 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +0000457 }
458
459 // Do the resolution.
460 OverloadCandidateSet::iterator Best;
461 switch(BestViableFunction(Candidates, Best)) {
462 case OR_Success: {
463 // Got one!
464 FunctionDecl *FnDecl = Best->Function;
465 // The first argument is size_t, and the first parameter must be size_t,
466 // too. This is checked on declaration and can be assumed. (It can't be
467 // asserted on, though, since invalid decls are left in there.)
468 for (unsigned i = 1; i < NumArgs; ++i) {
469 // FIXME: Passing word to diagnostic.
470 if (PerformCopyInitialization(Args[i-1],
471 FnDecl->getParamDecl(i)->getType(),
472 "passing"))
473 return true;
474 }
475 Operator = FnDecl;
476 return false;
477 }
478
479 case OR_No_Viable_Function:
480 if (AllowMissing)
481 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +0000482 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +0000483 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000484 PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
485 return true;
486
487 case OR_Ambiguous:
Sebastian Redl7f662392008-12-04 22:20:51 +0000488 Diag(StartLoc, diag::err_ovl_ambiguous_call)
Sebastian Redl00e68e22009-02-09 18:24:27 +0000489 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +0000490 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
491 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000492
493 case OR_Deleted:
494 Diag(StartLoc, diag::err_ovl_deleted_call)
495 << Best->Function->isDeleted()
496 << Name << Range;
497 PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
498 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +0000499 }
500 assert(false && "Unreachable, bad result from BestViableFunction");
501 return true;
502}
503
504
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000505/// DeclareGlobalNewDelete - Declare the global forms of operator new and
506/// delete. These are:
507/// @code
508/// void* operator new(std::size_t) throw(std::bad_alloc);
509/// void* operator new[](std::size_t) throw(std::bad_alloc);
510/// void operator delete(void *) throw();
511/// void operator delete[](void *) throw();
512/// @endcode
513/// Note that the placement and nothrow forms of new are *not* implicitly
514/// declared. Their use requires including \<new\>.
515void Sema::DeclareGlobalNewDelete()
516{
517 if (GlobalNewDeleteDeclared)
518 return;
519 GlobalNewDeleteDeclared = true;
520
521 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
522 QualType SizeT = Context.getSizeType();
523
524 // FIXME: Exception specifications are not added.
525 DeclareGlobalAllocationFunction(
526 Context.DeclarationNames.getCXXOperatorName(OO_New),
527 VoidPtr, SizeT);
528 DeclareGlobalAllocationFunction(
529 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
530 VoidPtr, SizeT);
531 DeclareGlobalAllocationFunction(
532 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
533 Context.VoidTy, VoidPtr);
534 DeclareGlobalAllocationFunction(
535 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
536 Context.VoidTy, VoidPtr);
537}
538
539/// DeclareGlobalAllocationFunction - Declares a single implicit global
540/// allocation function if it doesn't already exist.
541void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
542 QualType Return, QualType Argument)
543{
544 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
545
546 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000547 {
Douglas Gregor5cc37092008-12-23 22:05:29 +0000548 DeclContext::lookup_iterator Alloc, AllocEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000549 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000550 Alloc != AllocEnd; ++Alloc) {
551 // FIXME: Do we need to check for default arguments here?
552 FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
553 if (Func->getNumParams() == 1 &&
Ted Kremenek8189cde2009-02-07 01:47:29 +0000554 Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000555 return;
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000556 }
557 }
558
559 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
560 FunctionDecl *Alloc =
561 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
Douglas Gregor2224f842009-02-25 16:33:18 +0000562 FnType, FunctionDecl::None, false, true,
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000563 SourceLocation());
564 Alloc->setImplicit();
565 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000566 0, Argument, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000567 Alloc->setParams(Context, &Param, 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000568
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000569 // FIXME: Also add this declaration to the IdentifierResolver, but
570 // make sure it is at the end of the chain to coincide with the
571 // global scope.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000572 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000573}
574
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000575/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
576/// @code ::delete ptr; @endcode
577/// or
578/// @code delete [] ptr; @endcode
579Action::ExprResult
580Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
581 bool ArrayForm, ExprTy *Operand)
582{
583 // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
584 // having a single conversion function to a pointer type. The result has
585 // type void."
586 // DR599 amends "pointer type" to "pointer to object type" in both cases.
587
588 Expr *Ex = (Expr *)Operand;
Sebastian Redl28507842009-02-26 14:39:58 +0000589 if (!Ex->isTypeDependent()) {
590 QualType Type = Ex->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000591
Sebastian Redl28507842009-02-26 14:39:58 +0000592 if (Type->isRecordType()) {
593 // FIXME: Find that one conversion function and amend the type.
594 }
595
596 if (!Type->isPointerType()) {
597 Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange();
598 return true;
599 }
600
601 QualType Pointee = Type->getAsPointerType()->getPointeeType();
602 if (!Pointee->isVoidType() &&
Douglas Gregor86447ec2009-03-09 16:13:40 +0000603 RequireCompleteType(StartLoc, Pointee, diag::warn_delete_incomplete,
Sebastian Redl28507842009-02-26 14:39:58 +0000604 Ex->getSourceRange()))
605 return true;
606 else if (!Pointee->isObjectType()) {
607 Diag(StartLoc, diag::err_delete_operand)
608 << Type << Ex->getSourceRange();
609 return true;
610 }
611
612 // FIXME: Look up the correct operator delete overload and pass a pointer
613 // along.
614 // FIXME: Check access and ambiguity of operator delete and destructor.
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000615 }
616
Ted Kremenek8189cde2009-02-07 01:47:29 +0000617 return new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0,
618 Ex, StartLoc);
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000619}
620
621
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000622/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
623/// C++ if/switch/while/for statement.
624/// e.g: "if (int x = f()) {...}"
625Action::ExprResult
626Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
627 Declarator &D,
628 SourceLocation EqualLoc,
629 ExprTy *AssignExprVal) {
630 assert(AssignExprVal && "Null assignment expression");
631
632 // C++ 6.4p2:
633 // The declarator shall not specify a function or an array.
634 // The type-specifier-seq shall not contain typedef and shall not declare a
635 // new class or enumeration.
636
637 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
638 "Parser allowed 'typedef' as storage class of condition decl.");
639
640 QualType Ty = GetTypeForDeclarator(D, S);
641
642 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
643 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
644 // would be created and CXXConditionDeclExpr wants a VarDecl.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000645 return Diag(StartLoc, diag::err_invalid_use_of_function_type)
646 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000647 } else if (Ty->isArrayType()) { // ...or an array.
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000648 Diag(StartLoc, diag::err_invalid_use_of_array_type)
649 << SourceRange(StartLoc, EqualLoc);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000650 } else if (const RecordType *RT = Ty->getAsRecordType()) {
651 RecordDecl *RD = RT->getDecl();
652 // The type-specifier-seq shall not declare a new class...
653 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
654 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
655 } else if (const EnumType *ET = Ty->getAsEnumType()) {
656 EnumDecl *ED = ET->getDecl();
657 // ...or enumeration.
658 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
659 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
660 }
661
662 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
663 if (!Dcl)
664 return true;
Sebastian Redl798d1192008-12-13 16:23:55 +0000665 AddInitializerToDecl(Dcl, ExprArg(*this, AssignExprVal));
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000666
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000667 // Mark this variable as one that is declared within a conditional.
668 if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl))
669 VD->setDeclaredInCondition(true);
670
Ted Kremenek8189cde2009-02-07 01:47:29 +0000671 return new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc,
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000672 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 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000685 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000686}
Douglas Gregor77a52232008-09-12 00:47:35 +0000687
688/// Helper function to determine whether this is the (deprecated) C++
689/// conversion from a string literal to a pointer to non-const char or
690/// non-const wchar_t (for narrow and wide string literals,
691/// respectively).
692bool
693Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
694 // Look inside the implicit cast, if it exists.
695 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
696 From = Cast->getSubExpr();
697
698 // A string literal (2.13.4) that is not a wide string literal can
699 // be converted to an rvalue of type "pointer to char"; a wide
700 // string literal can be converted to an rvalue of type "pointer
701 // to wchar_t" (C++ 4.2p2).
702 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
703 if (const PointerType *ToPtrType = ToType->getAsPointerType())
704 if (const BuiltinType *ToPointeeType
705 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
706 // This conversion is considered only when there is an
707 // explicit appropriate pointer target type (C++ 4.2p2).
708 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
709 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
710 (!StrLit->isWide() &&
711 (ToPointeeType->getKind() == BuiltinType::Char_U ||
712 ToPointeeType->getKind() == BuiltinType::Char_S))))
713 return true;
714 }
715
716 return false;
717}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000718
719/// PerformImplicitConversion - Perform an implicit conversion of the
720/// expression From to the type ToType. Returns true if there was an
721/// error, false otherwise. The expression From is replaced with the
Douglas Gregor45920e82008-12-19 17:40:08 +0000722/// converted expression. Flavor is the kind of conversion we're
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000723/// performing, used in the error message. If @p AllowExplicit,
724/// explicit user-defined conversions are permitted.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000725bool
Douglas Gregor45920e82008-12-19 17:40:08 +0000726Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000727 const char *Flavor, bool AllowExplicit)
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000728{
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000729 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType, false,
730 AllowExplicit);
731 return PerformImplicitConversion(From, ToType, ICS, Flavor);
732}
733
734/// PerformImplicitConversion - Perform an implicit conversion of the
735/// expression From to the type ToType using the pre-computed implicit
736/// conversion sequence ICS. Returns true if there was an error, false
737/// otherwise. The expression From is replaced with the converted
738/// expression. Flavor is the kind of conversion we're performing,
739/// used in the error message.
740bool
741Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
742 const ImplicitConversionSequence &ICS,
743 const char* Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000744 switch (ICS.ConversionKind) {
745 case ImplicitConversionSequence::StandardConversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000746 if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000747 return true;
748 break;
749
750 case ImplicitConversionSequence::UserDefinedConversion:
751 // FIXME: This is, of course, wrong. We'll need to actually call
752 // the constructor or conversion operator, and then cope with the
753 // standard conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000754 ImpCastExprToType(From, ToType.getNonReferenceType(),
755 ToType->isReferenceType());
Douglas Gregor60d62c22008-10-31 16:23:19 +0000756 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000757
758 case ImplicitConversionSequence::EllipsisConversion:
759 assert(false && "Cannot perform an ellipsis conversion");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000760 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000761
762 case ImplicitConversionSequence::BadConversion:
763 return true;
764 }
765
766 // Everything went well.
767 return false;
768}
769
770/// PerformImplicitConversion - Perform an implicit conversion of the
771/// expression From to the type ToType by following the standard
772/// conversion sequence SCS. Returns true if there was an error, false
773/// otherwise. The expression From is replaced with the converted
Douglas Gregor45920e82008-12-19 17:40:08 +0000774/// expression. Flavor is the context in which we're performing this
775/// conversion, for use in error messages.
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000776bool
777Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000778 const StandardConversionSequence& SCS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000779 const char *Flavor) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000780 // Overall FIXME: we are recomputing too many types here and doing
781 // far too much extra work. What this means is that we need to keep
782 // track of more information that is computed when we try the
783 // implicit conversion initially, so that we don't need to recompute
784 // anything here.
785 QualType FromType = From->getType();
786
Douglas Gregor225c41e2008-11-03 19:09:14 +0000787 if (SCS.CopyConstructor) {
788 // FIXME: Create a temporary object by calling the copy
789 // constructor.
Douglas Gregor66b947f2009-01-16 19:38:23 +0000790 ImpCastExprToType(From, ToType.getNonReferenceType(),
791 ToType->isReferenceType());
Douglas Gregor225c41e2008-11-03 19:09:14 +0000792 return false;
793 }
794
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000795 // Perform the first implicit conversion.
796 switch (SCS.First) {
797 case ICK_Identity:
798 case ICK_Lvalue_To_Rvalue:
799 // Nothing to do.
800 break;
801
802 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000803 FromType = Context.getArrayDecayedType(FromType);
804 ImpCastExprToType(From, FromType);
805 break;
806
807 case ICK_Function_To_Pointer:
Douglas Gregor063daf62009-03-13 18:40:31 +0000808 if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +0000809 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
810 if (!Fn)
811 return true;
812
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000813 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
814 return true;
815
Douglas Gregor904eed32008-11-10 20:40:00 +0000816 FixOverloadedFunctionReference(From, Fn);
817 FromType = From->getType();
Douglas Gregor904eed32008-11-10 20:40:00 +0000818 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000819 FromType = Context.getPointerType(FromType);
820 ImpCastExprToType(From, FromType);
821 break;
822
823 default:
824 assert(false && "Improper first standard conversion");
825 break;
826 }
827
828 // Perform the second implicit conversion
829 switch (SCS.Second) {
830 case ICK_Identity:
831 // Nothing to do.
832 break;
833
834 case ICK_Integral_Promotion:
835 case ICK_Floating_Promotion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000836 case ICK_Complex_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000837 case ICK_Integral_Conversion:
838 case ICK_Floating_Conversion:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000839 case ICK_Complex_Conversion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000840 case ICK_Floating_Integral:
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000841 case ICK_Complex_Real:
Douglas Gregorf9201e02009-02-11 23:02:49 +0000842 case ICK_Compatible_Conversion:
843 // FIXME: Go deeper to get the unqualified type!
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000844 FromType = ToType.getUnqualifiedType();
845 ImpCastExprToType(From, FromType);
846 break;
847
848 case ICK_Pointer_Conversion:
Douglas Gregor45920e82008-12-19 17:40:08 +0000849 if (SCS.IncompatibleObjC) {
850 // Diagnose incompatible Objective-C conversions
851 Diag(From->getSourceRange().getBegin(),
852 diag::ext_typecheck_convert_incompatible_pointer)
853 << From->getType() << ToType << Flavor
854 << From->getSourceRange();
855 }
856
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000857 if (CheckPointerConversion(From, ToType))
858 return true;
859 ImpCastExprToType(From, ToType);
860 break;
861
862 case ICK_Pointer_Member:
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000863 if (CheckMemberPointerConversion(From, ToType))
864 return true;
865 ImpCastExprToType(From, ToType);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000866 break;
867
868 case ICK_Boolean_Conversion:
869 FromType = Context.BoolTy;
870 ImpCastExprToType(From, FromType);
871 break;
872
873 default:
874 assert(false && "Improper second standard conversion");
875 break;
876 }
877
878 switch (SCS.Third) {
879 case ICK_Identity:
880 // Nothing to do.
881 break;
882
883 case ICK_Qualification:
Douglas Gregor66b947f2009-01-16 19:38:23 +0000884 ImpCastExprToType(From, ToType.getNonReferenceType(),
885 ToType->isReferenceType());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000886 break;
887
888 default:
889 assert(false && "Improper second standard conversion");
890 break;
891 }
892
893 return false;
894}
895
Sebastian Redl64b45f72009-01-05 20:52:13 +0000896Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
897 SourceLocation KWLoc,
898 SourceLocation LParen,
899 TypeTy *Ty,
900 SourceLocation RParen) {
901 // FIXME: Some of the type traits have requirements. Interestingly, only the
902 // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
903 // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
904 // type is indeed a POD.
905
906 // There is no point in eagerly computing the value. The traits are designed
907 // to be used from type trait templates, so Ty will be a template parameter
908 // 99% of the time.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000909 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT,
Sebastian Redl64b45f72009-01-05 20:52:13 +0000910 QualType::getFromOpaquePtr(Ty),
911 RParen, Context.BoolTy));
912}
Sebastian Redl7c8bd602009-02-07 20:10:22 +0000913
914QualType Sema::CheckPointerToMemberOperands(
915 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
916{
917 const char *OpSpelling = isIndirect ? "->*" : ".*";
918 // C++ 5.5p2
919 // The binary operator .* [p3: ->*] binds its second operand, which shall
920 // be of type "pointer to member of T" (where T is a completely-defined
921 // class type) [...]
922 QualType RType = rex->getType();
923 const MemberPointerType *MemPtr = RType->getAsMemberPointerType();
924 if (!MemPtr || MemPtr->getClass()->isIncompleteType()) {
925 Diag(Loc, diag::err_bad_memptr_rhs)
926 << OpSpelling << RType << rex->getSourceRange();
927 return QualType();
928 }
929 QualType Class(MemPtr->getClass(), 0);
930
931 // C++ 5.5p2
932 // [...] to its first operand, which shall be of class T or of a class of
933 // which T is an unambiguous and accessible base class. [p3: a pointer to
934 // such a class]
935 QualType LType = lex->getType();
936 if (isIndirect) {
937 if (const PointerType *Ptr = LType->getAsPointerType())
938 LType = Ptr->getPointeeType().getNonReferenceType();
939 else {
940 Diag(Loc, diag::err_bad_memptr_lhs)
941 << OpSpelling << 1 << LType << lex->getSourceRange();
942 return QualType();
943 }
944 }
945
946 if (Context.getCanonicalType(Class).getUnqualifiedType() !=
947 Context.getCanonicalType(LType).getUnqualifiedType()) {
948 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
949 /*DetectVirtual=*/false);
950 // FIXME: Would it be useful to print full ambiguity paths,
951 // or is that overkill?
952 if (!IsDerivedFrom(LType, Class, Paths) ||
953 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
954 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
955 << (int)isIndirect << lex->getType() << lex->getSourceRange();
956 return QualType();
957 }
958 }
959
960 // C++ 5.5p2
961 // The result is an object or a function of the type specified by the
962 // second operand.
963 // The cv qualifiers are the union of those in the pointer and the left side,
964 // in accordance with 5.5p5 and 5.2.5.
965 // FIXME: This returns a dereferenced member function pointer as a normal
966 // function type. However, the only operation valid on such functions is
967 // calling them. There's also a GCC extension to get a function pointer to
968 // the thing, which is another complication, because this type - unlike the
969 // type that is the result of this expression - takes the class as the first
970 // argument.
971 // We probably need a "MemberFunctionClosureType" or something like that.
972 QualType Result = MemPtr->getPointeeType();
973 if (LType.isConstQualified())
974 Result.addConst();
975 if (LType.isVolatileQualified())
976 Result.addVolatile();
977 return Result;
978}