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