blob: 5c62a936f1917a2134e9a810b55e23d6b5375b02 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ExprCXX.h"
Steve Naroff210679c2007-08-25 14:02:58 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +000017#include "clang/Parse/DeclSpec.h"
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +000018#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregor2f639b92008-10-24 15:36:09 +000020#include "llvm/ADT/SmallVector.h"
21#include "llvm/Support/Debug.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Steve Naroff1b273c42007-09-16 14:56:35 +000024/// ActOnCXXCasts - Parse {dynamic,static,reinterpret,const}_cast's.
Reid Spencer5f016e22007-07-11 17:01:13 +000025Action::ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +000026Sema::ActOnCXXCasts(SourceLocation OpLoc, tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +000027 SourceLocation LAngleBracketLoc, TypeTy *Ty,
28 SourceLocation RAngleBracketLoc,
29 SourceLocation LParenLoc, ExprTy *E,
30 SourceLocation RParenLoc) {
31 CXXCastExpr::Opcode Op;
Douglas Gregor2f639b92008-10-24 15:36:09 +000032 Expr *Ex = (Expr*)E;
33 QualType DestType = QualType::getFromOpaquePtr(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +000034
35 switch (Kind) {
36 default: assert(0 && "Unknown C++ cast!");
Douglas Gregor2f639b92008-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;
Reid Spencer5f016e22007-07-11 17:01:13 +000051 }
52
Douglas Gregor2f639b92008-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
290/// Check if the pointer conversion from SrcType to DestType casts away
291/// constness as defined in C++ 5.2.11p8ff. This is used by the cast checkers.
292/// Both arguments must denote pointer types.
293bool
294Sema::CastsAwayConstness(QualType SrcType, QualType DestType)
295{
296 // Casting away constness is defined in C++ 5.2.11p8 with reference to
297 // C++ 4.4.
298 // We piggyback on Sema::IsQualificationConversion for this, since the rules
299 // are non-trivial. So first we construct Tcv *...cv* as described in
300 // C++ 5.2.11p8.
301 SrcType = Context.getCanonicalType(SrcType);
302 DestType = Context.getCanonicalType(DestType);
303
304 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
305 llvm::SmallVector<unsigned, 8> cv1, cv2;
306
307 // Find the qualifications.
308 while (UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
309 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
310 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
311 }
312 assert(cv1.size() > 0 && "Must have at least one pointer level.");
313
314 // Construct void pointers with those qualifiers (in reverse order of
315 // unwrapping, of course).
316 QualType SrcConstruct = Context.VoidTy;
317 QualType DestConstruct = Context.VoidTy;
318 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
319 i2 = cv2.rbegin();
320 i1 != cv1.rend(); ++i1, ++i2)
321 {
322 SrcConstruct = Context.getPointerType(SrcConstruct.getQualifiedType(*i1));
323 DestConstruct = Context.getPointerType(DestConstruct.getQualifiedType(*i2));
324 }
325
326 // Test if they're compatible.
327 return SrcConstruct != DestConstruct &&
328 !IsQualificationConversion(SrcConstruct, DestConstruct);
329}
330
331/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
332void
333Sema::CheckStaticCast(SourceLocation OpLoc, Expr *&SrcExpr, QualType DestType)
334{
335#if 0
336 // 5.2.9/1 sets the ground rule of disallowing casting away constness.
337 // 5.2.9/2 permits everything allowed for direct-init, deferring to 8.5.
338 // Note: for class destination, that's overload resolution over dest's
339 // constructors. Src's conversions are only considered in overload choice.
340 // For any other destination, that's just the clause 4 standards convs.
341 // 5.2.9/4 permits static_cast&lt;cv void>(anything), which is a no-op.
342 // 5.2.9/5 permits explicit non-dynamic downcasts for lvalue-to-reference.
343 // 5.2.9/6 permits reversing all implicit conversions except lvalue-to-rvalue,
344 // function-to-pointer, array decay and to-bool, with some further
345 // restrictions. Defers to 4.
346 // 5.2.9/7 permits integer-to-enum conversion. Interesting note: if the
347 // integer does not correspond to an enum value, the result is unspecified -
348 // but it still has to be some value of the enum. I don't think any compiler
349 // complies with that.
350 // 5.2.9/8 is 5.2.9/5 for pointers.
351 // 5.2.9/9 messes with member pointers. TODO. No need to think about that yet.
352 // 5.2.9/10 permits void* to T*.
353
354 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
355 DestType = Context.getCanonicalType(DestType);
356 // Tests are ordered by simplicity and a wild guess at commonness.
357
358 if (const BuiltinType *BuiltinDest = DestType->getAsBuiltinType()) {
359 // 5.2.9/4
360 if (BuiltinDest->getKind() == BuiltinType::Void) {
361 return;
362 }
363
364 // Primitive conversions for 5.2.9/2 and 6.
365 }
366#endif
Reid Spencer5f016e22007-07-11 17:01:13 +0000367}
368
Steve Naroff1b273c42007-09-16 14:56:35 +0000369/// ActOnCXXBoolLiteral - Parse {true,false} literals.
Reid Spencer5f016e22007-07-11 17:01:13 +0000370Action::ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000371Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000372 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 "Unknown C++ Boolean value!");
Steve Naroff210679c2007-08-25 14:02:58 +0000374 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000375}
Chris Lattner50dd2892008-02-26 00:51:44 +0000376
377/// ActOnCXXThrow - Parse throw expressions.
378Action::ExprResult
379Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
380 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
381}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000382
383Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
384 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
385 /// is a non-lvalue expression whose value is the address of the object for
386 /// which the function is called.
387
388 if (!isa<FunctionDecl>(CurContext)) {
389 Diag(ThisLoc, diag::err_invalid_this_use);
390 return ExprResult(true);
391 }
392
393 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
394 if (MD->isInstance())
Chris Lattnerd9f69102008-08-10 01:53:14 +0000395 return new PredefinedExpr(ThisLoc, MD->getThisType(Context),
396 PredefinedExpr::CXXThis);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000397
398 return Diag(ThisLoc, diag::err_invalid_this_use);
399}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000400
401/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
402/// Can be interpreted either as function-style casting ("int(x)")
403/// or class type construction ("ClassType(x,y,z)")
404/// or creation of a value-initialized type ("int()").
405Action::ExprResult
406Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
407 SourceLocation LParenLoc,
408 ExprTy **ExprTys, unsigned NumExprs,
409 SourceLocation *CommaLocs,
410 SourceLocation RParenLoc) {
411 assert(TypeRep && "Missing type!");
412 QualType Ty = QualType::getFromOpaquePtr(TypeRep);
413 Expr **Exprs = (Expr**)ExprTys;
414 SourceLocation TyBeginLoc = TypeRange.getBegin();
415 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
416
417 if (const RecordType *RT = Ty->getAsRecordType()) {
418 // C++ 5.2.3p1:
419 // If the simple-type-specifier specifies a class type, the class type shall
420 // be complete.
421 //
422 if (!RT->getDecl()->isDefinition())
423 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
424 Ty.getAsString(), FullRange);
425
Argyrios Kyrtzidis4021a842008-10-06 23:16:35 +0000426 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
427 "class constructors are not supported yet");
428 return Diag(TyBeginLoc, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000429 }
430
431 // C++ 5.2.3p1:
432 // If the expression list is a single expression, the type conversion
433 // expression is equivalent (in definedness, and if defined in meaning) to the
434 // corresponding cast expression.
435 //
436 if (NumExprs == 1) {
437 if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
438 return true;
439 return new CXXFunctionalCastExpr(Ty, TyBeginLoc, Exprs[0], RParenLoc);
440 }
441
442 // C++ 5.2.3p1:
443 // If the expression list specifies more than a single value, the type shall
444 // be a class with a suitably declared constructor.
445 //
446 if (NumExprs > 1)
447 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg,
448 FullRange);
449
450 assert(NumExprs == 0 && "Expected 0 expressions");
451
452 // C++ 5.2.3p2:
453 // The expression T(), where T is a simple-type-specifier for a non-array
454 // complete object type or the (possibly cv-qualified) void type, creates an
455 // rvalue of the specified type, which is value-initialized.
456 //
457 if (Ty->isArrayType())
458 return Diag(TyBeginLoc, diag::err_value_init_for_array_type, FullRange);
459 if (Ty->isIncompleteType() && !Ty->isVoidType())
460 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use,
461 Ty.getAsString(), FullRange);
462
463 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
464}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000465
466
467/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
468/// C++ if/switch/while/for statement.
469/// e.g: "if (int x = f()) {...}"
470Action::ExprResult
471Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
472 Declarator &D,
473 SourceLocation EqualLoc,
474 ExprTy *AssignExprVal) {
475 assert(AssignExprVal && "Null assignment expression");
476
477 // C++ 6.4p2:
478 // The declarator shall not specify a function or an array.
479 // The type-specifier-seq shall not contain typedef and shall not declare a
480 // new class or enumeration.
481
482 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
483 "Parser allowed 'typedef' as storage class of condition decl.");
484
485 QualType Ty = GetTypeForDeclarator(D, S);
486
487 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
488 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
489 // would be created and CXXConditionDeclExpr wants a VarDecl.
490 return Diag(StartLoc, diag::err_invalid_use_of_function_type,
491 SourceRange(StartLoc, EqualLoc));
492 } else if (Ty->isArrayType()) { // ...or an array.
493 Diag(StartLoc, diag::err_invalid_use_of_array_type,
494 SourceRange(StartLoc, EqualLoc));
495 } else if (const RecordType *RT = Ty->getAsRecordType()) {
496 RecordDecl *RD = RT->getDecl();
497 // The type-specifier-seq shall not declare a new class...
498 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
499 Diag(RD->getLocation(), diag::err_type_defined_in_condition);
500 } else if (const EnumType *ET = Ty->getAsEnumType()) {
501 EnumDecl *ED = ET->getDecl();
502 // ...or enumeration.
503 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
504 Diag(ED->getLocation(), diag::err_type_defined_in_condition);
505 }
506
507 DeclTy *Dcl = ActOnDeclarator(S, D, 0);
508 if (!Dcl)
509 return true;
510 AddInitializerToDecl(Dcl, AssignExprVal);
511
512 return new CXXConditionDeclExpr(StartLoc, EqualLoc,
513 cast<VarDecl>(static_cast<Decl *>(Dcl)));
514}
515
516/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
517bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
518 // C++ 6.4p4:
519 // The value of a condition that is an initialized declaration in a statement
520 // other than a switch statement is the value of the declared variable
521 // implicitly converted to type bool. If that conversion is ill-formed, the
522 // program is ill-formed.
523 // The value of a condition that is an expression is the value of the
524 // expression, implicitly converted to bool.
525 //
526 QualType Ty = CondExpr->getType(); // Save the type.
527 AssignConvertType
528 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr);
529 if (ConvTy == Incompatible)
530 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition,
531 Ty.getAsString(), CondExpr->getSourceRange());
532 return false;
533}
Douglas Gregor77a52232008-09-12 00:47:35 +0000534
535/// Helper function to determine whether this is the (deprecated) C++
536/// conversion from a string literal to a pointer to non-const char or
537/// non-const wchar_t (for narrow and wide string literals,
538/// respectively).
539bool
540Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
541 // Look inside the implicit cast, if it exists.
542 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
543 From = Cast->getSubExpr();
544
545 // A string literal (2.13.4) that is not a wide string literal can
546 // be converted to an rvalue of type "pointer to char"; a wide
547 // string literal can be converted to an rvalue of type "pointer
548 // to wchar_t" (C++ 4.2p2).
549 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
550 if (const PointerType *ToPtrType = ToType->getAsPointerType())
551 if (const BuiltinType *ToPointeeType
552 = ToPtrType->getPointeeType()->getAsBuiltinType()) {
553 // This conversion is considered only when there is an
554 // explicit appropriate pointer target type (C++ 4.2p2).
555 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
556 ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
557 (!StrLit->isWide() &&
558 (ToPointeeType->getKind() == BuiltinType::Char_U ||
559 ToPointeeType->getKind() == BuiltinType::Char_S))))
560 return true;
561 }
562
563 return false;
564}
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000565
566/// PerformImplicitConversion - Perform an implicit conversion of the
567/// expression From to the type ToType. Returns true if there was an
568/// error, false otherwise. The expression From is replaced with the
569/// converted expression.
570bool
571Sema::PerformImplicitConversion(Expr *&From, QualType ToType)
572{
573 ImplicitConversionSequence ICS = TryCopyInitialization(From, ToType);
574 switch (ICS.ConversionKind) {
575 case ImplicitConversionSequence::StandardConversion:
576 if (PerformImplicitConversion(From, ToType, ICS.Standard))
577 return true;
578 break;
579
580 case ImplicitConversionSequence::UserDefinedConversion:
581 // FIXME: This is, of course, wrong. We'll need to actually call
582 // the constructor or conversion operator, and then cope with the
583 // standard conversions.
584 ImpCastExprToType(From, ToType);
585 break;
586
587 case ImplicitConversionSequence::EllipsisConversion:
588 assert(false && "Cannot perform an ellipsis conversion");
589 break;
590
591 case ImplicitConversionSequence::BadConversion:
592 return true;
593 }
594
595 // Everything went well.
596 return false;
597}
598
599/// PerformImplicitConversion - Perform an implicit conversion of the
600/// expression From to the type ToType by following the standard
601/// conversion sequence SCS. Returns true if there was an error, false
602/// otherwise. The expression From is replaced with the converted
603/// expression.
604bool
605Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
606 const StandardConversionSequence& SCS)
607{
608 // Overall FIXME: we are recomputing too many types here and doing
609 // far too much extra work. What this means is that we need to keep
610 // track of more information that is computed when we try the
611 // implicit conversion initially, so that we don't need to recompute
612 // anything here.
613 QualType FromType = From->getType();
614
615 // Perform the first implicit conversion.
616 switch (SCS.First) {
617 case ICK_Identity:
618 case ICK_Lvalue_To_Rvalue:
619 // Nothing to do.
620 break;
621
622 case ICK_Array_To_Pointer:
623 FromType = Context.getArrayDecayedType(FromType);
624 ImpCastExprToType(From, FromType);
625 break;
626
627 case ICK_Function_To_Pointer:
628 FromType = Context.getPointerType(FromType);
629 ImpCastExprToType(From, FromType);
630 break;
631
632 default:
633 assert(false && "Improper first standard conversion");
634 break;
635 }
636
637 // Perform the second implicit conversion
638 switch (SCS.Second) {
639 case ICK_Identity:
640 // Nothing to do.
641 break;
642
643 case ICK_Integral_Promotion:
644 case ICK_Floating_Promotion:
645 case ICK_Integral_Conversion:
646 case ICK_Floating_Conversion:
647 case ICK_Floating_Integral:
648 FromType = ToType.getUnqualifiedType();
649 ImpCastExprToType(From, FromType);
650 break;
651
652 case ICK_Pointer_Conversion:
653 if (CheckPointerConversion(From, ToType))
654 return true;
655 ImpCastExprToType(From, ToType);
656 break;
657
658 case ICK_Pointer_Member:
659 // FIXME: Implement pointer-to-member conversions.
660 assert(false && "Pointer-to-member conversions are unsupported");
661 break;
662
663 case ICK_Boolean_Conversion:
664 FromType = Context.BoolTy;
665 ImpCastExprToType(From, FromType);
666 break;
667
668 default:
669 assert(false && "Improper second standard conversion");
670 break;
671 }
672
673 switch (SCS.Third) {
674 case ICK_Identity:
675 // Nothing to do.
676 break;
677
678 case ICK_Qualification:
679 ImpCastExprToType(From, ToType);
680 break;
681
682 default:
683 assert(false && "Improper second standard conversion");
684 break;
685 }
686
687 return false;
688}
689