SemaExprCXX.cpp revision d5a56f0e5d8f495a471fe739195f86756e22de48
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "SemaInherit.h" 16#include "clang/AST/ExprCXX.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/Parse/DeclSpec.h" 19#include "clang/Lex/Preprocessor.h" 20#include "clang/Basic/Diagnostic.h" 21#include "llvm/ADT/SmallVector.h" 22#include "llvm/Support/Debug.h" 23using namespace clang; 24 25/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 26Action::ExprResult 27Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 28 SourceLocation LAngleBracketLoc, TypeTy *Ty, 29 SourceLocation RAngleBracketLoc, 30 SourceLocation LParenLoc, ExprTy *E, 31 SourceLocation RParenLoc) { 32 Expr *Ex = (Expr*)E; 33 QualType DestType = QualType::getFromOpaquePtr(Ty); 34 SourceRange OpRange(OpLoc, RParenLoc); 35 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc); 36 37 switch (Kind) { 38 default: assert(0 && "Unknown C++ cast!"); 39 40 case tok::kw_const_cast: 41 CheckConstCast(Ex, DestType, OpRange, DestRange); 42 return new CXXConstCastExpr(DestType.getNonReferenceType(), Ex, 43 DestType, OpLoc); 44 45 case tok::kw_dynamic_cast: 46 CheckDynamicCast(Ex, DestType, OpRange, DestRange); 47 return new CXXDynamicCastExpr(DestType.getNonReferenceType(), Ex, 48 DestType, OpLoc); 49 50 case tok::kw_reinterpret_cast: 51 CheckReinterpretCast(Ex, DestType, OpRange, DestRange); 52 return new CXXReinterpretCastExpr(DestType.getNonReferenceType(), Ex, 53 DestType, OpLoc); 54 55 case tok::kw_static_cast: 56 CheckStaticCast(Ex, DestType, OpRange); 57 return new CXXStaticCastExpr(DestType.getNonReferenceType(), Ex, 58 DestType, OpLoc); 59 } 60 61 return true; 62} 63 64/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid. 65/// Refer to C++ 5.2.11 for details. const_cast is typically used in code 66/// like this: 67/// const char *str = "literal"; 68/// legacy_function(const_cast\<char*\>(str)); 69void 70Sema::CheckConstCast(Expr *&SrcExpr, QualType DestType, 71 const SourceRange &OpRange, const SourceRange &DestRange) 72{ 73 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType(); 74 75 DestType = Context.getCanonicalType(DestType); 76 QualType SrcType = SrcExpr->getType(); 77 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) { 78 if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) { 79 // Cannot cast non-lvalue to reference type. 80 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue, 81 "const_cast", OrigDestType.getAsString(), SrcExpr->getSourceRange()); 82 return; 83 } 84 85 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2 86 // [...] if a pointer to T1 can be [cast] to the type pointer to T2. 87 DestType = Context.getPointerType(DestTypeTmp->getPointeeType()); 88 SrcType = Context.getPointerType(SrcType); 89 } else { 90 // C++ 5.2.11p1: Otherwise, the result is an rvalue and the 91 // lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard 92 // conversions are performed on the expression. 93 DefaultFunctionArrayConversion(SrcExpr); 94 SrcType = SrcExpr->getType(); 95 } 96 97 if (!DestType->isPointerType()) { 98 // Cannot cast to non-pointer, non-reference type. Note that, if DestType 99 // was a reference type, we converted it to a pointer above. 100 // C++ 5.2.11p3: For two pointer types [...] 101 Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest, OrigDestType.getAsString(), 102 DestRange); 103 return; 104 } 105 if (DestType->isFunctionPointerType()) { 106 // Cannot cast direct function pointers. 107 // C++ 5.2.11p2: [...] where T is any object type or the void type [...] 108 // T is the ultimate pointee of source and target type. 109 Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest, OrigDestType.getAsString(), 110 DestRange); 111 return; 112 } 113 SrcType = Context.getCanonicalType(SrcType); 114 115 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are 116 // completely equal. 117 // FIXME: const_cast should probably not be able to convert between pointers 118 // to different address spaces. 119 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers 120 // in multi-level pointers may change, but the level count must be the same, 121 // as must be the final pointee type. 122 while (SrcType != DestType && UnwrapSimilarPointerTypes(SrcType, DestType)) { 123 SrcType = SrcType.getUnqualifiedType(); 124 DestType = DestType.getUnqualifiedType(); 125 } 126 127 // Doug Gregor said to disallow this until users complain. 128#if 0 129 // If we end up with constant arrays of equal size, unwrap those too. A cast 130 // from const int [N] to int (&)[N] is invalid by my reading of the 131 // standard, but g++ accepts it even with -ansi -pedantic. 132 // No more than one level, though, so don't embed this in the unwrap loop 133 // above. 134 const ConstantArrayType *SrcTypeArr, *DestTypeArr; 135 if ((SrcTypeArr = Context.getAsConstantArrayType(SrcType)) && 136 (DestTypeArr = Context.getAsConstantArrayType(DestType))) 137 { 138 if (SrcTypeArr->getSize() != DestTypeArr->getSize()) { 139 // Different array sizes. 140 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "const_cast", 141 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange); 142 return; 143 } 144 SrcType = SrcTypeArr->getElementType().getUnqualifiedType(); 145 DestType = DestTypeArr->getElementType().getUnqualifiedType(); 146 } 147#endif 148 149 // Since we're dealing in canonical types, the remainder must be the same. 150 if (SrcType != DestType) { 151 // Cast between unrelated types. 152 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "const_cast", 153 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange); 154 return; 155 } 156} 157 158/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is 159/// valid. 160/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code 161/// like this: 162/// char *bytes = reinterpret_cast\<char*\>(int_ptr); 163void 164Sema::CheckReinterpretCast(Expr *&SrcExpr, QualType DestType, 165 const SourceRange &OpRange, 166 const SourceRange &DestRange) 167{ 168 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType(); 169 170 DestType = Context.getCanonicalType(DestType); 171 QualType SrcType = SrcExpr->getType(); 172 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) { 173 if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) { 174 // Cannot cast non-lvalue to reference type. 175 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue, 176 "reinterpret_cast", OrigDestType.getAsString(), 177 SrcExpr->getSourceRange()); 178 return; 179 } 180 181 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the 182 // same effect as the conversion *reinterpret_cast<T*>(&x) with the 183 // built-in & and * operators. 184 // This code does this transformation for the checked types. 185 DestType = Context.getPointerType(DestTypeTmp->getPointeeType()); 186 SrcType = Context.getPointerType(SrcType); 187 } else { 188 // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and 189 // function-to-pointer standard conversions are performed on the 190 // expression v. 191 DefaultFunctionArrayConversion(SrcExpr); 192 SrcType = SrcExpr->getType(); 193 } 194 195 // Canonicalize source for comparison. 196 SrcType = Context.getCanonicalType(SrcType); 197 198 bool destIsPtr = DestType->isPointerType(); 199 bool srcIsPtr = SrcType->isPointerType(); 200 if (!destIsPtr && !srcIsPtr) { 201 // Except for std::nullptr_t->integer, which is not supported yet, and 202 // lvalue->reference, which is handled above, at least one of the two 203 // arguments must be a pointer. 204 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "reinterpret_cast", 205 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange); 206 return; 207 } 208 209 if (SrcType == DestType) { 210 // C++ 5.2.10p2 has a note that mentions that, subject to all other 211 // restrictions, a cast to the same type is allowed. The intent is not 212 // entirely clear here, since all other paragraphs explicitly forbid casts 213 // to the same type. However, the behavior of compilers is pretty consistent 214 // on this point: allow same-type conversion if the involved are pointers, 215 // disallow otherwise. 216 return; 217 } 218 219 // Note: Clang treats enumeration types as integral types. If this is ever 220 // changed for C++, the additional check here will be redundant. 221 if (DestType->isIntegralType() && !DestType->isEnumeralType()) { 222 assert(srcIsPtr); 223 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral 224 // type large enough to hold it. 225 if (Context.getTypeSize(SrcType) > Context.getTypeSize(DestType)) { 226 Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int, 227 OrigDestType.getAsString(), DestRange); 228 } 229 return; 230 } 231 232 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) { 233 assert(destIsPtr); 234 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly 235 // converted to a pointer. 236 return; 237 } 238 239 if (!destIsPtr || !srcIsPtr) { 240 // With the valid non-pointer conversions out of the way, we can be even 241 // more stringent. 242 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "reinterpret_cast", 243 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange); 244 return; 245 } 246 247 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness. 248 if (CastsAwayConstness(SrcType, DestType)) { 249 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away, 250 "reinterpret_cast", OrigDestType.getAsString(), OrigSrcType.getAsString(), 251 OpRange); 252 return; 253 } 254 255 // Not casting away constness, so the only remaining check is for compatible 256 // pointer categories. 257 258 if (SrcType->isFunctionPointerType()) { 259 if (DestType->isFunctionPointerType()) { 260 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to 261 // a pointer to a function of a different type. 262 return; 263 } 264 265 // FIXME: Handle member pointers. 266 267 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to 268 // an object type or vice versa is conditionally-supported. 269 // Compilers support it in C++03 too, though, because it's necessary for 270 // casting the return value of dlsym() and GetProcAddress(). 271 // FIXME: Conditionally-supported behavior should be configurable in the 272 // TargetInfo or similar. 273 if (!getLangOptions().CPlusPlus0x) { 274 Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj, OpRange); 275 } 276 return; 277 } 278 279 // FIXME: Handle member pointers. 280 281 if (DestType->isFunctionPointerType()) { 282 // See above. 283 if (!getLangOptions().CPlusPlus0x) { 284 Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj, OpRange); 285 } 286 return; 287 } 288 289 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to 290 // a pointer to an object of different type. 291 // Void pointers are not specified, but supported by every compiler out there. 292 // So we finish by allowing everything that remains - it's got to be two 293 // object pointers. 294} 295 296/// CastsAwayConstness - Check if the pointer conversion from SrcType 297/// to DestType casts away constness as defined in C++ 298/// 5.2.11p8ff. This is used by the cast checkers. Both arguments 299/// must denote pointer types. 300bool 301Sema::CastsAwayConstness(QualType SrcType, QualType DestType) 302{ 303 // Casting away constness is defined in C++ 5.2.11p8 with reference to 304 // C++ 4.4. 305 // We piggyback on Sema::IsQualificationConversion for this, since the rules 306 // are non-trivial. So first we construct Tcv *...cv* as described in 307 // C++ 5.2.11p8. 308 SrcType = Context.getCanonicalType(SrcType); 309 DestType = Context.getCanonicalType(DestType); 310 311 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType; 312 llvm::SmallVector<unsigned, 8> cv1, cv2; 313 314 // Find the qualifications. 315 while (UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) { 316 cv1.push_back(UnwrappedSrcType.getCVRQualifiers()); 317 cv2.push_back(UnwrappedDestType.getCVRQualifiers()); 318 } 319 assert(cv1.size() > 0 && "Must have at least one pointer level."); 320 321 // Construct void pointers with those qualifiers (in reverse order of 322 // unwrapping, of course). 323 QualType SrcConstruct = Context.VoidTy; 324 QualType DestConstruct = Context.VoidTy; 325 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(), 326 i2 = cv2.rbegin(); 327 i1 != cv1.rend(); ++i1, ++i2) 328 { 329 SrcConstruct = Context.getPointerType(SrcConstruct.getQualifiedType(*i1)); 330 DestConstruct = Context.getPointerType(DestConstruct.getQualifiedType(*i2)); 331 } 332 333 // Test if they're compatible. 334 return SrcConstruct != DestConstruct && 335 !IsQualificationConversion(SrcConstruct, DestConstruct); 336} 337 338/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid. 339/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making 340/// implicit conversions explicit and getting rid of data loss warnings. 341void 342Sema::CheckStaticCast(Expr *&SrcExpr, QualType DestType, 343 const SourceRange &OpRange) 344{ 345 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType(); 346 347 // Conversions are tried roughly in the order the standard specifies them. 348 // This is necessary because there are some conversions that can be 349 // interpreted in more than one way, and the order disambiguates. 350 // DR 427 specifies that paragraph 5 is to be applied before paragraph 2. 351 352 // This option is unambiguous and simple, so put it here. 353 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void". 354 if (DestType->isVoidType()) { 355 return; 356 } 357 358 DestType = Context.getCanonicalType(DestType); 359 360 // C++ 5.2.9p5, reference downcast. 361 // See the function for details. 362 if (IsStaticReferenceDowncast(SrcExpr, DestType)) { 363 return; 364 } 365 366 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T 367 // [...] if the declaration "T t(e);" is well-formed, [...]. 368 ImplicitConversionSequence ICS = TryDirectInitialization(SrcExpr, DestType); 369 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) { 370 if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion && 371 ICS.Standard.First != ICK_Identity) 372 { 373 DefaultFunctionArrayConversion(SrcExpr); 374 } 375 return; 376 } 377 // FIXME: Missing the validation of the conversion, e.g. for an accessible 378 // base. 379 380 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except 381 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean 382 // conversions, subject to further restrictions. 383 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal 384 // of qualification conversions impossible. 385 386 // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions 387 // are applied to the expression. 388 DefaultFunctionArrayConversion(SrcExpr); 389 390 QualType SrcType = Context.getCanonicalType(SrcExpr->getType()); 391 392 // Reverse integral promotion/conversion. All such conversions are themselves 393 // again integral promotions or conversions and are thus already handled by 394 // p2 (TryDirectInitialization above). 395 // (Note: any data loss warnings should be suppressed.) 396 // The exception is the reverse of enum->integer, i.e. integer->enum (and 397 // enum->enum). See also C++ 5.2.9p7. 398 // The same goes for reverse floating point promotion/conversion and 399 // floating-integral conversions. Again, only floating->enum is relevant. 400 if (DestType->isEnumeralType()) { 401 if (SrcType->isComplexType() || SrcType->isVectorType()) { 402 // Fall through - these cannot be converted. 403 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) { 404 return; 405 } 406 } 407 408 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast. 409 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance. 410 if (IsStaticPointerDowncast(SrcType, DestType)) { 411 return; 412 } 413 414 // Reverse member pointer conversion. C++ 5.11 specifies member pointer 415 // conversion. C++ 5.2.9p9 has additional information. 416 // DR54's access restrictions apply here also. 417 // FIXME: Don't have member pointers yet. 418 419 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to 420 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is 421 // just the usual constness stuff. 422 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) { 423 QualType SrcPointee = SrcPointer->getPointeeType(); 424 if (SrcPointee->isVoidType()) { 425 if (const PointerType *DestPointer = DestType->getAsPointerType()) { 426 QualType DestPointee = DestPointer->getPointeeType(); 427 if (DestPointee->isObjectType() && 428 DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) 429 { 430 return; 431 } 432 } 433 } 434 } 435 436 // We tried everything. Everything! Nothing works! :-( 437 // FIXME: Error reporting could be a lot better. Should store the reason 438 // why every substep failed and, at the end, select the most specific and 439 // report that. 440 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "static_cast", 441 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange); 442} 443 444/// Tests whether a conversion according to C++ 5.2.9p5 is valid. 445bool 446Sema::IsStaticReferenceDowncast(Expr *SrcExpr, QualType DestType) 447{ 448 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be 449 // cast to type "reference to cv2 D", where D is a class derived from B, 450 // if a valid standard conversion from "pointer to D" to "pointer to B" 451 // exists, cv2 >= cv1, and B is not a virtual base class of D. 452 // In addition, DR54 clarifies that the base must be accessible in the 453 // current context. Although the wording of DR54 only applies to the pointer 454 // variant of this rule, the intent is clearly for it to apply to the this 455 // conversion as well. 456 457 if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) { 458 return false; 459 } 460 461 DestType = Context.getCanonicalType(DestType); 462 const ReferenceType *DestReference = DestType->getAsReferenceType(); 463 if (!DestReference) { 464 return false; 465 } 466 QualType DestPointee = DestReference->getPointeeType(); 467 468 QualType SrcType = Context.getCanonicalType(SrcExpr->getType()); 469 470 return IsStaticDowncast(SrcType, DestPointee); 471} 472 473/// Tests whether a conversion according to C++ 5.2.9p8 is valid. 474bool 475Sema::IsStaticPointerDowncast(QualType SrcType, QualType DestType) 476{ 477 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class 478 // type, can be converted to an rvalue of type "pointer to cv2 D", where D 479 // is a class derived from B, if a valid standard conversion from "pointer 480 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base 481 // class of D. 482 // In addition, DR54 clarifies that the base must be accessible in the 483 // current context. 484 485 SrcType = Context.getCanonicalType(SrcType); 486 const PointerType *SrcPointer = SrcType->getAsPointerType(); 487 if (!SrcPointer) { 488 return false; 489 } 490 491 DestType = Context.getCanonicalType(DestType); 492 const PointerType *DestPointer = DestType->getAsPointerType(); 493 if (!DestPointer) { 494 return false; 495 } 496 497 return IsStaticDowncast(SrcPointer->getPointeeType(), 498 DestPointer->getPointeeType()); 499} 500 501/// IsStaticDowncast - Common functionality of IsStaticReferenceDowncast and 502/// IsStaticPointerDowncast. Tests whether a static downcast from SrcType to 503/// DestType, both of which must be canonical, is possible and allowed. 504bool 505Sema::IsStaticDowncast(QualType SrcType, QualType DestType) 506{ 507 assert(SrcType->isCanonical()); 508 assert(DestType->isCanonical()); 509 510 if (!DestType->isRecordType()) { 511 return false; 512 } 513 514 if (!SrcType->isRecordType()) { 515 return false; 516 } 517 518 // Comparing cv is cheaper, so do it first. 519 if (!DestType.isAtLeastAsQualifiedAs(SrcType)) { 520 return false; 521 } 522 523 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 524 /*DetectVirtual=*/true); 525 if (!IsDerivedFrom(DestType, SrcType, Paths)) { 526 return false; 527 } 528 529 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) { 530 return false; 531 } 532 533 if (Paths.getDetectedVirtual() != 0) { 534 return false; 535 } 536 537 // FIXME: Test accessibility. 538 539 return true; 540} 541 542/// TryDirectInitialization - Attempt to direct-initialize a value of the 543/// given type (DestType) from the given expression (SrcExpr), as one would 544/// do when creating an object with new with parameters. This function returns 545/// an implicit conversion sequence that can be used to perform the 546/// initialization. 547/// This routine is very similar to TryCopyInitialization; the differences 548/// between the two (C++ 8.5p12 and C++ 8.5p14) are: 549/// 1) In direct-initialization, all constructors of the target type are 550/// considered, including those marked as explicit. 551/// 2) In direct-initialization, overload resolution is performed over the 552/// constructors of the target type. In copy-initialization, overload 553/// resolution is performed over all conversion functions that result in 554/// the target type. This can lead to different functions used. 555ImplicitConversionSequence 556Sema::TryDirectInitialization(Expr *SrcExpr, QualType DestType) 557{ 558 if (!DestType->isRecordType()) { 559 // For non-class types, copy and direct initialization are identical. 560 // C++ 8.5p11 561 // FIXME: Those parts should be in a common function, actually. 562 return TryCopyInitialization(SrcExpr, DestType); 563 } 564 565 // Not enough support for the rest yet, actually. 566 ImplicitConversionSequence ICS; 567 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 568 return ICS; 569} 570 571/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid. 572/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime- 573/// checked downcasts in class hierarchies. 574void 575Sema::CheckDynamicCast(Expr *&SrcExpr, QualType DestType, 576 const SourceRange &OpRange, 577 const SourceRange &DestRange) 578{ 579 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType(); 580 DestType = Context.getCanonicalType(DestType); 581 582 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type, 583 // or "pointer to cv void". 584 585 QualType DestPointee; 586 const PointerType *DestPointer = DestType->getAsPointerType(); 587 const ReferenceType *DestReference = DestType->getAsReferenceType(); 588 if (DestPointer) { 589 DestPointee = DestPointer->getPointeeType(); 590 } else if (DestReference) { 591 DestPointee = DestReference->getPointeeType(); 592 } else { 593 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_operand, 594 OrigDestType.getAsString(), "not a reference or pointer", DestRange); 595 return; 596 } 597 598 const RecordType *DestRecord = DestPointee->getAsRecordType(); 599 if (DestPointee->isVoidType()) { 600 assert(DestPointer && "Reference to void is not possible"); 601 } else if (DestRecord) { 602 if (!DestRecord->getDecl()->isDefinition()) { 603 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_operand, 604 DestPointee.getUnqualifiedType().getAsString(), 605 "incomplete", DestRange); 606 return; 607 } 608 } else { 609 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_operand, 610 DestPointee.getUnqualifiedType().getAsString(), 611 "not a class", DestRange); 612 return; 613 } 614 615 // C++ 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to 616 // complete class type, [...]. If T is a reference type, v shall be an 617 // lvalue of a complete class type, [...]. 618 619 QualType SrcType = Context.getCanonicalType(OrigSrcType); 620 QualType SrcPointee; 621 if (DestPointer) { 622 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) { 623 SrcPointee = SrcPointer->getPointeeType(); 624 } else { 625 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_operand, 626 OrigSrcType.getAsString(), "not a pointer", SrcExpr->getSourceRange()); 627 return; 628 } 629 } else { 630 if (SrcExpr->isLvalue(Context) != Expr::LV_Valid) { 631 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_operand, 632 OrigDestType.getAsString(), "not an lvalue", SrcExpr->getSourceRange()); 633 } 634 SrcPointee = SrcType; 635 } 636 637 const RecordType *SrcRecord = SrcPointee->getAsRecordType(); 638 if (SrcRecord) { 639 if (!SrcRecord->getDecl()->isDefinition()) { 640 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_operand, 641 SrcPointee.getUnqualifiedType().getAsString(), "incomplete", 642 SrcExpr->getSourceRange()); 643 return; 644 } 645 } else { 646 Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_operand, 647 SrcPointee.getUnqualifiedType().getAsString(), "not a class", 648 SrcExpr->getSourceRange()); 649 return; 650 } 651 652 // Assumptions to this point. 653 assert(DestPointer || DestReference); 654 assert(DestRecord || DestPointee->isVoidType()); 655 assert(SrcRecord); 656 657 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness. 658 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) { 659 Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away, "dynamic_cast", 660 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange); 661 return; 662 } 663 664 // C++ 5.2.7p3: If the type of v is the same as the required result type, 665 // [except for cv]. 666 if (DestRecord == SrcRecord) { 667 return; 668 } 669 670 // C++ 5.2.7p5 671 // Upcasts are resolved statically. 672 if (DestRecord && IsDerivedFrom(SrcPointee, DestPointee)) { 673 CheckDerivedToBaseConversion(SrcPointee, DestPointee, OpRange.getBegin(), 674 OpRange); 675 // Diagnostic already emitted on error. 676 return; 677 } 678 679 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic]. 680 // FIXME: Information not yet available. 681 682 // Done. Everything else is run-time checks. 683} 684 685/// ActOnCXXBoolLiteral - Parse {true,false} literals. 686Action::ExprResult 687Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 688 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 689 "Unknown C++ Boolean value!"); 690 return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); 691} 692 693/// ActOnCXXThrow - Parse throw expressions. 694Action::ExprResult 695Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) { 696 return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc); 697} 698 699Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 700 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 701 /// is a non-lvalue expression whose value is the address of the object for 702 /// which the function is called. 703 704 if (!isa<FunctionDecl>(CurContext)) { 705 Diag(ThisLoc, diag::err_invalid_this_use); 706 return ExprResult(true); 707 } 708 709 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) 710 if (MD->isInstance()) 711 return new PredefinedExpr(ThisLoc, MD->getThisType(Context), 712 PredefinedExpr::CXXThis); 713 714 return Diag(ThisLoc, diag::err_invalid_this_use); 715} 716 717/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 718/// Can be interpreted either as function-style casting ("int(x)") 719/// or class type construction ("ClassType(x,y,z)") 720/// or creation of a value-initialized type ("int()"). 721Action::ExprResult 722Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 723 SourceLocation LParenLoc, 724 ExprTy **ExprTys, unsigned NumExprs, 725 SourceLocation *CommaLocs, 726 SourceLocation RParenLoc) { 727 assert(TypeRep && "Missing type!"); 728 QualType Ty = QualType::getFromOpaquePtr(TypeRep); 729 Expr **Exprs = (Expr**)ExprTys; 730 SourceLocation TyBeginLoc = TypeRange.getBegin(); 731 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 732 733 if (const RecordType *RT = Ty->getAsRecordType()) { 734 // C++ 5.2.3p1: 735 // If the simple-type-specifier specifies a class type, the class type shall 736 // be complete. 737 // 738 if (!RT->getDecl()->isDefinition()) 739 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use, 740 Ty.getAsString(), FullRange); 741 742 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error, 743 "class constructors are not supported yet"); 744 return Diag(TyBeginLoc, DiagID); 745 } 746 747 // C++ 5.2.3p1: 748 // If the expression list is a single expression, the type conversion 749 // expression is equivalent (in definedness, and if defined in meaning) to the 750 // corresponding cast expression. 751 // 752 if (NumExprs == 1) { 753 if (CheckCastTypes(TypeRange, Ty, Exprs[0])) 754 return true; 755 return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc, 756 Exprs[0], RParenLoc); 757 } 758 759 // C++ 5.2.3p1: 760 // If the expression list specifies more than a single value, the type shall 761 // be a class with a suitably declared constructor. 762 // 763 if (NumExprs > 1) 764 return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg, 765 FullRange); 766 767 assert(NumExprs == 0 && "Expected 0 expressions"); 768 769 // C++ 5.2.3p2: 770 // The expression T(), where T is a simple-type-specifier for a non-array 771 // complete object type or the (possibly cv-qualified) void type, creates an 772 // rvalue of the specified type, which is value-initialized. 773 // 774 if (Ty->isArrayType()) 775 return Diag(TyBeginLoc, diag::err_value_init_for_array_type, FullRange); 776 if (Ty->isIncompleteType() && !Ty->isVoidType()) 777 return Diag(TyBeginLoc, diag::err_invalid_incomplete_type_use, 778 Ty.getAsString(), FullRange); 779 780 return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc); 781} 782 783 784/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 785/// C++ if/switch/while/for statement. 786/// e.g: "if (int x = f()) {...}" 787Action::ExprResult 788Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc, 789 Declarator &D, 790 SourceLocation EqualLoc, 791 ExprTy *AssignExprVal) { 792 assert(AssignExprVal && "Null assignment expression"); 793 794 // C++ 6.4p2: 795 // The declarator shall not specify a function or an array. 796 // The type-specifier-seq shall not contain typedef and shall not declare a 797 // new class or enumeration. 798 799 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 800 "Parser allowed 'typedef' as storage class of condition decl."); 801 802 QualType Ty = GetTypeForDeclarator(D, S); 803 804 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 805 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 806 // would be created and CXXConditionDeclExpr wants a VarDecl. 807 return Diag(StartLoc, diag::err_invalid_use_of_function_type, 808 SourceRange(StartLoc, EqualLoc)); 809 } else if (Ty->isArrayType()) { // ...or an array. 810 Diag(StartLoc, diag::err_invalid_use_of_array_type, 811 SourceRange(StartLoc, EqualLoc)); 812 } else if (const RecordType *RT = Ty->getAsRecordType()) { 813 RecordDecl *RD = RT->getDecl(); 814 // The type-specifier-seq shall not declare a new class... 815 if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD))) 816 Diag(RD->getLocation(), diag::err_type_defined_in_condition); 817 } else if (const EnumType *ET = Ty->getAsEnumType()) { 818 EnumDecl *ED = ET->getDecl(); 819 // ...or enumeration. 820 if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED))) 821 Diag(ED->getLocation(), diag::err_type_defined_in_condition); 822 } 823 824 DeclTy *Dcl = ActOnDeclarator(S, D, 0); 825 if (!Dcl) 826 return true; 827 AddInitializerToDecl(Dcl, AssignExprVal); 828 829 return new CXXConditionDeclExpr(StartLoc, EqualLoc, 830 cast<VarDecl>(static_cast<Decl *>(Dcl))); 831} 832 833/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 834bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 835 // C++ 6.4p4: 836 // The value of a condition that is an initialized declaration in a statement 837 // other than a switch statement is the value of the declared variable 838 // implicitly converted to type bool. If that conversion is ill-formed, the 839 // program is ill-formed. 840 // The value of a condition that is an expression is the value of the 841 // expression, implicitly converted to bool. 842 // 843 QualType Ty = CondExpr->getType(); // Save the type. 844 AssignConvertType 845 ConvTy = CheckSingleAssignmentConstraints(Context.BoolTy, CondExpr); 846 if (ConvTy == Incompatible) 847 return Diag(CondExpr->getLocStart(), diag::err_typecheck_bool_condition, 848 Ty.getAsString(), CondExpr->getSourceRange()); 849 return false; 850} 851 852/// Helper function to determine whether this is the (deprecated) C++ 853/// conversion from a string literal to a pointer to non-const char or 854/// non-const wchar_t (for narrow and wide string literals, 855/// respectively). 856bool 857Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 858 // Look inside the implicit cast, if it exists. 859 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 860 From = Cast->getSubExpr(); 861 862 // A string literal (2.13.4) that is not a wide string literal can 863 // be converted to an rvalue of type "pointer to char"; a wide 864 // string literal can be converted to an rvalue of type "pointer 865 // to wchar_t" (C++ 4.2p2). 866 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 867 if (const PointerType *ToPtrType = ToType->getAsPointerType()) 868 if (const BuiltinType *ToPointeeType 869 = ToPtrType->getPointeeType()->getAsBuiltinType()) { 870 // This conversion is considered only when there is an 871 // explicit appropriate pointer target type (C++ 4.2p2). 872 if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 && 873 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 874 (!StrLit->isWide() && 875 (ToPointeeType->getKind() == BuiltinType::Char_U || 876 ToPointeeType->getKind() == BuiltinType::Char_S)))) 877 return true; 878 } 879 880 return false; 881} 882 883/// PerformImplicitConversion - Perform an implicit conversion of the 884/// expression From to the type ToType. Returns true if there was an 885/// error, false otherwise. The expression From is replaced with the 886/// converted expression. 887bool 888Sema::PerformImplicitConversion(Expr *&From, QualType ToType) 889{ 890 ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType); 891 switch (ICS.ConversionKind) { 892 case ImplicitConversionSequence::StandardConversion: 893 if (PerformImplicitConversion(From, ToType, ICS.Standard)) 894 return true; 895 break; 896 897 case ImplicitConversionSequence::UserDefinedConversion: 898 // FIXME: This is, of course, wrong. We'll need to actually call 899 // the constructor or conversion operator, and then cope with the 900 // standard conversions. 901 ImpCastExprToType(From, ToType); 902 return false; 903 904 case ImplicitConversionSequence::EllipsisConversion: 905 assert(false && "Cannot perform an ellipsis conversion"); 906 return false; 907 908 case ImplicitConversionSequence::BadConversion: 909 return true; 910 } 911 912 // Everything went well. 913 return false; 914} 915 916/// PerformImplicitConversion - Perform an implicit conversion of the 917/// expression From to the type ToType by following the standard 918/// conversion sequence SCS. Returns true if there was an error, false 919/// otherwise. The expression From is replaced with the converted 920/// expression. 921bool 922Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 923 const StandardConversionSequence& SCS) 924{ 925 // Overall FIXME: we are recomputing too many types here and doing 926 // far too much extra work. What this means is that we need to keep 927 // track of more information that is computed when we try the 928 // implicit conversion initially, so that we don't need to recompute 929 // anything here. 930 QualType FromType = From->getType(); 931 932 // Perform the first implicit conversion. 933 switch (SCS.First) { 934 case ICK_Identity: 935 case ICK_Lvalue_To_Rvalue: 936 // Nothing to do. 937 break; 938 939 case ICK_Array_To_Pointer: 940 FromType = Context.getArrayDecayedType(FromType); 941 ImpCastExprToType(From, FromType); 942 break; 943 944 case ICK_Function_To_Pointer: 945 FromType = Context.getPointerType(FromType); 946 ImpCastExprToType(From, FromType); 947 break; 948 949 default: 950 assert(false && "Improper first standard conversion"); 951 break; 952 } 953 954 // Perform the second implicit conversion 955 switch (SCS.Second) { 956 case ICK_Identity: 957 // Nothing to do. 958 break; 959 960 case ICK_Integral_Promotion: 961 case ICK_Floating_Promotion: 962 case ICK_Integral_Conversion: 963 case ICK_Floating_Conversion: 964 case ICK_Floating_Integral: 965 FromType = ToType.getUnqualifiedType(); 966 ImpCastExprToType(From, FromType); 967 break; 968 969 case ICK_Pointer_Conversion: 970 if (CheckPointerConversion(From, ToType)) 971 return true; 972 ImpCastExprToType(From, ToType); 973 break; 974 975 case ICK_Pointer_Member: 976 // FIXME: Implement pointer-to-member conversions. 977 assert(false && "Pointer-to-member conversions are unsupported"); 978 break; 979 980 case ICK_Boolean_Conversion: 981 FromType = Context.BoolTy; 982 ImpCastExprToType(From, FromType); 983 break; 984 985 default: 986 assert(false && "Improper second standard conversion"); 987 break; 988 } 989 990 switch (SCS.Third) { 991 case ICK_Identity: 992 // Nothing to do. 993 break; 994 995 case ICK_Qualification: 996 ImpCastExprToType(From, ToType); 997 break; 998 999 default: 1000 assert(false && "Improper second standard conversion"); 1001 break; 1002 } 1003 1004 return false; 1005} 1006 1007