blob: fa81f118c70e4ce9ced59715de27e4e7f9061d79 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffac5d4f12007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +000017#include "clang/Parse/DeclSpec.h"
Argiris Kirtzidiscf4e8f82008-10-06 23:16:35 +000018#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregorf8e92702008-10-24 15:36:09 +000020#include "llvm/ADT/SmallVector.h"
21#include "llvm/Support/Debug.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022using namespace clang;
23
Steve Naroff5cbb02f2007-09-16 14:56:35 +000024/// ActOnCXXCasts - Parse {dynamic,static,reinterpret,const}_cast's.
Chris Lattner4b009652007-07-25 00:24:17 +000025Action::ExprResult
Steve Naroff5cbb02f2007-09-16 14:56:35 +000026Sema::ActOnCXXCasts(SourceLocation OpLoc, tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +000027 SourceLocation LAngleBracketLoc, TypeTy *Ty,
28 SourceLocation RAngleBracketLoc,
29 SourceLocation LParenLoc, ExprTy *E,
30 SourceLocation RParenLoc) {
31 CXXCastExpr::Opcode Op;
Douglas Gregorf8e92702008-10-24 15:36:09 +000032 Expr *Ex = (Expr*)E;
33 QualType DestType = QualType::getFromOpaquePtr(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +000034
35 switch (Kind) {
36 default: assert(0 && "Unknown C++ cast!");
Douglas Gregorf8e92702008-10-24 15:36:09 +000037 case tok::kw_const_cast:
38 Op = CXXCastExpr::ConstCast;
39 CheckConstCast(OpLoc, Ex, DestType);
40 break;
41 case tok::kw_dynamic_cast:
42 Op = CXXCastExpr::DynamicCast;
43 break;
44 case tok::kw_reinterpret_cast:
45 Op = CXXCastExpr::ReinterpretCast;
46 CheckReinterpretCast(OpLoc, Ex, DestType);
47 break;
48 case tok::kw_static_cast:
49 Op = CXXCastExpr::StaticCast;
50 break;
Chris Lattner4b009652007-07-25 00:24:17 +000051 }
52
Douglas Gregorf8e92702008-10-24 15:36:09 +000053 return new CXXCastExpr(Op, DestType, Ex, OpLoc);
54}
55
56/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
57/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
58/// like this:
59/// const char *str = "literal";
60/// legacy_function(const_cast\<char*\>(str));
61void
62Sema::CheckConstCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType)
63{
64 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
65
66 DestType = Context.getCanonicalType(DestType);
67 QualType SrcType = SrcExpr->getType();
68 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
69 if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
70 // Cannot cast non-lvalue to reference type.
71 Diag(OpLoc, diag::err_bad_cxx_cast_rvalue,
72 "const_cast", OrigDestType.getAsString());
73 return;
74 }
75
76 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
77 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
78 DestType = Context.getPointerType(DestTypeTmp->getPointeeType());
79 if (const ReferenceType *SrcTypeTmp = SrcType->getAsReferenceType()) {
80 // FIXME: This shouldn't actually be possible, but right now it is.
81 SrcType = SrcTypeTmp->getPointeeType();
82 }
83 SrcType = Context.getPointerType(SrcType);
84 } else {
85 // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
86 // lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
87 // conversions are performed on the expression.
88 DefaultFunctionArrayConversion(SrcExpr);
89 SrcType = SrcExpr->getType();
90 }
91
92 if (!DestType->isPointerType()) {
93 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
94 // was a reference type, we converted it to a pointer above.
95 // C++ 5.2.11p3: For two pointer types [...]
96 Diag(OpLoc, diag::err_bad_const_cast_dest, OrigDestType.getAsString());
97 return;
98 }
99 if (DestType->isFunctionPointerType()) {
100 // Cannot cast direct function pointers.
101 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
102 // T is the ultimate pointee of source and target type.
103 Diag(OpLoc, diag::err_bad_const_cast_dest, OrigDestType.getAsString());
104 return;
105 }
106 SrcType = Context.getCanonicalType(SrcType);
107
108 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
109 // completely equal.
110 // FIXME: const_cast should probably not be able to convert between pointers
111 // to different address spaces.
112 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
113 // in multi-level pointers may change, but the level count must be the same,
114 // as must be the final pointee type.
115 while (SrcType != DestType && UnwrapSimilarPointerTypes(SrcType, DestType)) {
116 SrcType = SrcType.getUnqualifiedType();
117 DestType = DestType.getUnqualifiedType();
118 }
119
120 // Doug Gregor said to disallow this until users complain.
121#if 0
122 // If we end up with constant arrays of equal size, unwrap those too. A cast
123 // from const int [N] to int (&)[N] is invalid by my reading of the
124 // standard, but g++ accepts it even with -ansi -pedantic.
125 // No more than one level, though, so don't embed this in the unwrap loop
126 // above.
127 const ConstantArrayType *SrcTypeArr, *DestTypeArr;
128 if ((SrcTypeArr = Context.getAsConstantArrayType(SrcType)) &&
129 (DestTypeArr = Context.getAsConstantArrayType(DestType)))
130 {
131 if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
132 // Different array sizes.
133 Diag(OpLoc, diag::err_bad_cxx_cast_generic, "const_cast",
134 OrigDestType.getAsString(), OrigSrcType.getAsString());
135 return;
136 }
137 SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
138 DestType = DestTypeArr->getElementType().getUnqualifiedType();
139 }
140#endif
141
142 // Since we're dealing in canonical types, the remainder must be the same.
143 if (SrcType != DestType) {
144 // Cast between unrelated types.
145 Diag(OpLoc, diag::err_bad_cxx_cast_generic, "const_cast",
146 OrigDestType.getAsString(), OrigSrcType.getAsString());
147 return;
148 }
149}
150
151/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
152/// valid.
153/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
154/// like this:
155/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
156void
157Sema::CheckReinterpretCast(SourceLocation OpLoc, Expr *&SrcExpr,
158 QualType DestType)
159{
160 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
161
162 DestType = Context.getCanonicalType(DestType);
163 QualType SrcType = SrcExpr->getType();
164 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
165 if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) {
166 // Cannot cast non-lvalue to reference type.
167 Diag(OpLoc, diag::err_bad_cxx_cast_rvalue,
168 "reinterpret_cast", OrigDestType.getAsString());
169 return;
170 }
171
172 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
173 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
174 // built-in & and * operators.
175 // This code does this transformation for the checked types.
176 DestType = Context.getPointerType(DestTypeTmp->getPointeeType());
177 if (const ReferenceType *SrcTypeTmp = SrcType->getAsReferenceType()) {
178 // FIXME: This shouldn't actually be possible, but right now it is.
179 SrcType = SrcTypeTmp->getPointeeType();
180 }
181 SrcType = Context.getPointerType(SrcType);
182 } else {
183 // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
184 // function-to-pointer standard conversions are performed on the
185 // expression v.
186 DefaultFunctionArrayConversion(SrcExpr);
187 SrcType = SrcExpr->getType();
188 }
189
190 // Canonicalize source for comparison.
191 SrcType = Context.getCanonicalType(SrcType);
192
193 bool destIsPtr = DestType->isPointerType();
194 bool srcIsPtr = SrcType->isPointerType();
195 if (!destIsPtr && !srcIsPtr) {
196 // Except for std::nullptr_t->integer, which is not supported yet, and
197 // lvalue->reference, which is handled above, at least one of the two
198 // arguments must be a pointer.
199 Diag(OpLoc, diag::err_bad_cxx_cast_generic, "reinterpret_cast",
200 OrigDestType.getAsString(), OrigSrcType.getAsString());
201 return;
202 }
203
204 if (SrcType == DestType) {
205 // C++ 5.2.10p2 has a note that mentions that, subject to all other
206 // restrictions, a cast to the same type is allowed. The intent is not
207 // entirely clear here, since all other paragraphs explicitly forbid casts
208 // to the same type. However, the behavior of compilers is pretty consistent
209 // on this point: allow same-type conversion if the involved are pointers,
210 // disallow otherwise.
211 return;
212 }
213
214 // Note: Clang treats enumeration types as integral types. If this is ever
215 // changed for C++, the additional check here will be redundant.
216 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
217 assert(srcIsPtr);
218 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
219 // type large enough to hold it.
220 if (Context.getTypeSize(SrcType) > Context.getTypeSize(DestType)) {
221 Diag(OpLoc, diag::err_bad_reinterpret_cast_small_int,
222 OrigDestType.getAsString());
223 }
224 return;
225 }
226
227 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
228 assert(destIsPtr);
229 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
230 // converted to a pointer.
231 return;
232 }
233
234 if (!destIsPtr || !srcIsPtr) {
235 // With the valid non-pointer conversions out of the way, we can be even
236 // more stringent.
237 Diag(OpLoc, diag::err_bad_cxx_cast_generic, "reinterpret_cast",
238 OrigDestType.getAsString(), OrigSrcType.getAsString());
239 return;
240 }
241
242 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
243 if (CastsAwayConstness(SrcType, DestType)) {
244 Diag(OpLoc, diag::err_bad_cxx_cast_const_away, "reinterpret_cast",
245 OrigDestType.getAsString(), OrigSrcType.getAsString());
246 return;
247 }
248
249 // Not casting away constness, so the only remaining check is for compatible
250 // pointer categories.
251
252 if (SrcType->isFunctionPointerType()) {
253 if (DestType->isFunctionPointerType()) {
254 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
255 // a pointer to a function of a different type.
256 return;
257 }
258
259 // FIXME: Handle member pointers.
260
261 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
262 // an object type or vice versa is conditionally-supported.
263 // Compilers support it in C++03 too, though, because it's necessary for
264 // casting the return value of dlsym() and GetProcAddress().
265 // FIXME: Conditionally-supported behavior should be configurable in the
266 // TargetInfo or similar.
267 if (!getLangOptions().CPlusPlus0x) {
268 Diag(OpLoc, diag::ext_reinterpret_cast_fn_obj);
269 }
270 return;
271 }
272
273 // FIXME: Handle member pointers.
274
275 if (DestType->isFunctionPointerType()) {
276 // See above.
277 if (!getLangOptions().CPlusPlus0x) {
278 Diag(OpLoc, diag::ext_reinterpret_cast_fn_obj);
279 }
280 return;
281 }
282
283 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
284 // a pointer to an object of different type.
285 // Void pointers are not specified, but supported by every compiler out there.
286 // So we finish by allowing everything that remains - it's got to be two
287 // object pointers.
288}
289
Douglas Gregor651d1cc2008-10-24 16:17:19 +0000290/// CastsAwayConstness - Check if the pointer conversion from SrcType
291/// to DestType casts away constness as defined in C++
292/// 5.2.11p8ff. This is used by the cast checkers. Both arguments
293/// must denote pointer types.
Douglas Gregorf8e92702008-10-24 15:36:09 +0000294bool
295Sema::CastsAwayConstness(QualType SrcType, QualType DestType)
296{
297 // Casting away constness is defined in C++ 5.2.11p8 with reference to
298 // C++ 4.4.
299 // We piggyback on Sema::IsQualificationConversion for this, since the rules
300 // are non-trivial. So first we construct Tcv *...cv* as described in
301 // C++ 5.2.11p8.
302 SrcType = Context.getCanonicalType(SrcType);
303 DestType = Context.getCanonicalType(DestType);
304
305 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
306 llvm::SmallVector<unsigned, 8> cv1, cv2;
307
308 // Find the qualifications.
309 while (UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
310 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
311 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
312 }
313 assert(cv1.size() > 0 && "Must have at least one pointer level.");
314
315 // Construct void pointers with those qualifiers (in reverse order of
316 // unwrapping, of course).
317 QualType SrcConstruct = Context.VoidTy;
318 QualType DestConstruct = Context.VoidTy;
319 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
320 i2 = cv2.rbegin();
321 i1 != cv1.rend(); ++i1, ++i2)
322 {
323 SrcConstruct = Context.getPointerType(SrcConstruct.getQualifiedType(*i1));
324 DestConstruct = Context.getPointerType(DestConstruct.getQualifiedType(*i2));
325 }
326
327 // Test if they're compatible.
328 return SrcConstruct != DestConstruct &&
329 !IsQualificationConversion(SrcConstruct, DestConstruct);
330}
331
332/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
333void
334Sema::CheckStaticCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType)
335{
336#if 0
337 // 5.2.9/1 sets the ground rule of disallowing casting away constness.
338 // 5.2.9/2 permits everything allowed for direct-init, deferring to 8.5.
339 // Note: for class destination, that's overload resolution over dest's
340 // constructors. Src's conversions are only considered in overload choice.
341 // For any other destination, that's just the clause 4 standards convs.
342 // 5.2.9/4 permits static_cast&lt;cv void>(anything), which is a no-op.
343 // 5.2.9/5 permits explicit non-dynamic downcasts for lvalue-to-reference.
344 // 5.2.9/6 permits reversing all implicit conversions except lvalue-to-rvalue,
345 // function-to-pointer, array decay and to-bool, with some further
346 // restrictions. Defers to 4.
347 // 5.2.9/7 permits integer-to-enum conversion. Interesting note: if the
348 // integer does not correspond to an enum value, the result is unspecified -
349 // but it still has to be some value of the enum. I don't think any compiler
350 // complies with that.
351 // 5.2.9/8 is 5.2.9/5 for pointers.
352 // 5.2.9/9 messes with member pointers. TODO. No need to think about that yet.
353 // 5.2.9/10 permits void* to T*.
354
355 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
356 DestType = Context.getCanonicalType(DestType);
357 // Tests are ordered by simplicity and a wild guess at commonness.
358
359 if (const BuiltinType *BuiltinDest = DestType->getAsBuiltinType()) {
360 // 5.2.9/4
361 if (BuiltinDest->getKind() == BuiltinType::Void) {
362 return;
363 }
364
365 // Primitive conversions for 5.2.9/2 and 6.
366 }
367#endif
Chris Lattner4b009652007-07-25 00:24:17 +0000368}
369
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000370/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Chris Lattner4b009652007-07-25 00:24:17 +0000371Action::ExprResult
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000372Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregorf8e92702008-10-24 15:36:09 +0000373 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Chris Lattner4b009652007-07-25 00:24:17 +0000374 "Unknown C++ Boolean value!");
Steve Naroffac5d4f12007-08-25 14:02:58 +0000375 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000376}
Chris Lattnera7447ba2008-02-26 00:51:44 +0000377
378/// ActOnCXXThrow - Parse throw expressions.
379Action::ExprResult
380Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
381 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
382}
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000383
384Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
385 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
386 /// is a non-lvalue expression whose value is the address of the object for
387 /// which the function is called.
388
389 if (!isa<FunctionDecl>(CurContext)) {
390 Diag(ThisLoc, diag::err_invalid_this_use);
391 return ExprResult(true);
392 }
393
394 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
395 if (MD->isInstance())
Chris Lattner69909292008-08-10 01:53:14 +0000396 return new PredefinedExpr(ThisLoc, MD->getThisType(Context),
397 PredefinedExpr::CXXThis);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000398
399 return Diag(ThisLoc, diag::err_invalid_this_use);
400}
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000401
402/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
403/// Can be interpreted either as function-style casting ("int(x)")
404/// or class type construction ("ClassType(x,y,z)")
405/// or creation of a value-initialized type ("int()").
406Action::ExprResult
407Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
408 SourceLocation LParenLoc,
409 ExprTy **ExprTys, unsigned NumExprs,
410 SourceLocation *CommaLocs,
411 SourceLocation RParenLoc) {
412 assert(TypeRep && "Missing type!");
413 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
414 Expr **Exprs = (Expr**)ExprTys;
415 SourceLocation TyBeginLoc = TypeRange.getBegin();
416 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
417
418 if (const RecordType *RT = Ty->getAsRecordType()) {
419 // C++ 5.2.3p1:
420 // If the simple-type-specifier specifies a class type, the class type shall
421 // be complete.
422 //
423 if (!RT->getDecl()->isDefinition())
424 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
425 Ty.getAsString(), FullRange);
426
Argiris Kirtzidiscf4e8f82008-10-06 23:16:35 +0000427 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
428 "class constructors are not supported yet");
429 return Diag(TyBeginLoc, DiagID);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000430 }
431
432 // C++ 5.2.3p1:
433 // If the expression list is a single expression, the type conversion
434 // expression is equivalent (in definedness, and if defined in meaning) to the
435 // corresponding cast expression.
436 //
437 if (NumExprs == 1) {
438 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
439 return true;
440 return new CXXFunctionalCastExpr(Ty, TyBeginLoc, Exprs[0], RParenLoc);
441 }
442
443 // C++ 5.2.3p1:
444 // If the expression list specifies more than a single value, the type shall
445 // be a class with a suitably declared constructor.
446 //
447 if (NumExprs > 1)
448 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg,
449 FullRange);
450
451 assert(NumExprs == 0 && "Expected 0 expressions");
452
453 // C++ 5.2.3p2:
454 // The expression T(), where T is a simple-type-specifier for a non-array
455 // complete object type or the (possibly cv-qualified) void type, creates an
456 // rvalue of the specified type, which is value-initialized.
457 //
458 if (Ty->isArrayType())
459 return Diag(TyBeginLoc, diag::err_value_init_for_array_type, FullRange);
460 if (Ty->isIncompleteType() && !Ty->isVoidType())
461 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
462 Ty.getAsString(), FullRange);
463
464 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
465}
Argiris Kirtzidis810c0f72008-09-10 02:17:11 +0000466
467
468/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
469/// C++ if/switch/while/for statement.
470/// e.g: "if (int x = f()) {...}"
471Action::ExprResult
472Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
473 Declarator &D,
474 SourceLocation EqualLoc,
475 ExprTy *AssignExprVal) {
476 assert(AssignExprVal && "Null assignment expression");
477
478 // C++ 6.4p2:
479 // The declarator shall not specify a function or an array.
480 // The type-specifier-seq shall not contain typedef and shall not declare a
481 // new class or enumeration.
482
483 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
484 "Parser allowed 'typedef' as storage class of condition decl.");
485
486 QualType Ty = GetTypeForDeclarator(D, S);
487
488 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
489 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
490 // would be created and CXXConditionDeclExpr wants a VarDecl.
491 return Diag(StartLoc, diag::err_invalid_use_of_function_type,
492 SourceRange(StartLoc, EqualLoc));
493 } else if (Ty->isArrayType()) { // ...or an array.
494 Diag(StartLoc, diag::err_invalid_use_of_array_type,
495 SourceRange(StartLoc, EqualLoc));
496 } else if (const RecordType *RT = Ty->getAsRecordType()) {
497 RecordDecl *RD = RT->getDecl();
498 // The type-specifier-seq shall not declare a new class...
499 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
500 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
501 } else if (const EnumType *ET = Ty->getAsEnumType()) {
502 EnumDecl *ED = ET->getDecl();
503 // ...or enumeration.
504 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
505 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
506 }
507
508 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
509 if (!Dcl)
510 return true;
511 AddInitializerToDecl(Dcl, AssignExprVal);
512
513 return new CXXConditionDeclExpr(StartLoc, EqualLoc,
514 cast<VarDecl>(static_cast<Decl *>(Dcl)));
515}
516
517/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
518bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
519 // C++ 6.4p4:
520 // The value of a condition that is an initialized declaration in a statement
521 // other than a switch statement is the value of the declared variable
522 // implicitly converted to type bool. If that conversion is ill-formed, the
523 // program is ill-formed.
524 // The value of a condition that is an expression is the value of the
525 // expression, implicitly converted to bool.
526 //
527 QualType Ty = CondExpr->getType(); // Save the type.
528 AssignConvertType
529 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
530 if (ConvTy == Incompatible)
531 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition,
532 Ty.getAsString(), CondExpr->getSourceRange());
533 return false;
534}
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000535
536/// Helper function to determine whether this is the (deprecated) C++
537/// conversion from a string literal to a pointer to non-const char or
538/// non-const wchar_t (for narrow and wide string literals,
539/// respectively).
540bool
541Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
542 // Look inside the implicit cast, if it exists.
543 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
544 From = Cast->getSubExpr();
545
546 // A string literal (2.13.4) that is not a wide string literal can
547 // be converted to an rvalue of type "pointer to char"; a wide
548 // string literal can be converted to an rvalue of type "pointer
549 // to wchar_t" (C++ 4.2p2).
550 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
551 if (const PointerType *ToPtrType = ToType->getAsPointerType())
552 if (const BuiltinType *ToPointeeType
553 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
554 // This conversion is considered only when there is an
555 // explicit appropriate pointer target type (C++ 4.2p2).
556 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
557 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
558 (!StrLit->isWide() &&
559 (ToPointeeType->getKind() == BuiltinType::Char_U ||
560 ToPointeeType->getKind() == BuiltinType::Char_S))))
561 return true;
562 }
563
564 return false;
565}
Douglas Gregorbb461502008-10-24 04:54:22 +0000566
567/// PerformImplicitConversion - Perform an implicit conversion of the
568/// expression From to the type ToType. Returns true if there was an
569/// error, false otherwise. The expression From is replaced with the
570/// converted expression.
571bool
572Sema::PerformImplicitConversion(Expr *&From, QualType ToType)
573{
574 ImplicitConversionSequence ICS = TryCopyInitialization(From, ToType);
575 switch (ICS.ConversionKind) {
576 case ImplicitConversionSequence::StandardConversion:
577 if (PerformImplicitConversion(From, ToType, ICS.Standard))
578 return true;
579 break;
580
581 case ImplicitConversionSequence::UserDefinedConversion:
582 // FIXME: This is, of course, wrong. We'll need to actually call
583 // the constructor or conversion operator, and then cope with the
584 // standard conversions.
585 ImpCastExprToType(From, ToType);
586 break;
587
588 case ImplicitConversionSequence::EllipsisConversion:
589 assert(false && "Cannot perform an ellipsis conversion");
590 break;
591
592 case ImplicitConversionSequence::BadConversion:
593 return true;
594 }
595
596 // Everything went well.
597 return false;
598}
599
600/// PerformImplicitConversion - Perform an implicit conversion of the
601/// expression From to the type ToType by following the standard
602/// conversion sequence SCS. Returns true if there was an error, false
603/// otherwise. The expression From is replaced with the converted
604/// expression.
605bool
606Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
607 const StandardConversionSequence& SCS)
608{
609 // Overall FIXME: we are recomputing too many types here and doing
610 // far too much extra work. What this means is that we need to keep
611 // track of more information that is computed when we try the
612 // implicit conversion initially, so that we don't need to recompute
613 // anything here.
614 QualType FromType = From->getType();
615
616 // Perform the first implicit conversion.
617 switch (SCS.First) {
618 case ICK_Identity:
619 case ICK_Lvalue_To_Rvalue:
620 // Nothing to do.
621 break;
622
623 case ICK_Array_To_Pointer:
624 FromType = Context.getArrayDecayedType(FromType);
625 ImpCastExprToType(From, FromType);
626 break;
627
628 case ICK_Function_To_Pointer:
629 FromType = Context.getPointerType(FromType);
630 ImpCastExprToType(From, FromType);
631 break;
632
633 default:
634 assert(false && "Improper first standard conversion");
635 break;
636 }
637
638 // Perform the second implicit conversion
639 switch (SCS.Second) {
640 case ICK_Identity:
641 // Nothing to do.
642 break;
643
644 case ICK_Integral_Promotion:
645 case ICK_Floating_Promotion:
646 case ICK_Integral_Conversion:
647 case ICK_Floating_Conversion:
648 case ICK_Floating_Integral:
649 FromType = ToType.getUnqualifiedType();
650 ImpCastExprToType(From, FromType);
651 break;
652
653 case ICK_Pointer_Conversion:
654 if (CheckPointerConversion(From, ToType))
655 return true;
656 ImpCastExprToType(From, ToType);
657 break;
658
659 case ICK_Pointer_Member:
660 // FIXME: Implement pointer-to-member conversions.
661 assert(false && "Pointer-to-member conversions are unsupported");
662 break;
663
664 case ICK_Boolean_Conversion:
665 FromType = Context.BoolTy;
666 ImpCastExprToType(From, FromType);
667 break;
668
669 default:
670 assert(false && "Improper second standard conversion");
671 break;
672 }
673
674 switch (SCS.Third) {
675 case ICK_Identity:
676 // Nothing to do.
677 break;
678
679 case ICK_Qualification:
680 ImpCastExprToType(From, ToType);
681 break;
682
683 default:
684 assert(false && "Improper second standard conversion");
685 break;
686 }
687
688 return false;
689}
690