ExprConstant.cpp revision 7d99bc37e77157523e3bfbc6c077842b74e6690f
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 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 the Expr constant evaluator. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/AST/APValue.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/CharUnits.h" 17#include "clang/AST/RecordLayout.h" 18#include "clang/AST/StmtVisitor.h" 19#include "clang/AST/TypeLoc.h" 20#include "clang/AST/ASTDiagnostic.h" 21#include "clang/AST/Expr.h" 22#include "clang/Basic/Builtins.h" 23#include "clang/Basic/TargetInfo.h" 24#include "llvm/ADT/SmallString.h" 25#include <cstring> 26 27using namespace clang; 28using llvm::APSInt; 29using llvm::APFloat; 30 31/// EvalInfo - This is a private struct used by the evaluator to capture 32/// information about a subexpression as it is folded. It retains information 33/// about the AST context, but also maintains information about the folded 34/// expression. 35/// 36/// If an expression could be evaluated, it is still possible it is not a C 37/// "integer constant expression" or constant expression. If not, this struct 38/// captures information about how and why not. 39/// 40/// One bit of information passed *into* the request for constant folding 41/// indicates whether the subexpression is "evaluated" or not according to C 42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 43/// evaluate the expression regardless of what the RHS is, but C only allows 44/// certain things in certain situations. 45namespace { 46 struct EvalInfo { 47 const ASTContext &Ctx; 48 49 /// EvalResult - Contains information about the evaluation. 50 Expr::EvalResult &EvalResult; 51 52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy; 53 MapTy OpaqueValues; 54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const { 55 MapTy::const_iterator i = OpaqueValues.find(e); 56 if (i == OpaqueValues.end()) return 0; 57 return &i->second; 58 } 59 60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult) 61 : Ctx(ctx), EvalResult(evalresult) {} 62 }; 63 64 struct ComplexValue { 65 private: 66 bool IsInt; 67 68 public: 69 APSInt IntReal, IntImag; 70 APFloat FloatReal, FloatImag; 71 72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {} 73 74 void makeComplexFloat() { IsInt = false; } 75 bool isComplexFloat() const { return !IsInt; } 76 APFloat &getComplexFloatReal() { return FloatReal; } 77 APFloat &getComplexFloatImag() { return FloatImag; } 78 79 void makeComplexInt() { IsInt = true; } 80 bool isComplexInt() const { return IsInt; } 81 APSInt &getComplexIntReal() { return IntReal; } 82 APSInt &getComplexIntImag() { return IntImag; } 83 84 void moveInto(APValue &v) const { 85 if (isComplexFloat()) 86 v = APValue(FloatReal, FloatImag); 87 else 88 v = APValue(IntReal, IntImag); 89 } 90 void setFrom(const APValue &v) { 91 assert(v.isComplexFloat() || v.isComplexInt()); 92 if (v.isComplexFloat()) { 93 makeComplexFloat(); 94 FloatReal = v.getComplexFloatReal(); 95 FloatImag = v.getComplexFloatImag(); 96 } else { 97 makeComplexInt(); 98 IntReal = v.getComplexIntReal(); 99 IntImag = v.getComplexIntImag(); 100 } 101 } 102 }; 103 104 struct LValue { 105 Expr *Base; 106 CharUnits Offset; 107 108 Expr *getLValueBase() { return Base; } 109 CharUnits getLValueOffset() { return Offset; } 110 111 void moveInto(APValue &v) const { 112 v = APValue(Base, Offset); 113 } 114 void setFrom(const APValue &v) { 115 assert(v.isLValue()); 116 Base = v.getLValueBase(); 117 Offset = v.getLValueOffset(); 118 } 119 }; 120} 121 122static bool Evaluate(EvalInfo &info, const Expr *E); 123static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info); 124static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info); 125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 127 EvalInfo &Info); 128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 130 131//===----------------------------------------------------------------------===// 132// Misc utilities 133//===----------------------------------------------------------------------===// 134 135static bool IsGlobalLValue(const Expr* E) { 136 if (!E) return true; 137 138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 139 if (isa<FunctionDecl>(DRE->getDecl())) 140 return true; 141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 142 return VD->hasGlobalStorage(); 143 return false; 144 } 145 146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E)) 147 return CLE->isFileScope(); 148 149 return true; 150} 151 152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) { 153 const Expr* Base = Value.Base; 154 155 // A null base expression indicates a null pointer. These are always 156 // evaluatable, and they are false unless the offset is zero. 157 if (!Base) { 158 Result = !Value.Offset.isZero(); 159 return true; 160 } 161 162 // Require the base expression to be a global l-value. 163 if (!IsGlobalLValue(Base)) return false; 164 165 // We have a non-null base expression. These are generally known to 166 // be true, but if it'a decl-ref to a weak symbol it can be null at 167 // runtime. 168 Result = true; 169 170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base); 171 if (!DeclRef) 172 return true; 173 174 // If it's a weak symbol, it isn't constant-evaluable. 175 const ValueDecl* Decl = DeclRef->getDecl(); 176 if (Decl->hasAttr<WeakAttr>() || 177 Decl->hasAttr<WeakRefAttr>() || 178 Decl->isWeakImported()) 179 return false; 180 181 return true; 182} 183 184static bool HandleConversionToBool(const Expr* E, bool& Result, 185 EvalInfo &Info) { 186 if (E->getType()->isIntegralOrEnumerationType()) { 187 APSInt IntResult; 188 if (!EvaluateInteger(E, IntResult, Info)) 189 return false; 190 Result = IntResult != 0; 191 return true; 192 } else if (E->getType()->isRealFloatingType()) { 193 APFloat FloatResult(0.0); 194 if (!EvaluateFloat(E, FloatResult, Info)) 195 return false; 196 Result = !FloatResult.isZero(); 197 return true; 198 } else if (E->getType()->hasPointerRepresentation()) { 199 LValue PointerResult; 200 if (!EvaluatePointer(E, PointerResult, Info)) 201 return false; 202 return EvalPointerValueAsBool(PointerResult, Result); 203 } else if (E->getType()->isAnyComplexType()) { 204 ComplexValue ComplexResult; 205 if (!EvaluateComplex(E, ComplexResult, Info)) 206 return false; 207 if (ComplexResult.isComplexFloat()) { 208 Result = !ComplexResult.getComplexFloatReal().isZero() || 209 !ComplexResult.getComplexFloatImag().isZero(); 210 } else { 211 Result = ComplexResult.getComplexIntReal().getBoolValue() || 212 ComplexResult.getComplexIntImag().getBoolValue(); 213 } 214 return true; 215 } 216 217 return false; 218} 219 220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType, 221 APFloat &Value, const ASTContext &Ctx) { 222 unsigned DestWidth = Ctx.getIntWidth(DestType); 223 // Determine whether we are converting to unsigned or signed. 224 bool DestSigned = DestType->isSignedIntegerType(); 225 226 // FIXME: Warning for overflow. 227 uint64_t Space[4]; 228 bool ignored; 229 (void)Value.convertToInteger(Space, DestWidth, DestSigned, 230 llvm::APFloat::rmTowardZero, &ignored); 231 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned); 232} 233 234static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType, 235 APFloat &Value, const ASTContext &Ctx) { 236 bool ignored; 237 APFloat Result = Value; 238 Result.convert(Ctx.getFloatTypeSemantics(DestType), 239 APFloat::rmNearestTiesToEven, &ignored); 240 return Result; 241} 242 243static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType, 244 APSInt &Value, const ASTContext &Ctx) { 245 unsigned DestWidth = Ctx.getIntWidth(DestType); 246 APSInt Result = Value; 247 // Figure out if this is a truncate, extend or noop cast. 248 // If the input is signed, do a sign extend, noop, or truncate. 249 Result = Result.extOrTrunc(DestWidth); 250 Result.setIsUnsigned(DestType->isUnsignedIntegerType()); 251 return Result; 252} 253 254static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType, 255 APSInt &Value, const ASTContext &Ctx) { 256 257 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1); 258 Result.convertFromAPInt(Value, Value.isSigned(), 259 APFloat::rmNearestTiesToEven); 260 return Result; 261} 262 263namespace { 264class HasSideEffect 265 : public StmtVisitor<HasSideEffect, bool> { 266 EvalInfo &Info; 267public: 268 269 HasSideEffect(EvalInfo &info) : Info(info) {} 270 271 // Unhandled nodes conservatively default to having side effects. 272 bool VisitStmt(Stmt *S) { 273 return true; 274 } 275 276 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 277 bool VisitDeclRefExpr(DeclRefExpr *E) { 278 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 279 return true; 280 return false; 281 } 282 // We don't want to evaluate BlockExprs multiple times, as they generate 283 // a ton of code. 284 bool VisitBlockExpr(BlockExpr *E) { return true; } 285 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; } 286 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E) 287 { return Visit(E->getInitializer()); } 288 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); } 289 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; } 290 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; } 291 bool VisitStringLiteral(StringLiteral *E) { return false; } 292 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; } 293 bool VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) 294 { return false; } 295 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E) 296 { return Visit(E->getLHS()) || Visit(E->getRHS()); } 297 bool VisitChooseExpr(ChooseExpr *E) 298 { return Visit(E->getChosenSubExpr(Info.Ctx)); } 299 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); } 300 bool VisitBinAssign(BinaryOperator *E) { return true; } 301 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; } 302 bool VisitBinaryOperator(BinaryOperator *E) 303 { return Visit(E->getLHS()) || Visit(E->getRHS()); } 304 bool VisitUnaryPreInc(UnaryOperator *E) { return true; } 305 bool VisitUnaryPostInc(UnaryOperator *E) { return true; } 306 bool VisitUnaryPreDec(UnaryOperator *E) { return true; } 307 bool VisitUnaryPostDec(UnaryOperator *E) { return true; } 308 bool VisitUnaryDeref(UnaryOperator *E) { 309 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 310 return true; 311 return Visit(E->getSubExpr()); 312 } 313 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); } 314 315 // Has side effects if any element does. 316 bool VisitInitListExpr(InitListExpr *E) { 317 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i) 318 if (Visit(E->getInit(i))) return true; 319 return false; 320 } 321 322 bool VisitSizeOfPackExpr(SizeOfPackExpr *) { return false; } 323}; 324 325class OpaqueValueEvaluation { 326 EvalInfo &info; 327 OpaqueValueExpr *opaqueValue; 328 329public: 330 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue, 331 Expr *value) 332 : info(info), opaqueValue(opaqueValue) { 333 334 // If evaluation fails, fail immediately. 335 if (!Evaluate(info, value)) { 336 this->opaqueValue = 0; 337 return; 338 } 339 info.OpaqueValues[opaqueValue] = info.EvalResult.Val; 340 } 341 342 bool hasError() const { return opaqueValue == 0; } 343 344 ~OpaqueValueEvaluation() { 345 if (opaqueValue) info.OpaqueValues.erase(opaqueValue); 346 } 347}; 348 349} // end anonymous namespace 350 351//===----------------------------------------------------------------------===// 352// LValue Evaluation 353//===----------------------------------------------------------------------===// 354namespace { 355class LValueExprEvaluator 356 : public StmtVisitor<LValueExprEvaluator, bool> { 357 EvalInfo &Info; 358 LValue &Result; 359 360 bool Success(Expr *E) { 361 Result.Base = E; 362 Result.Offset = CharUnits::Zero(); 363 return true; 364 } 365public: 366 367 LValueExprEvaluator(EvalInfo &info, LValue &Result) : 368 Info(info), Result(Result) {} 369 370 bool VisitStmt(Stmt *S) { 371 return false; 372 } 373 374 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 375 bool VisitDeclRefExpr(DeclRefExpr *E); 376 bool VisitPredefinedExpr(PredefinedExpr *E) { return Success(E); } 377 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 378 bool VisitMemberExpr(MemberExpr *E); 379 bool VisitStringLiteral(StringLiteral *E) { return Success(E); } 380 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return Success(E); } 381 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E); 382 bool VisitUnaryDeref(UnaryOperator *E); 383 bool VisitUnaryExtension(const UnaryOperator *E) 384 { return Visit(E->getSubExpr()); } 385 bool VisitChooseExpr(const ChooseExpr *E) 386 { return Visit(E->getChosenSubExpr(Info.Ctx)); } 387 388 bool VisitCastExpr(CastExpr *E) { 389 switch (E->getCastKind()) { 390 default: 391 return false; 392 393 case CK_NoOp: 394 return Visit(E->getSubExpr()); 395 } 396 } 397 // FIXME: Missing: __real__, __imag__ 398}; 399} // end anonymous namespace 400 401static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) { 402 return LValueExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E)); 403} 404 405bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) { 406 if (isa<FunctionDecl>(E->getDecl())) { 407 return Success(E); 408 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) { 409 if (!VD->getType()->isReferenceType()) 410 return Success(E); 411 // Reference parameters can refer to anything even if they have an 412 // "initializer" in the form of a default argument. 413 if (isa<ParmVarDecl>(VD)) 414 return false; 415 // FIXME: Check whether VD might be overridden! 416 if (const Expr *Init = VD->getAnyInitializer()) 417 return Visit(const_cast<Expr *>(Init)); 418 } 419 420 return false; 421} 422 423bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 424 return Success(E); 425} 426 427bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) { 428 QualType Ty; 429 if (E->isArrow()) { 430 if (!EvaluatePointer(E->getBase(), Result, Info)) 431 return false; 432 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType(); 433 } else { 434 if (!Visit(E->getBase())) 435 return false; 436 Ty = E->getBase()->getType(); 437 } 438 439 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl(); 440 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 441 442 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 443 if (!FD) // FIXME: deal with other kinds of member expressions 444 return false; 445 446 if (FD->getType()->isReferenceType()) 447 return false; 448 449 // FIXME: This is linear time. 450 unsigned i = 0; 451 for (RecordDecl::field_iterator Field = RD->field_begin(), 452 FieldEnd = RD->field_end(); 453 Field != FieldEnd; (void)++Field, ++i) { 454 if (*Field == FD) 455 break; 456 } 457 458 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 459 return true; 460} 461 462bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 463 if (!EvaluatePointer(E->getBase(), Result, Info)) 464 return false; 465 466 APSInt Index; 467 if (!EvaluateInteger(E->getIdx(), Index, Info)) 468 return false; 469 470 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType()); 471 Result.Offset += Index.getSExtValue() * ElementSize; 472 return true; 473} 474 475bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) { 476 return EvaluatePointer(E->getSubExpr(), Result, Info); 477} 478 479//===----------------------------------------------------------------------===// 480// Pointer Evaluation 481//===----------------------------------------------------------------------===// 482 483namespace { 484class PointerExprEvaluator 485 : public StmtVisitor<PointerExprEvaluator, bool> { 486 EvalInfo &Info; 487 LValue &Result; 488 489 bool Success(Expr *E) { 490 Result.Base = E; 491 Result.Offset = CharUnits::Zero(); 492 return true; 493 } 494public: 495 496 PointerExprEvaluator(EvalInfo &info, LValue &Result) 497 : Info(info), Result(Result) {} 498 499 bool VisitStmt(Stmt *S) { 500 return false; 501 } 502 503 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 504 505 bool VisitBinaryOperator(const BinaryOperator *E); 506 bool VisitCastExpr(CastExpr* E); 507 bool VisitUnaryExtension(const UnaryOperator *E) 508 { return Visit(E->getSubExpr()); } 509 bool VisitUnaryAddrOf(const UnaryOperator *E); 510 bool VisitObjCStringLiteral(ObjCStringLiteral *E) 511 { return Success(E); } 512 bool VisitAddrLabelExpr(AddrLabelExpr *E) 513 { return Success(E); } 514 bool VisitCallExpr(CallExpr *E); 515 bool VisitBlockExpr(BlockExpr *E) { 516 if (!E->getBlockDecl()->hasCaptures()) 517 return Success(E); 518 return false; 519 } 520 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) 521 { return Success((Expr*)0); } 522 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E); 523 bool VisitConditionalOperator(ConditionalOperator *E); 524 bool VisitChooseExpr(ChooseExpr *E) 525 { return Visit(E->getChosenSubExpr(Info.Ctx)); } 526 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) 527 { return Success((Expr*)0); } 528 529 bool VisitOpaqueValueExpr(OpaqueValueExpr *E); 530 // FIXME: Missing: @protocol, @selector 531}; 532} // end anonymous namespace 533 534static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) { 535 assert(E->getType()->hasPointerRepresentation()); 536 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E)); 537} 538 539bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 540 if (E->getOpcode() != BO_Add && 541 E->getOpcode() != BO_Sub) 542 return false; 543 544 const Expr *PExp = E->getLHS(); 545 const Expr *IExp = E->getRHS(); 546 if (IExp->getType()->isPointerType()) 547 std::swap(PExp, IExp); 548 549 if (!EvaluatePointer(PExp, Result, Info)) 550 return false; 551 552 llvm::APSInt Offset; 553 if (!EvaluateInteger(IExp, Offset, Info)) 554 return false; 555 int64_t AdditionalOffset 556 = Offset.isSigned() ? Offset.getSExtValue() 557 : static_cast<int64_t>(Offset.getZExtValue()); 558 559 // Compute the new offset in the appropriate width. 560 561 QualType PointeeType = 562 PExp->getType()->getAs<PointerType>()->getPointeeType(); 563 CharUnits SizeOfPointee; 564 565 // Explicitly handle GNU void* and function pointer arithmetic extensions. 566 if (PointeeType->isVoidType() || PointeeType->isFunctionType()) 567 SizeOfPointee = CharUnits::One(); 568 else 569 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType); 570 571 if (E->getOpcode() == BO_Add) 572 Result.Offset += AdditionalOffset * SizeOfPointee; 573 else 574 Result.Offset -= AdditionalOffset * SizeOfPointee; 575 576 return true; 577} 578 579bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 580 return EvaluateLValue(E->getSubExpr(), Result, Info); 581} 582 583 584bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) { 585 Expr* SubExpr = E->getSubExpr(); 586 587 switch (E->getCastKind()) { 588 default: 589 break; 590 591 case CK_NoOp: 592 case CK_BitCast: 593 case CK_AnyPointerToObjCPointerCast: 594 case CK_AnyPointerToBlockPointerCast: 595 return Visit(SubExpr); 596 597 case CK_DerivedToBase: 598 case CK_UncheckedDerivedToBase: { 599 LValue BaseLV; 600 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info)) 601 return false; 602 603 // Now figure out the necessary offset to add to the baseLV to get from 604 // the derived class to the base class. 605 CharUnits Offset = CharUnits::Zero(); 606 607 QualType Ty = E->getSubExpr()->getType(); 608 const CXXRecordDecl *DerivedDecl = 609 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl(); 610 611 for (CastExpr::path_const_iterator PathI = E->path_begin(), 612 PathE = E->path_end(); PathI != PathE; ++PathI) { 613 const CXXBaseSpecifier *Base = *PathI; 614 615 // FIXME: If the base is virtual, we'd need to determine the type of the 616 // most derived class and we don't support that right now. 617 if (Base->isVirtual()) 618 return false; 619 620 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 621 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 622 623 Offset += Layout.getBaseClassOffset(BaseDecl); 624 DerivedDecl = BaseDecl; 625 } 626 627 Result.Base = BaseLV.getLValueBase(); 628 Result.Offset = BaseLV.getLValueOffset() + Offset; 629 return true; 630 } 631 632 case CK_NullToPointer: { 633 Result.Base = 0; 634 Result.Offset = CharUnits::Zero(); 635 return true; 636 } 637 638 case CK_IntegralToPointer: { 639 APValue Value; 640 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 641 break; 642 643 if (Value.isInt()) { 644 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType())); 645 Result.Base = 0; 646 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue()); 647 return true; 648 } else { 649 // Cast is of an lvalue, no need to change value. 650 Result.Base = Value.getLValueBase(); 651 Result.Offset = Value.getLValueOffset(); 652 return true; 653 } 654 } 655 case CK_ArrayToPointerDecay: 656 case CK_FunctionToPointerDecay: 657 return EvaluateLValue(SubExpr, Result, Info); 658 } 659 660 return false; 661} 662 663bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) { 664 if (E->isBuiltinCall(Info.Ctx) == 665 Builtin::BI__builtin___CFStringMakeConstantString || 666 E->isBuiltinCall(Info.Ctx) == 667 Builtin::BI__builtin___NSStringMakeConstantString) 668 return Success(E); 669 return false; 670} 671 672bool PointerExprEvaluator::VisitOpaqueValueExpr(OpaqueValueExpr *e) { 673 const APValue *value = Info.getOpaqueValue(e); 674 if (!value) 675 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false); 676 Result.setFrom(*value); 677 return true; 678} 679 680bool PointerExprEvaluator:: 681VisitBinaryConditionalOperator(BinaryConditionalOperator *e) { 682 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon()); 683 if (opaque.hasError()) return false; 684 685 bool cond; 686 if (!HandleConversionToBool(e->getCond(), cond, Info)) 687 return false; 688 689 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr()); 690} 691 692bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) { 693 bool BoolResult; 694 if (!HandleConversionToBool(E->getCond(), BoolResult, Info)) 695 return false; 696 697 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 698 return Visit(EvalExpr); 699} 700 701//===----------------------------------------------------------------------===// 702// Vector Evaluation 703//===----------------------------------------------------------------------===// 704 705namespace { 706 class VectorExprEvaluator 707 : public StmtVisitor<VectorExprEvaluator, APValue> { 708 EvalInfo &Info; 709 APValue GetZeroVector(QualType VecType); 710 public: 711 712 VectorExprEvaluator(EvalInfo &info) : Info(info) {} 713 714 APValue VisitStmt(Stmt *S) { 715 return APValue(); 716 } 717 718 APValue VisitParenExpr(ParenExpr *E) 719 { return Visit(E->getSubExpr()); } 720 APValue VisitUnaryExtension(const UnaryOperator *E) 721 { return Visit(E->getSubExpr()); } 722 APValue VisitUnaryPlus(const UnaryOperator *E) 723 { return Visit(E->getSubExpr()); } 724 APValue VisitUnaryReal(const UnaryOperator *E) 725 { return Visit(E->getSubExpr()); } 726 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) 727 { return GetZeroVector(E->getType()); } 728 APValue VisitCastExpr(const CastExpr* E); 729 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 730 APValue VisitInitListExpr(const InitListExpr *E); 731 APValue VisitConditionalOperator(const ConditionalOperator *E); 732 APValue VisitChooseExpr(const ChooseExpr *E) 733 { return Visit(E->getChosenSubExpr(Info.Ctx)); } 734 APValue VisitUnaryImag(const UnaryOperator *E); 735 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 736 // binary comparisons, binary and/or/xor, 737 // shufflevector, ExtVectorElementExpr 738 // (Note that these require implementing conversions 739 // between vector types.) 740 }; 741} // end anonymous namespace 742 743static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 744 if (!E->getType()->isVectorType()) 745 return false; 746 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E)); 747 return !Result.isUninit(); 748} 749 750APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) { 751 const VectorType *VTy = E->getType()->getAs<VectorType>(); 752 QualType EltTy = VTy->getElementType(); 753 unsigned NElts = VTy->getNumElements(); 754 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy); 755 756 const Expr* SE = E->getSubExpr(); 757 QualType SETy = SE->getType(); 758 759 switch (E->getCastKind()) { 760 case CK_VectorSplat: { 761 APValue Result = APValue(); 762 if (SETy->isIntegerType()) { 763 APSInt IntResult; 764 if (!EvaluateInteger(SE, IntResult, Info)) 765 return APValue(); 766 Result = APValue(IntResult); 767 } else if (SETy->isRealFloatingType()) { 768 APFloat F(0.0); 769 if (!EvaluateFloat(SE, F, Info)) 770 return APValue(); 771 Result = APValue(F); 772 } else { 773 return APValue(); 774 } 775 776 // Splat and create vector APValue. 777 llvm::SmallVector<APValue, 4> Elts(NElts, Result); 778 return APValue(&Elts[0], Elts.size()); 779 } 780 case CK_BitCast: { 781 if (SETy->isVectorType()) 782 return Visit(const_cast<Expr*>(SE)); 783 784 if (!SETy->isIntegerType()) 785 return APValue(); 786 787 APSInt Init; 788 if (!EvaluateInteger(SE, Init, Info)) 789 return APValue(); 790 791 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) && 792 "Vectors must be composed of ints or floats"); 793 794 llvm::SmallVector<APValue, 4> Elts; 795 for (unsigned i = 0; i != NElts; ++i) { 796 APSInt Tmp = Init.extOrTrunc(EltWidth); 797 798 if (EltTy->isIntegerType()) 799 Elts.push_back(APValue(Tmp)); 800 else 801 Elts.push_back(APValue(APFloat(Tmp))); 802 803 Init >>= EltWidth; 804 } 805 return APValue(&Elts[0], Elts.size()); 806 } 807 case CK_LValueToRValue: 808 case CK_NoOp: 809 return Visit(const_cast<Expr*>(SE)); 810 default: 811 return APValue(); 812 } 813} 814 815APValue 816VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 817 return this->Visit(const_cast<Expr*>(E->getInitializer())); 818} 819 820APValue 821VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 822 const VectorType *VT = E->getType()->getAs<VectorType>(); 823 unsigned NumInits = E->getNumInits(); 824 unsigned NumElements = VT->getNumElements(); 825 826 QualType EltTy = VT->getElementType(); 827 llvm::SmallVector<APValue, 4> Elements; 828 829 // If a vector is initialized with a single element, that value 830 // becomes every element of the vector, not just the first. 831 // This is the behavior described in the IBM AltiVec documentation. 832 if (NumInits == 1) { 833 APValue InitValue; 834 if (EltTy->isIntegerType()) { 835 llvm::APSInt sInt(32); 836 if (!EvaluateInteger(E->getInit(0), sInt, Info)) 837 return APValue(); 838 InitValue = APValue(sInt); 839 } else { 840 llvm::APFloat f(0.0); 841 if (!EvaluateFloat(E->getInit(0), f, Info)) 842 return APValue(); 843 InitValue = APValue(f); 844 } 845 for (unsigned i = 0; i < NumElements; i++) { 846 Elements.push_back(InitValue); 847 } 848 } else { 849 for (unsigned i = 0; i < NumElements; i++) { 850 if (EltTy->isIntegerType()) { 851 llvm::APSInt sInt(32); 852 if (i < NumInits) { 853 if (!EvaluateInteger(E->getInit(i), sInt, Info)) 854 return APValue(); 855 } else { 856 sInt = Info.Ctx.MakeIntValue(0, EltTy); 857 } 858 Elements.push_back(APValue(sInt)); 859 } else { 860 llvm::APFloat f(0.0); 861 if (i < NumInits) { 862 if (!EvaluateFloat(E->getInit(i), f, Info)) 863 return APValue(); 864 } else { 865 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 866 } 867 Elements.push_back(APValue(f)); 868 } 869 } 870 } 871 return APValue(&Elements[0], Elements.size()); 872} 873 874APValue 875VectorExprEvaluator::GetZeroVector(QualType T) { 876 const VectorType *VT = T->getAs<VectorType>(); 877 QualType EltTy = VT->getElementType(); 878 APValue ZeroElement; 879 if (EltTy->isIntegerType()) 880 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 881 else 882 ZeroElement = 883 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 884 885 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 886 return APValue(&Elements[0], Elements.size()); 887} 888 889APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) { 890 bool BoolResult; 891 if (!HandleConversionToBool(E->getCond(), BoolResult, Info)) 892 return APValue(); 893 894 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 895 896 APValue Result; 897 if (EvaluateVector(EvalExpr, Result, Info)) 898 return Result; 899 return APValue(); 900} 901 902APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 903 if (!E->getSubExpr()->isEvaluatable(Info.Ctx)) 904 Info.EvalResult.HasSideEffects = true; 905 return GetZeroVector(E->getType()); 906} 907 908//===----------------------------------------------------------------------===// 909// Integer Evaluation 910//===----------------------------------------------------------------------===// 911 912namespace { 913class IntExprEvaluator 914 : public StmtVisitor<IntExprEvaluator, bool> { 915 EvalInfo &Info; 916 APValue &Result; 917public: 918 IntExprEvaluator(EvalInfo &info, APValue &result) 919 : Info(info), Result(result) {} 920 921 bool Success(const llvm::APSInt &SI, const Expr *E) { 922 assert(E->getType()->isIntegralOrEnumerationType() && 923 "Invalid evaluation result."); 924 assert(SI.isSigned() == E->getType()->isSignedIntegerType() && 925 "Invalid evaluation result."); 926 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 927 "Invalid evaluation result."); 928 Result = APValue(SI); 929 return true; 930 } 931 932 bool Success(const llvm::APInt &I, const Expr *E) { 933 assert(E->getType()->isIntegralOrEnumerationType() && 934 "Invalid evaluation result."); 935 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 936 "Invalid evaluation result."); 937 Result = APValue(APSInt(I)); 938 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType()); 939 return true; 940 } 941 942 bool Success(uint64_t Value, const Expr *E) { 943 assert(E->getType()->isIntegralOrEnumerationType() && 944 "Invalid evaluation result."); 945 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 946 return true; 947 } 948 949 bool Success(CharUnits Size, const Expr *E) { 950 return Success(Size.getQuantity(), E); 951 } 952 953 954 bool Error(SourceLocation L, diag::kind D, const Expr *E) { 955 // Take the first error. 956 if (Info.EvalResult.Diag == 0) { 957 Info.EvalResult.DiagLoc = L; 958 Info.EvalResult.Diag = D; 959 Info.EvalResult.DiagExpr = E; 960 } 961 return false; 962 } 963 964 //===--------------------------------------------------------------------===// 965 // Visitor Methods 966 //===--------------------------------------------------------------------===// 967 968 bool VisitStmt(Stmt *) { 969 assert(0 && "This should be called on integers, stmts are not integers"); 970 return false; 971 } 972 973 bool VisitExpr(Expr *E) { 974 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 975 } 976 977 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 978 979 bool VisitIntegerLiteral(const IntegerLiteral *E) { 980 return Success(E->getValue(), E); 981 } 982 bool VisitCharacterLiteral(const CharacterLiteral *E) { 983 return Success(E->getValue(), E); 984 } 985 986 bool VisitOpaqueValueExpr(OpaqueValueExpr *e) { 987 const APValue *value = Info.getOpaqueValue(e); 988 if (!value) { 989 if (e->getSourceExpr()) return Visit(e->getSourceExpr()); 990 return Error(e->getExprLoc(), diag::note_invalid_subexpr_in_ice, e); 991 } 992 return Success(value->getInt(), e); 993 } 994 995 bool CheckReferencedDecl(const Expr *E, const Decl *D); 996 bool VisitDeclRefExpr(const DeclRefExpr *E) { 997 return CheckReferencedDecl(E, E->getDecl()); 998 } 999 bool VisitMemberExpr(const MemberExpr *E) { 1000 if (CheckReferencedDecl(E, E->getMemberDecl())) { 1001 // Conservatively assume a MemberExpr will have side-effects 1002 Info.EvalResult.HasSideEffects = true; 1003 return true; 1004 } 1005 return false; 1006 } 1007 1008 bool VisitCallExpr(CallExpr *E); 1009 bool VisitBinaryOperator(const BinaryOperator *E); 1010 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 1011 bool VisitUnaryOperator(const UnaryOperator *E); 1012 bool VisitConditionalOperator(const ConditionalOperator *E); 1013 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E); 1014 1015 bool VisitCastExpr(CastExpr* E); 1016 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 1017 1018 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 1019 return Success(E->getValue(), E); 1020 } 1021 1022 bool VisitGNUNullExpr(const GNUNullExpr *E) { 1023 return Success(0, E); 1024 } 1025 1026 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 1027 return Success(0, E); 1028 } 1029 1030 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 1031 return Success(0, E); 1032 } 1033 1034 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 1035 return Success(E->getValue(), E); 1036 } 1037 1038 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) { 1039 return Success(E->getValue(), E); 1040 } 1041 1042 bool VisitChooseExpr(const ChooseExpr *E) { 1043 return Visit(E->getChosenSubExpr(Info.Ctx)); 1044 } 1045 1046 bool VisitUnaryReal(const UnaryOperator *E); 1047 bool VisitUnaryImag(const UnaryOperator *E); 1048 1049 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 1050 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 1051 1052private: 1053 CharUnits GetAlignOfExpr(const Expr *E); 1054 CharUnits GetAlignOfType(QualType T); 1055 static QualType GetObjectType(const Expr *E); 1056 bool TryEvaluateBuiltinObjectSize(CallExpr *E); 1057 // FIXME: Missing: array subscript of vector, member of vector 1058}; 1059} // end anonymous namespace 1060 1061static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) { 1062 assert(E->getType()->isIntegralOrEnumerationType()); 1063 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E)); 1064} 1065 1066static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) { 1067 assert(E->getType()->isIntegralOrEnumerationType()); 1068 1069 APValue Val; 1070 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt()) 1071 return false; 1072 Result = Val.getInt(); 1073 return true; 1074} 1075 1076bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 1077 // Enums are integer constant exprs. 1078 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 1079 return Success(ECD->getInitVal(), E); 1080 1081 // In C++, const, non-volatile integers initialized with ICEs are ICEs. 1082 // In C, they can also be folded, although they are not ICEs. 1083 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers() 1084 == Qualifiers::Const) { 1085 1086 if (isa<ParmVarDecl>(D)) 1087 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 1088 1089 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1090 if (const Expr *Init = VD->getAnyInitializer()) { 1091 if (APValue *V = VD->getEvaluatedValue()) { 1092 if (V->isInt()) 1093 return Success(V->getInt(), E); 1094 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 1095 } 1096 1097 if (VD->isEvaluatingValue()) 1098 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 1099 1100 VD->setEvaluatingValue(); 1101 1102 Expr::EvalResult EResult; 1103 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects && 1104 EResult.Val.isInt()) { 1105 // Cache the evaluated value in the variable declaration. 1106 Result = EResult.Val; 1107 VD->setEvaluatedValue(Result); 1108 return true; 1109 } 1110 1111 VD->setEvaluatedValue(APValue()); 1112 } 1113 } 1114 } 1115 1116 // Otherwise, random variable references are not constants. 1117 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 1118} 1119 1120/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 1121/// as GCC. 1122static int EvaluateBuiltinClassifyType(const CallExpr *E) { 1123 // The following enum mimics the values returned by GCC. 1124 // FIXME: Does GCC differ between lvalue and rvalue references here? 1125 enum gcc_type_class { 1126 no_type_class = -1, 1127 void_type_class, integer_type_class, char_type_class, 1128 enumeral_type_class, boolean_type_class, 1129 pointer_type_class, reference_type_class, offset_type_class, 1130 real_type_class, complex_type_class, 1131 function_type_class, method_type_class, 1132 record_type_class, union_type_class, 1133 array_type_class, string_type_class, 1134 lang_type_class 1135 }; 1136 1137 // If no argument was supplied, default to "no_type_class". This isn't 1138 // ideal, however it is what gcc does. 1139 if (E->getNumArgs() == 0) 1140 return no_type_class; 1141 1142 QualType ArgTy = E->getArg(0)->getType(); 1143 if (ArgTy->isVoidType()) 1144 return void_type_class; 1145 else if (ArgTy->isEnumeralType()) 1146 return enumeral_type_class; 1147 else if (ArgTy->isBooleanType()) 1148 return boolean_type_class; 1149 else if (ArgTy->isCharType()) 1150 return string_type_class; // gcc doesn't appear to use char_type_class 1151 else if (ArgTy->isIntegerType()) 1152 return integer_type_class; 1153 else if (ArgTy->isPointerType()) 1154 return pointer_type_class; 1155 else if (ArgTy->isReferenceType()) 1156 return reference_type_class; 1157 else if (ArgTy->isRealType()) 1158 return real_type_class; 1159 else if (ArgTy->isComplexType()) 1160 return complex_type_class; 1161 else if (ArgTy->isFunctionType()) 1162 return function_type_class; 1163 else if (ArgTy->isStructureOrClassType()) 1164 return record_type_class; 1165 else if (ArgTy->isUnionType()) 1166 return union_type_class; 1167 else if (ArgTy->isArrayType()) 1168 return array_type_class; 1169 else if (ArgTy->isUnionType()) 1170 return union_type_class; 1171 else // FIXME: offset_type_class, method_type_class, & lang_type_class? 1172 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type"); 1173 return -1; 1174} 1175 1176/// Retrieves the "underlying object type" of the given expression, 1177/// as used by __builtin_object_size. 1178QualType IntExprEvaluator::GetObjectType(const Expr *E) { 1179 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 1180 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 1181 return VD->getType(); 1182 } else if (isa<CompoundLiteralExpr>(E)) { 1183 return E->getType(); 1184 } 1185 1186 return QualType(); 1187} 1188 1189bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) { 1190 // TODO: Perhaps we should let LLVM lower this? 1191 LValue Base; 1192 if (!EvaluatePointer(E->getArg(0), Base, Info)) 1193 return false; 1194 1195 // If we can prove the base is null, lower to zero now. 1196 const Expr *LVBase = Base.getLValueBase(); 1197 if (!LVBase) return Success(0, E); 1198 1199 QualType T = GetObjectType(LVBase); 1200 if (T.isNull() || 1201 T->isIncompleteType() || 1202 T->isFunctionType() || 1203 T->isVariablyModifiedType() || 1204 T->isDependentType()) 1205 return false; 1206 1207 CharUnits Size = Info.Ctx.getTypeSizeInChars(T); 1208 CharUnits Offset = Base.getLValueOffset(); 1209 1210 if (!Offset.isNegative() && Offset <= Size) 1211 Size -= Offset; 1212 else 1213 Size = CharUnits::Zero(); 1214 return Success(Size, E); 1215} 1216 1217bool IntExprEvaluator::VisitCallExpr(CallExpr *E) { 1218 switch (E->isBuiltinCall(Info.Ctx)) { 1219 default: 1220 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 1221 1222 case Builtin::BI__builtin_object_size: { 1223 if (TryEvaluateBuiltinObjectSize(E)) 1224 return true; 1225 1226 // If evaluating the argument has side-effects we can't determine 1227 // the size of the object and lower it to unknown now. 1228 if (E->getArg(0)->HasSideEffects(Info.Ctx)) { 1229 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1) 1230 return Success(-1ULL, E); 1231 return Success(0, E); 1232 } 1233 1234 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 1235 } 1236 1237 case Builtin::BI__builtin_classify_type: 1238 return Success(EvaluateBuiltinClassifyType(E), E); 1239 1240 case Builtin::BI__builtin_constant_p: 1241 // __builtin_constant_p always has one operand: it returns true if that 1242 // operand can be folded, false otherwise. 1243 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E); 1244 1245 case Builtin::BI__builtin_eh_return_data_regno: { 1246 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue(); 1247 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand); 1248 return Success(Operand, E); 1249 } 1250 1251 case Builtin::BI__builtin_expect: 1252 return Visit(E->getArg(0)); 1253 1254 case Builtin::BIstrlen: 1255 case Builtin::BI__builtin_strlen: 1256 // As an extension, we support strlen() and __builtin_strlen() as constant 1257 // expressions when the argument is a string literal. 1258 if (StringLiteral *S 1259 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) { 1260 // The string literal may have embedded null characters. Find the first 1261 // one and truncate there. 1262 llvm::StringRef Str = S->getString(); 1263 llvm::StringRef::size_type Pos = Str.find(0); 1264 if (Pos != llvm::StringRef::npos) 1265 Str = Str.substr(0, Pos); 1266 1267 return Success(Str.size(), E); 1268 } 1269 1270 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E); 1271 } 1272} 1273 1274bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 1275 if (E->getOpcode() == BO_Comma) { 1276 if (!Visit(E->getRHS())) 1277 return false; 1278 1279 // If we can't evaluate the LHS, it might have side effects; 1280 // conservatively mark it. 1281 if (!E->getLHS()->isEvaluatable(Info.Ctx)) 1282 Info.EvalResult.HasSideEffects = true; 1283 1284 return true; 1285 } 1286 1287 if (E->isLogicalOp()) { 1288 // These need to be handled specially because the operands aren't 1289 // necessarily integral 1290 bool lhsResult, rhsResult; 1291 1292 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) { 1293 // We were able to evaluate the LHS, see if we can get away with not 1294 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 1295 if (lhsResult == (E->getOpcode() == BO_LOr)) 1296 return Success(lhsResult, E); 1297 1298 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) { 1299 if (E->getOpcode() == BO_LOr) 1300 return Success(lhsResult || rhsResult, E); 1301 else 1302 return Success(lhsResult && rhsResult, E); 1303 } 1304 } else { 1305 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) { 1306 // We can't evaluate the LHS; however, sometimes the result 1307 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 1308 if (rhsResult == (E->getOpcode() == BO_LOr) || 1309 !rhsResult == (E->getOpcode() == BO_LAnd)) { 1310 // Since we weren't able to evaluate the left hand side, it 1311 // must have had side effects. 1312 Info.EvalResult.HasSideEffects = true; 1313 1314 return Success(rhsResult, E); 1315 } 1316 } 1317 } 1318 1319 return false; 1320 } 1321 1322 QualType LHSTy = E->getLHS()->getType(); 1323 QualType RHSTy = E->getRHS()->getType(); 1324 1325 if (LHSTy->isAnyComplexType()) { 1326 assert(RHSTy->isAnyComplexType() && "Invalid comparison"); 1327 ComplexValue LHS, RHS; 1328 1329 if (!EvaluateComplex(E->getLHS(), LHS, Info)) 1330 return false; 1331 1332 if (!EvaluateComplex(E->getRHS(), RHS, Info)) 1333 return false; 1334 1335 if (LHS.isComplexFloat()) { 1336 APFloat::cmpResult CR_r = 1337 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 1338 APFloat::cmpResult CR_i = 1339 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 1340 1341 if (E->getOpcode() == BO_EQ) 1342 return Success((CR_r == APFloat::cmpEqual && 1343 CR_i == APFloat::cmpEqual), E); 1344 else { 1345 assert(E->getOpcode() == BO_NE && 1346 "Invalid complex comparison."); 1347 return Success(((CR_r == APFloat::cmpGreaterThan || 1348 CR_r == APFloat::cmpLessThan || 1349 CR_r == APFloat::cmpUnordered) || 1350 (CR_i == APFloat::cmpGreaterThan || 1351 CR_i == APFloat::cmpLessThan || 1352 CR_i == APFloat::cmpUnordered)), E); 1353 } 1354 } else { 1355 if (E->getOpcode() == BO_EQ) 1356 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() && 1357 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E); 1358 else { 1359 assert(E->getOpcode() == BO_NE && 1360 "Invalid compex comparison."); 1361 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() || 1362 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E); 1363 } 1364 } 1365 } 1366 1367 if (LHSTy->isRealFloatingType() && 1368 RHSTy->isRealFloatingType()) { 1369 APFloat RHS(0.0), LHS(0.0); 1370 1371 if (!EvaluateFloat(E->getRHS(), RHS, Info)) 1372 return false; 1373 1374 if (!EvaluateFloat(E->getLHS(), LHS, Info)) 1375 return false; 1376 1377 APFloat::cmpResult CR = LHS.compare(RHS); 1378 1379 switch (E->getOpcode()) { 1380 default: 1381 assert(0 && "Invalid binary operator!"); 1382 case BO_LT: 1383 return Success(CR == APFloat::cmpLessThan, E); 1384 case BO_GT: 1385 return Success(CR == APFloat::cmpGreaterThan, E); 1386 case BO_LE: 1387 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E); 1388 case BO_GE: 1389 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual, 1390 E); 1391 case BO_EQ: 1392 return Success(CR == APFloat::cmpEqual, E); 1393 case BO_NE: 1394 return Success(CR == APFloat::cmpGreaterThan 1395 || CR == APFloat::cmpLessThan 1396 || CR == APFloat::cmpUnordered, E); 1397 } 1398 } 1399 1400 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 1401 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) { 1402 LValue LHSValue; 1403 if (!EvaluatePointer(E->getLHS(), LHSValue, Info)) 1404 return false; 1405 1406 LValue RHSValue; 1407 if (!EvaluatePointer(E->getRHS(), RHSValue, Info)) 1408 return false; 1409 1410 // Reject any bases from the normal codepath; we special-case comparisons 1411 // to null. 1412 if (LHSValue.getLValueBase()) { 1413 if (!E->isEqualityOp()) 1414 return false; 1415 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero()) 1416 return false; 1417 bool bres; 1418 if (!EvalPointerValueAsBool(LHSValue, bres)) 1419 return false; 1420 return Success(bres ^ (E->getOpcode() == BO_EQ), E); 1421 } else if (RHSValue.getLValueBase()) { 1422 if (!E->isEqualityOp()) 1423 return false; 1424 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero()) 1425 return false; 1426 bool bres; 1427 if (!EvalPointerValueAsBool(RHSValue, bres)) 1428 return false; 1429 return Success(bres ^ (E->getOpcode() == BO_EQ), E); 1430 } 1431 1432 if (E->getOpcode() == BO_Sub) { 1433 QualType Type = E->getLHS()->getType(); 1434 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 1435 1436 CharUnits ElementSize = CharUnits::One(); 1437 if (!ElementType->isVoidType() && !ElementType->isFunctionType()) 1438 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType); 1439 1440 CharUnits Diff = LHSValue.getLValueOffset() - 1441 RHSValue.getLValueOffset(); 1442 return Success(Diff / ElementSize, E); 1443 } 1444 bool Result; 1445 if (E->getOpcode() == BO_EQ) { 1446 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset(); 1447 } else { 1448 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset(); 1449 } 1450 return Success(Result, E); 1451 } 1452 } 1453 if (!LHSTy->isIntegralOrEnumerationType() || 1454 !RHSTy->isIntegralOrEnumerationType()) { 1455 // We can't continue from here for non-integral types, and they 1456 // could potentially confuse the following operations. 1457 return false; 1458 } 1459 1460 // The LHS of a constant expr is always evaluated and needed. 1461 if (!Visit(E->getLHS())) 1462 return false; // error in subexpression. 1463 1464 APValue RHSVal; 1465 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info)) 1466 return false; 1467 1468 // Handle cases like (unsigned long)&a + 4. 1469 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) { 1470 CharUnits Offset = Result.getLValueOffset(); 1471 CharUnits AdditionalOffset = CharUnits::fromQuantity( 1472 RHSVal.getInt().getZExtValue()); 1473 if (E->getOpcode() == BO_Add) 1474 Offset += AdditionalOffset; 1475 else 1476 Offset -= AdditionalOffset; 1477 Result = APValue(Result.getLValueBase(), Offset); 1478 return true; 1479 } 1480 1481 // Handle cases like 4 + (unsigned long)&a 1482 if (E->getOpcode() == BO_Add && 1483 RHSVal.isLValue() && Result.isInt()) { 1484 CharUnits Offset = RHSVal.getLValueOffset(); 1485 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue()); 1486 Result = APValue(RHSVal.getLValueBase(), Offset); 1487 return true; 1488 } 1489 1490 // All the following cases expect both operands to be an integer 1491 if (!Result.isInt() || !RHSVal.isInt()) 1492 return false; 1493 1494 APSInt& RHS = RHSVal.getInt(); 1495 1496 switch (E->getOpcode()) { 1497 default: 1498 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E); 1499 case BO_Mul: return Success(Result.getInt() * RHS, E); 1500 case BO_Add: return Success(Result.getInt() + RHS, E); 1501 case BO_Sub: return Success(Result.getInt() - RHS, E); 1502 case BO_And: return Success(Result.getInt() & RHS, E); 1503 case BO_Xor: return Success(Result.getInt() ^ RHS, E); 1504 case BO_Or: return Success(Result.getInt() | RHS, E); 1505 case BO_Div: 1506 if (RHS == 0) 1507 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E); 1508 return Success(Result.getInt() / RHS, E); 1509 case BO_Rem: 1510 if (RHS == 0) 1511 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E); 1512 return Success(Result.getInt() % RHS, E); 1513 case BO_Shl: { 1514 // During constant-folding, a negative shift is an opposite shift. 1515 if (RHS.isSigned() && RHS.isNegative()) { 1516 RHS = -RHS; 1517 goto shift_right; 1518 } 1519 1520 shift_left: 1521 unsigned SA 1522 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1); 1523 return Success(Result.getInt() << SA, E); 1524 } 1525 case BO_Shr: { 1526 // During constant-folding, a negative shift is an opposite shift. 1527 if (RHS.isSigned() && RHS.isNegative()) { 1528 RHS = -RHS; 1529 goto shift_left; 1530 } 1531 1532 shift_right: 1533 unsigned SA = 1534 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1); 1535 return Success(Result.getInt() >> SA, E); 1536 } 1537 1538 case BO_LT: return Success(Result.getInt() < RHS, E); 1539 case BO_GT: return Success(Result.getInt() > RHS, E); 1540 case BO_LE: return Success(Result.getInt() <= RHS, E); 1541 case BO_GE: return Success(Result.getInt() >= RHS, E); 1542 case BO_EQ: return Success(Result.getInt() == RHS, E); 1543 case BO_NE: return Success(Result.getInt() != RHS, E); 1544 } 1545} 1546 1547bool IntExprEvaluator:: 1548VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) { 1549 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon()); 1550 if (opaque.hasError()) return false; 1551 1552 bool cond; 1553 if (!HandleConversionToBool(e->getCond(), cond, Info)) 1554 return false; 1555 1556 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr()); 1557} 1558 1559bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) { 1560 bool Cond; 1561 if (!HandleConversionToBool(E->getCond(), Cond, Info)) 1562 return false; 1563 1564 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr()); 1565} 1566 1567CharUnits IntExprEvaluator::GetAlignOfType(QualType T) { 1568 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 1569 // the result is the size of the referenced type." 1570 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 1571 // result shall be the alignment of the referenced type." 1572 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 1573 T = Ref->getPointeeType(); 1574 1575 // __alignof is defined to return the preferred alignment. 1576 return Info.Ctx.toCharUnitsFromBits( 1577 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 1578} 1579 1580CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) { 1581 E = E->IgnoreParens(); 1582 1583 // alignof decl is always accepted, even if it doesn't make sense: we default 1584 // to 1 in those cases. 1585 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 1586 return Info.Ctx.getDeclAlign(DRE->getDecl(), 1587 /*RefAsPointee*/true); 1588 1589 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 1590 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 1591 /*RefAsPointee*/true); 1592 1593 return GetAlignOfType(E->getType()); 1594} 1595 1596 1597/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 1598/// a result as the expression's type. 1599bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 1600 const UnaryExprOrTypeTraitExpr *E) { 1601 switch(E->getKind()) { 1602 case UETT_AlignOf: { 1603 if (E->isArgumentType()) 1604 return Success(GetAlignOfType(E->getArgumentType()), E); 1605 else 1606 return Success(GetAlignOfExpr(E->getArgumentExpr()), E); 1607 } 1608 1609 case UETT_VecStep: { 1610 QualType Ty = E->getTypeOfArgument(); 1611 1612 if (Ty->isVectorType()) { 1613 unsigned n = Ty->getAs<VectorType>()->getNumElements(); 1614 1615 // The vec_step built-in functions that take a 3-component 1616 // vector return 4. (OpenCL 1.1 spec 6.11.12) 1617 if (n == 3) 1618 n = 4; 1619 1620 return Success(n, E); 1621 } else 1622 return Success(1, E); 1623 } 1624 1625 case UETT_SizeOf: { 1626 QualType SrcTy = E->getTypeOfArgument(); 1627 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 1628 // the result is the size of the referenced type." 1629 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 1630 // result shall be the alignment of the referenced type." 1631 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 1632 SrcTy = Ref->getPointeeType(); 1633 1634 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 1635 // extension. 1636 if (SrcTy->isVoidType() || SrcTy->isFunctionType()) 1637 return Success(1, E); 1638 1639 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 1640 if (!SrcTy->isConstantSizeType()) 1641 return false; 1642 1643 // Get information about the size. 1644 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E); 1645 } 1646 } 1647 1648 llvm_unreachable("unknown expr/type trait"); 1649 return false; 1650} 1651 1652bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) { 1653 CharUnits Result; 1654 unsigned n = E->getNumComponents(); 1655 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E); 1656 if (n == 0) 1657 return false; 1658 QualType CurrentType = E->getTypeSourceInfo()->getType(); 1659 for (unsigned i = 0; i != n; ++i) { 1660 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i); 1661 switch (ON.getKind()) { 1662 case OffsetOfExpr::OffsetOfNode::Array: { 1663 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 1664 APSInt IdxResult; 1665 if (!EvaluateInteger(Idx, IdxResult, Info)) 1666 return false; 1667 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 1668 if (!AT) 1669 return false; 1670 CurrentType = AT->getElementType(); 1671 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 1672 Result += IdxResult.getSExtValue() * ElementSize; 1673 break; 1674 } 1675 1676 case OffsetOfExpr::OffsetOfNode::Field: { 1677 FieldDecl *MemberDecl = ON.getField(); 1678 const RecordType *RT = CurrentType->getAs<RecordType>(); 1679 if (!RT) 1680 return false; 1681 RecordDecl *RD = RT->getDecl(); 1682 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 1683 unsigned i = MemberDecl->getFieldIndex(); 1684 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 1685 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 1686 CurrentType = MemberDecl->getType().getNonReferenceType(); 1687 break; 1688 } 1689 1690 case OffsetOfExpr::OffsetOfNode::Identifier: 1691 llvm_unreachable("dependent __builtin_offsetof"); 1692 return false; 1693 1694 case OffsetOfExpr::OffsetOfNode::Base: { 1695 CXXBaseSpecifier *BaseSpec = ON.getBase(); 1696 if (BaseSpec->isVirtual()) 1697 return false; 1698 1699 // Find the layout of the class whose base we are looking into. 1700 const RecordType *RT = CurrentType->getAs<RecordType>(); 1701 if (!RT) 1702 return false; 1703 RecordDecl *RD = RT->getDecl(); 1704 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 1705 1706 // Find the base class itself. 1707 CurrentType = BaseSpec->getType(); 1708 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 1709 if (!BaseRT) 1710 return false; 1711 1712 // Add the offset to the base. 1713 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 1714 break; 1715 } 1716 } 1717 } 1718 return Success(Result, E); 1719} 1720 1721bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 1722 if (E->getOpcode() == UO_LNot) { 1723 // LNot's operand isn't necessarily an integer, so we handle it specially. 1724 bool bres; 1725 if (!HandleConversionToBool(E->getSubExpr(), bres, Info)) 1726 return false; 1727 return Success(!bres, E); 1728 } 1729 1730 // Only handle integral operations... 1731 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType()) 1732 return false; 1733 1734 // Get the operand value into 'Result'. 1735 if (!Visit(E->getSubExpr())) 1736 return false; 1737 1738 switch (E->getOpcode()) { 1739 default: 1740 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 1741 // See C99 6.6p3. 1742 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E); 1743 case UO_Extension: 1744 // FIXME: Should extension allow i-c-e extension expressions in its scope? 1745 // If so, we could clear the diagnostic ID. 1746 return true; 1747 case UO_Plus: 1748 // The result is always just the subexpr. 1749 return true; 1750 case UO_Minus: 1751 if (!Result.isInt()) return false; 1752 return Success(-Result.getInt(), E); 1753 case UO_Not: 1754 if (!Result.isInt()) return false; 1755 return Success(~Result.getInt(), E); 1756 } 1757} 1758 1759/// HandleCast - This is used to evaluate implicit or explicit casts where the 1760/// result type is integer. 1761bool IntExprEvaluator::VisitCastExpr(CastExpr *E) { 1762 Expr *SubExpr = E->getSubExpr(); 1763 QualType DestType = E->getType(); 1764 QualType SrcType = SubExpr->getType(); 1765 1766 switch (E->getCastKind()) { 1767 case CK_BaseToDerived: 1768 case CK_DerivedToBase: 1769 case CK_UncheckedDerivedToBase: 1770 case CK_Dynamic: 1771 case CK_DynamicToNull: 1772 case CK_ToUnion: 1773 case CK_ArrayToPointerDecay: 1774 case CK_FunctionToPointerDecay: 1775 case CK_NullToPointer: 1776 case CK_NullToMemberPointer: 1777 case CK_BaseToDerivedMemberPointer: 1778 case CK_DerivedToBaseMemberPointer: 1779 case CK_ConstructorConversion: 1780 case CK_IntegralToPointer: 1781 case CK_ToVoid: 1782 case CK_VectorSplat: 1783 case CK_IntegralToFloating: 1784 case CK_FloatingCast: 1785 case CK_AnyPointerToObjCPointerCast: 1786 case CK_AnyPointerToBlockPointerCast: 1787 case CK_ObjCObjectLValueCast: 1788 case CK_FloatingRealToComplex: 1789 case CK_FloatingComplexToReal: 1790 case CK_FloatingComplexCast: 1791 case CK_FloatingComplexToIntegralComplex: 1792 case CK_IntegralRealToComplex: 1793 case CK_IntegralComplexCast: 1794 case CK_IntegralComplexToFloatingComplex: 1795 llvm_unreachable("invalid cast kind for integral value"); 1796 1797 case CK_BitCast: 1798 case CK_Dependent: 1799 case CK_GetObjCProperty: 1800 case CK_LValueBitCast: 1801 case CK_UserDefinedConversion: 1802 case CK_ResolveUnknownAnyType: 1803 return false; 1804 1805 case CK_LValueToRValue: 1806 case CK_NoOp: 1807 return Visit(E->getSubExpr()); 1808 1809 case CK_MemberPointerToBoolean: 1810 case CK_PointerToBoolean: 1811 case CK_IntegralToBoolean: 1812 case CK_FloatingToBoolean: 1813 case CK_FloatingComplexToBoolean: 1814 case CK_IntegralComplexToBoolean: { 1815 bool BoolResult; 1816 if (!HandleConversionToBool(SubExpr, BoolResult, Info)) 1817 return false; 1818 return Success(BoolResult, E); 1819 } 1820 1821 case CK_IntegralCast: { 1822 if (!Visit(SubExpr)) 1823 return false; 1824 1825 if (!Result.isInt()) { 1826 // Only allow casts of lvalues if they are lossless. 1827 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 1828 } 1829 1830 return Success(HandleIntToIntCast(DestType, SrcType, 1831 Result.getInt(), Info.Ctx), E); 1832 } 1833 1834 case CK_PointerToIntegral: { 1835 LValue LV; 1836 if (!EvaluatePointer(SubExpr, LV, Info)) 1837 return false; 1838 1839 if (LV.getLValueBase()) { 1840 // Only allow based lvalue casts if they are lossless. 1841 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 1842 return false; 1843 1844 LV.moveInto(Result); 1845 return true; 1846 } 1847 1848 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(), 1849 SrcType); 1850 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E); 1851 } 1852 1853 case CK_IntegralComplexToReal: { 1854 ComplexValue C; 1855 if (!EvaluateComplex(SubExpr, C, Info)) 1856 return false; 1857 return Success(C.getComplexIntReal(), E); 1858 } 1859 1860 case CK_FloatingToIntegral: { 1861 APFloat F(0.0); 1862 if (!EvaluateFloat(SubExpr, F, Info)) 1863 return false; 1864 1865 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E); 1866 } 1867 } 1868 1869 llvm_unreachable("unknown cast resulting in integral value"); 1870 return false; 1871} 1872 1873bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 1874 if (E->getSubExpr()->getType()->isAnyComplexType()) { 1875 ComplexValue LV; 1876 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt()) 1877 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E); 1878 return Success(LV.getComplexIntReal(), E); 1879 } 1880 1881 return Visit(E->getSubExpr()); 1882} 1883 1884bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 1885 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 1886 ComplexValue LV; 1887 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt()) 1888 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E); 1889 return Success(LV.getComplexIntImag(), E); 1890 } 1891 1892 if (!E->getSubExpr()->isEvaluatable(Info.Ctx)) 1893 Info.EvalResult.HasSideEffects = true; 1894 return Success(0, E); 1895} 1896 1897bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 1898 return Success(E->getPackLength(), E); 1899} 1900 1901bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 1902 return Success(E->getValue(), E); 1903} 1904 1905//===----------------------------------------------------------------------===// 1906// Float Evaluation 1907//===----------------------------------------------------------------------===// 1908 1909namespace { 1910class FloatExprEvaluator 1911 : public StmtVisitor<FloatExprEvaluator, bool> { 1912 EvalInfo &Info; 1913 APFloat &Result; 1914public: 1915 FloatExprEvaluator(EvalInfo &info, APFloat &result) 1916 : Info(info), Result(result) {} 1917 1918 bool VisitStmt(Stmt *S) { 1919 return false; 1920 } 1921 1922 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 1923 bool VisitCallExpr(const CallExpr *E); 1924 1925 bool VisitUnaryOperator(const UnaryOperator *E); 1926 bool VisitBinaryOperator(const BinaryOperator *E); 1927 bool VisitFloatingLiteral(const FloatingLiteral *E); 1928 bool VisitCastExpr(CastExpr *E); 1929 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 1930 bool VisitConditionalOperator(ConditionalOperator *E); 1931 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E); 1932 1933 bool VisitChooseExpr(const ChooseExpr *E) 1934 { return Visit(E->getChosenSubExpr(Info.Ctx)); } 1935 bool VisitUnaryExtension(const UnaryOperator *E) 1936 { return Visit(E->getSubExpr()); } 1937 bool VisitUnaryReal(const UnaryOperator *E); 1938 bool VisitUnaryImag(const UnaryOperator *E); 1939 1940 bool VisitDeclRefExpr(const DeclRefExpr *E); 1941 1942 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) { 1943 const APValue *value = Info.getOpaqueValue(e); 1944 if (!value) 1945 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false); 1946 Result = value->getFloat(); 1947 return true; 1948 } 1949 1950 // FIXME: Missing: array subscript of vector, member of vector, 1951 // ImplicitValueInitExpr 1952}; 1953} // end anonymous namespace 1954 1955static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 1956 assert(E->getType()->isRealFloatingType()); 1957 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E)); 1958} 1959 1960static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 1961 QualType ResultTy, 1962 const Expr *Arg, 1963 bool SNaN, 1964 llvm::APFloat &Result) { 1965 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 1966 if (!S) return false; 1967 1968 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 1969 1970 llvm::APInt fill; 1971 1972 // Treat empty strings as if they were zero. 1973 if (S->getString().empty()) 1974 fill = llvm::APInt(32, 0); 1975 else if (S->getString().getAsInteger(0, fill)) 1976 return false; 1977 1978 if (SNaN) 1979 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 1980 else 1981 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 1982 return true; 1983} 1984 1985bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 1986 switch (E->isBuiltinCall(Info.Ctx)) { 1987 default: return false; 1988 case Builtin::BI__builtin_huge_val: 1989 case Builtin::BI__builtin_huge_valf: 1990 case Builtin::BI__builtin_huge_vall: 1991 case Builtin::BI__builtin_inf: 1992 case Builtin::BI__builtin_inff: 1993 case Builtin::BI__builtin_infl: { 1994 const llvm::fltSemantics &Sem = 1995 Info.Ctx.getFloatTypeSemantics(E->getType()); 1996 Result = llvm::APFloat::getInf(Sem); 1997 return true; 1998 } 1999 2000 case Builtin::BI__builtin_nans: 2001 case Builtin::BI__builtin_nansf: 2002 case Builtin::BI__builtin_nansl: 2003 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 2004 true, Result); 2005 2006 case Builtin::BI__builtin_nan: 2007 case Builtin::BI__builtin_nanf: 2008 case Builtin::BI__builtin_nanl: 2009 // If this is __builtin_nan() turn this into a nan, otherwise we 2010 // can't constant fold it. 2011 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 2012 false, Result); 2013 2014 case Builtin::BI__builtin_fabs: 2015 case Builtin::BI__builtin_fabsf: 2016 case Builtin::BI__builtin_fabsl: 2017 if (!EvaluateFloat(E->getArg(0), Result, Info)) 2018 return false; 2019 2020 if (Result.isNegative()) 2021 Result.changeSign(); 2022 return true; 2023 2024 case Builtin::BI__builtin_copysign: 2025 case Builtin::BI__builtin_copysignf: 2026 case Builtin::BI__builtin_copysignl: { 2027 APFloat RHS(0.); 2028 if (!EvaluateFloat(E->getArg(0), Result, Info) || 2029 !EvaluateFloat(E->getArg(1), RHS, Info)) 2030 return false; 2031 Result.copySign(RHS); 2032 return true; 2033 } 2034 } 2035} 2036 2037bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 2038 const Decl *D = E->getDecl(); 2039 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false; 2040 const VarDecl *VD = cast<VarDecl>(D); 2041 2042 // Require the qualifiers to be const and not volatile. 2043 CanQualType T = Info.Ctx.getCanonicalType(E->getType()); 2044 if (!T.isConstQualified() || T.isVolatileQualified()) 2045 return false; 2046 2047 const Expr *Init = VD->getAnyInitializer(); 2048 if (!Init) return false; 2049 2050 if (APValue *V = VD->getEvaluatedValue()) { 2051 if (V->isFloat()) { 2052 Result = V->getFloat(); 2053 return true; 2054 } 2055 return false; 2056 } 2057 2058 if (VD->isEvaluatingValue()) 2059 return false; 2060 2061 VD->setEvaluatingValue(); 2062 2063 Expr::EvalResult InitResult; 2064 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects && 2065 InitResult.Val.isFloat()) { 2066 // Cache the evaluated value in the variable declaration. 2067 Result = InitResult.Val.getFloat(); 2068 VD->setEvaluatedValue(InitResult.Val); 2069 return true; 2070 } 2071 2072 VD->setEvaluatedValue(APValue()); 2073 return false; 2074} 2075 2076bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 2077 if (E->getSubExpr()->getType()->isAnyComplexType()) { 2078 ComplexValue CV; 2079 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 2080 return false; 2081 Result = CV.FloatReal; 2082 return true; 2083 } 2084 2085 return Visit(E->getSubExpr()); 2086} 2087 2088bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 2089 if (E->getSubExpr()->getType()->isAnyComplexType()) { 2090 ComplexValue CV; 2091 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 2092 return false; 2093 Result = CV.FloatImag; 2094 return true; 2095 } 2096 2097 if (!E->getSubExpr()->isEvaluatable(Info.Ctx)) 2098 Info.EvalResult.HasSideEffects = true; 2099 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 2100 Result = llvm::APFloat::getZero(Sem); 2101 return true; 2102} 2103 2104bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 2105 if (E->getOpcode() == UO_Deref) 2106 return false; 2107 2108 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 2109 return false; 2110 2111 switch (E->getOpcode()) { 2112 default: return false; 2113 case UO_Plus: 2114 return true; 2115 case UO_Minus: 2116 Result.changeSign(); 2117 return true; 2118 } 2119} 2120 2121bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 2122 if (E->getOpcode() == BO_Comma) { 2123 if (!EvaluateFloat(E->getRHS(), Result, Info)) 2124 return false; 2125 2126 // If we can't evaluate the LHS, it might have side effects; 2127 // conservatively mark it. 2128 if (!E->getLHS()->isEvaluatable(Info.Ctx)) 2129 Info.EvalResult.HasSideEffects = true; 2130 2131 return true; 2132 } 2133 2134 // We can't evaluate pointer-to-member operations. 2135 if (E->isPtrMemOp()) 2136 return false; 2137 2138 // FIXME: Diagnostics? I really don't understand how the warnings 2139 // and errors are supposed to work. 2140 APFloat RHS(0.0); 2141 if (!EvaluateFloat(E->getLHS(), Result, Info)) 2142 return false; 2143 if (!EvaluateFloat(E->getRHS(), RHS, Info)) 2144 return false; 2145 2146 switch (E->getOpcode()) { 2147 default: return false; 2148 case BO_Mul: 2149 Result.multiply(RHS, APFloat::rmNearestTiesToEven); 2150 return true; 2151 case BO_Add: 2152 Result.add(RHS, APFloat::rmNearestTiesToEven); 2153 return true; 2154 case BO_Sub: 2155 Result.subtract(RHS, APFloat::rmNearestTiesToEven); 2156 return true; 2157 case BO_Div: 2158 Result.divide(RHS, APFloat::rmNearestTiesToEven); 2159 return true; 2160 } 2161} 2162 2163bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 2164 Result = E->getValue(); 2165 return true; 2166} 2167 2168bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) { 2169 Expr* SubExpr = E->getSubExpr(); 2170 2171 switch (E->getCastKind()) { 2172 default: 2173 return false; 2174 2175 case CK_LValueToRValue: 2176 case CK_NoOp: 2177 return Visit(SubExpr); 2178 2179 case CK_IntegralToFloating: { 2180 APSInt IntResult; 2181 if (!EvaluateInteger(SubExpr, IntResult, Info)) 2182 return false; 2183 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(), 2184 IntResult, Info.Ctx); 2185 return true; 2186 } 2187 2188 case CK_FloatingCast: { 2189 if (!Visit(SubExpr)) 2190 return false; 2191 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(), 2192 Result, Info.Ctx); 2193 return true; 2194 } 2195 2196 case CK_FloatingComplexToReal: { 2197 ComplexValue V; 2198 if (!EvaluateComplex(SubExpr, V, Info)) 2199 return false; 2200 Result = V.getComplexFloatReal(); 2201 return true; 2202 } 2203 } 2204 2205 return false; 2206} 2207 2208bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 2209 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 2210 return true; 2211} 2212 2213bool FloatExprEvaluator:: 2214VisitBinaryConditionalOperator(BinaryConditionalOperator *e) { 2215 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon()); 2216 if (opaque.hasError()) return false; 2217 2218 bool cond; 2219 if (!HandleConversionToBool(e->getCond(), cond, Info)) 2220 return false; 2221 2222 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr()); 2223} 2224 2225bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) { 2226 bool Cond; 2227 if (!HandleConversionToBool(E->getCond(), Cond, Info)) 2228 return false; 2229 2230 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr()); 2231} 2232 2233//===----------------------------------------------------------------------===// 2234// Complex Evaluation (for float and integer) 2235//===----------------------------------------------------------------------===// 2236 2237namespace { 2238class ComplexExprEvaluator 2239 : public StmtVisitor<ComplexExprEvaluator, bool> { 2240 EvalInfo &Info; 2241 ComplexValue &Result; 2242 2243public: 2244 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 2245 : Info(info), Result(Result) {} 2246 2247 //===--------------------------------------------------------------------===// 2248 // Visitor Methods 2249 //===--------------------------------------------------------------------===// 2250 2251 bool VisitStmt(Stmt *S) { 2252 return false; 2253 } 2254 2255 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); } 2256 2257 bool VisitImaginaryLiteral(ImaginaryLiteral *E); 2258 2259 bool VisitCastExpr(CastExpr *E); 2260 2261 bool VisitBinaryOperator(const BinaryOperator *E); 2262 bool VisitUnaryOperator(const UnaryOperator *E); 2263 bool VisitConditionalOperator(const ConditionalOperator *E); 2264 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E); 2265 bool VisitChooseExpr(const ChooseExpr *E) 2266 { return Visit(E->getChosenSubExpr(Info.Ctx)); } 2267 bool VisitUnaryExtension(const UnaryOperator *E) 2268 { return Visit(E->getSubExpr()); } 2269 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) { 2270 const APValue *value = Info.getOpaqueValue(e); 2271 if (!value) 2272 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false); 2273 Result.setFrom(*value); 2274 return true; 2275 } 2276 // FIXME Missing: ImplicitValueInitExpr 2277}; 2278} // end anonymous namespace 2279 2280static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 2281 EvalInfo &Info) { 2282 assert(E->getType()->isAnyComplexType()); 2283 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E)); 2284} 2285 2286bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) { 2287 Expr* SubExpr = E->getSubExpr(); 2288 2289 if (SubExpr->getType()->isRealFloatingType()) { 2290 Result.makeComplexFloat(); 2291 APFloat &Imag = Result.FloatImag; 2292 if (!EvaluateFloat(SubExpr, Imag, Info)) 2293 return false; 2294 2295 Result.FloatReal = APFloat(Imag.getSemantics()); 2296 return true; 2297 } else { 2298 assert(SubExpr->getType()->isIntegerType() && 2299 "Unexpected imaginary literal."); 2300 2301 Result.makeComplexInt(); 2302 APSInt &Imag = Result.IntImag; 2303 if (!EvaluateInteger(SubExpr, Imag, Info)) 2304 return false; 2305 2306 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 2307 return true; 2308 } 2309} 2310 2311bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) { 2312 2313 switch (E->getCastKind()) { 2314 case CK_BitCast: 2315 case CK_BaseToDerived: 2316 case CK_DerivedToBase: 2317 case CK_UncheckedDerivedToBase: 2318 case CK_Dynamic: 2319 case CK_DynamicToNull: 2320 case CK_ToUnion: 2321 case CK_ArrayToPointerDecay: 2322 case CK_FunctionToPointerDecay: 2323 case CK_NullToPointer: 2324 case CK_NullToMemberPointer: 2325 case CK_BaseToDerivedMemberPointer: 2326 case CK_DerivedToBaseMemberPointer: 2327 case CK_MemberPointerToBoolean: 2328 case CK_ConstructorConversion: 2329 case CK_IntegralToPointer: 2330 case CK_PointerToIntegral: 2331 case CK_PointerToBoolean: 2332 case CK_ToVoid: 2333 case CK_VectorSplat: 2334 case CK_IntegralCast: 2335 case CK_IntegralToBoolean: 2336 case CK_IntegralToFloating: 2337 case CK_FloatingToIntegral: 2338 case CK_FloatingToBoolean: 2339 case CK_FloatingCast: 2340 case CK_AnyPointerToObjCPointerCast: 2341 case CK_AnyPointerToBlockPointerCast: 2342 case CK_ObjCObjectLValueCast: 2343 case CK_FloatingComplexToReal: 2344 case CK_FloatingComplexToBoolean: 2345 case CK_IntegralComplexToReal: 2346 case CK_IntegralComplexToBoolean: 2347 llvm_unreachable("invalid cast kind for complex value"); 2348 2349 case CK_LValueToRValue: 2350 case CK_NoOp: 2351 return Visit(E->getSubExpr()); 2352 2353 case CK_Dependent: 2354 case CK_GetObjCProperty: 2355 case CK_LValueBitCast: 2356 case CK_UserDefinedConversion: 2357 case CK_ResolveUnknownAnyType: 2358 return false; 2359 2360 case CK_FloatingRealToComplex: { 2361 APFloat &Real = Result.FloatReal; 2362 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 2363 return false; 2364 2365 Result.makeComplexFloat(); 2366 Result.FloatImag = APFloat(Real.getSemantics()); 2367 return true; 2368 } 2369 2370 case CK_FloatingComplexCast: { 2371 if (!Visit(E->getSubExpr())) 2372 return false; 2373 2374 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 2375 QualType From 2376 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 2377 2378 Result.FloatReal 2379 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx); 2380 Result.FloatImag 2381 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx); 2382 return true; 2383 } 2384 2385 case CK_FloatingComplexToIntegralComplex: { 2386 if (!Visit(E->getSubExpr())) 2387 return false; 2388 2389 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 2390 QualType From 2391 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 2392 Result.makeComplexInt(); 2393 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx); 2394 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx); 2395 return true; 2396 } 2397 2398 case CK_IntegralRealToComplex: { 2399 APSInt &Real = Result.IntReal; 2400 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 2401 return false; 2402 2403 Result.makeComplexInt(); 2404 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 2405 return true; 2406 } 2407 2408 case CK_IntegralComplexCast: { 2409 if (!Visit(E->getSubExpr())) 2410 return false; 2411 2412 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 2413 QualType From 2414 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 2415 2416 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx); 2417 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx); 2418 return true; 2419 } 2420 2421 case CK_IntegralComplexToFloatingComplex: { 2422 if (!Visit(E->getSubExpr())) 2423 return false; 2424 2425 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 2426 QualType From 2427 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 2428 Result.makeComplexFloat(); 2429 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx); 2430 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx); 2431 return true; 2432 } 2433 } 2434 2435 llvm_unreachable("unknown cast resulting in complex value"); 2436 return false; 2437} 2438 2439bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 2440 if (E->getOpcode() == BO_Comma) { 2441 if (!Visit(E->getRHS())) 2442 return false; 2443 2444 // If we can't evaluate the LHS, it might have side effects; 2445 // conservatively mark it. 2446 if (!E->getLHS()->isEvaluatable(Info.Ctx)) 2447 Info.EvalResult.HasSideEffects = true; 2448 2449 return true; 2450 } 2451 if (!Visit(E->getLHS())) 2452 return false; 2453 2454 ComplexValue RHS; 2455 if (!EvaluateComplex(E->getRHS(), RHS, Info)) 2456 return false; 2457 2458 assert(Result.isComplexFloat() == RHS.isComplexFloat() && 2459 "Invalid operands to binary operator."); 2460 switch (E->getOpcode()) { 2461 default: return false; 2462 case BO_Add: 2463 if (Result.isComplexFloat()) { 2464 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 2465 APFloat::rmNearestTiesToEven); 2466 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 2467 APFloat::rmNearestTiesToEven); 2468 } else { 2469 Result.getComplexIntReal() += RHS.getComplexIntReal(); 2470 Result.getComplexIntImag() += RHS.getComplexIntImag(); 2471 } 2472 break; 2473 case BO_Sub: 2474 if (Result.isComplexFloat()) { 2475 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 2476 APFloat::rmNearestTiesToEven); 2477 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 2478 APFloat::rmNearestTiesToEven); 2479 } else { 2480 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 2481 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 2482 } 2483 break; 2484 case BO_Mul: 2485 if (Result.isComplexFloat()) { 2486 ComplexValue LHS = Result; 2487 APFloat &LHS_r = LHS.getComplexFloatReal(); 2488 APFloat &LHS_i = LHS.getComplexFloatImag(); 2489 APFloat &RHS_r = RHS.getComplexFloatReal(); 2490 APFloat &RHS_i = RHS.getComplexFloatImag(); 2491 2492 APFloat Tmp = LHS_r; 2493 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 2494 Result.getComplexFloatReal() = Tmp; 2495 Tmp = LHS_i; 2496 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 2497 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven); 2498 2499 Tmp = LHS_r; 2500 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 2501 Result.getComplexFloatImag() = Tmp; 2502 Tmp = LHS_i; 2503 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 2504 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven); 2505 } else { 2506 ComplexValue LHS = Result; 2507 Result.getComplexIntReal() = 2508 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 2509 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 2510 Result.getComplexIntImag() = 2511 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 2512 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 2513 } 2514 break; 2515 case BO_Div: 2516 if (Result.isComplexFloat()) { 2517 ComplexValue LHS = Result; 2518 APFloat &LHS_r = LHS.getComplexFloatReal(); 2519 APFloat &LHS_i = LHS.getComplexFloatImag(); 2520 APFloat &RHS_r = RHS.getComplexFloatReal(); 2521 APFloat &RHS_i = RHS.getComplexFloatImag(); 2522 APFloat &Res_r = Result.getComplexFloatReal(); 2523 APFloat &Res_i = Result.getComplexFloatImag(); 2524 2525 APFloat Den = RHS_r; 2526 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven); 2527 APFloat Tmp = RHS_i; 2528 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 2529 Den.add(Tmp, APFloat::rmNearestTiesToEven); 2530 2531 Res_r = LHS_r; 2532 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven); 2533 Tmp = LHS_i; 2534 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 2535 Res_r.add(Tmp, APFloat::rmNearestTiesToEven); 2536 Res_r.divide(Den, APFloat::rmNearestTiesToEven); 2537 2538 Res_i = LHS_i; 2539 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven); 2540 Tmp = LHS_r; 2541 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 2542 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven); 2543 Res_i.divide(Den, APFloat::rmNearestTiesToEven); 2544 } else { 2545 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) { 2546 // FIXME: what about diagnostics? 2547 return false; 2548 } 2549 ComplexValue LHS = Result; 2550 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 2551 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 2552 Result.getComplexIntReal() = 2553 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 2554 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 2555 Result.getComplexIntImag() = 2556 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 2557 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 2558 } 2559 break; 2560 } 2561 2562 return true; 2563} 2564 2565bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 2566 // Get the operand value into 'Result'. 2567 if (!Visit(E->getSubExpr())) 2568 return false; 2569 2570 switch (E->getOpcode()) { 2571 default: 2572 // FIXME: what about diagnostics? 2573 return false; 2574 case UO_Extension: 2575 return true; 2576 case UO_Plus: 2577 // The result is always just the subexpr. 2578 return true; 2579 case UO_Minus: 2580 if (Result.isComplexFloat()) { 2581 Result.getComplexFloatReal().changeSign(); 2582 Result.getComplexFloatImag().changeSign(); 2583 } 2584 else { 2585 Result.getComplexIntReal() = -Result.getComplexIntReal(); 2586 Result.getComplexIntImag() = -Result.getComplexIntImag(); 2587 } 2588 return true; 2589 case UO_Not: 2590 if (Result.isComplexFloat()) 2591 Result.getComplexFloatImag().changeSign(); 2592 else 2593 Result.getComplexIntImag() = -Result.getComplexIntImag(); 2594 return true; 2595 } 2596} 2597 2598bool ComplexExprEvaluator:: 2599VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) { 2600 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon()); 2601 if (opaque.hasError()) return false; 2602 2603 bool cond; 2604 if (!HandleConversionToBool(e->getCond(), cond, Info)) 2605 return false; 2606 2607 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr()); 2608} 2609 2610bool ComplexExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) { 2611 bool Cond; 2612 if (!HandleConversionToBool(E->getCond(), Cond, Info)) 2613 return false; 2614 2615 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr()); 2616} 2617 2618//===----------------------------------------------------------------------===// 2619// Top level Expr::Evaluate method. 2620//===----------------------------------------------------------------------===// 2621 2622static bool Evaluate(EvalInfo &Info, const Expr *E) { 2623 if (E->getType()->isVectorType()) { 2624 if (!EvaluateVector(E, Info.EvalResult.Val, Info)) 2625 return false; 2626 } else if (E->getType()->isIntegerType()) { 2627 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E))) 2628 return false; 2629 if (Info.EvalResult.Val.isLValue() && 2630 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase())) 2631 return false; 2632 } else if (E->getType()->hasPointerRepresentation()) { 2633 LValue LV; 2634 if (!EvaluatePointer(E, LV, Info)) 2635 return false; 2636 if (!IsGlobalLValue(LV.Base)) 2637 return false; 2638 LV.moveInto(Info.EvalResult.Val); 2639 } else if (E->getType()->isRealFloatingType()) { 2640 llvm::APFloat F(0.0); 2641 if (!EvaluateFloat(E, F, Info)) 2642 return false; 2643 2644 Info.EvalResult.Val = APValue(F); 2645 } else if (E->getType()->isAnyComplexType()) { 2646 ComplexValue C; 2647 if (!EvaluateComplex(E, C, Info)) 2648 return false; 2649 C.moveInto(Info.EvalResult.Val); 2650 } else 2651 return false; 2652 2653 return true; 2654} 2655 2656/// Evaluate - Return true if this is a constant which we can fold using 2657/// any crazy technique (that has nothing to do with language standards) that 2658/// we want to. If this function returns true, it returns the folded constant 2659/// in Result. 2660bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const { 2661 EvalInfo Info(Ctx, Result); 2662 return ::Evaluate(Info, this); 2663} 2664 2665bool Expr::EvaluateAsBooleanCondition(bool &Result, 2666 const ASTContext &Ctx) const { 2667 EvalResult Scratch; 2668 EvalInfo Info(Ctx, Scratch); 2669 2670 return HandleConversionToBool(this, Result, Info); 2671} 2672 2673bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 2674 EvalInfo Info(Ctx, Result); 2675 2676 LValue LV; 2677 if (EvaluateLValue(this, LV, Info) && 2678 !Result.HasSideEffects && 2679 IsGlobalLValue(LV.Base)) { 2680 LV.moveInto(Result.Val); 2681 return true; 2682 } 2683 return false; 2684} 2685 2686bool Expr::EvaluateAsAnyLValue(EvalResult &Result, 2687 const ASTContext &Ctx) const { 2688 EvalInfo Info(Ctx, Result); 2689 2690 LValue LV; 2691 if (EvaluateLValue(this, LV, Info)) { 2692 LV.moveInto(Result.Val); 2693 return true; 2694 } 2695 return false; 2696} 2697 2698/// isEvaluatable - Call Evaluate to see if this expression can be constant 2699/// folded, but discard the result. 2700bool Expr::isEvaluatable(const ASTContext &Ctx) const { 2701 EvalResult Result; 2702 return Evaluate(Result, Ctx) && !Result.HasSideEffects; 2703} 2704 2705bool Expr::HasSideEffects(const ASTContext &Ctx) const { 2706 Expr::EvalResult Result; 2707 EvalInfo Info(Ctx, Result); 2708 return HasSideEffect(Info).Visit(const_cast<Expr*>(this)); 2709} 2710 2711APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const { 2712 EvalResult EvalResult; 2713 bool Result = Evaluate(EvalResult, Ctx); 2714 (void)Result; 2715 assert(Result && "Could not evaluate expression"); 2716 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 2717 2718 return EvalResult.Val.getInt(); 2719} 2720 2721 bool Expr::EvalResult::isGlobalLValue() const { 2722 assert(Val.isLValue()); 2723 return IsGlobalLValue(Val.getLValueBase()); 2724 } 2725 2726 2727/// isIntegerConstantExpr - this recursive routine will test if an expression is 2728/// an integer constant expression. 2729 2730/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 2731/// comma, etc 2732/// 2733/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof 2734/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer 2735/// cast+dereference. 2736 2737// CheckICE - This function does the fundamental ICE checking: the returned 2738// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation. 2739// Note that to reduce code duplication, this helper does no evaluation 2740// itself; the caller checks whether the expression is evaluatable, and 2741// in the rare cases where CheckICE actually cares about the evaluated 2742// value, it calls into Evalute. 2743// 2744// Meanings of Val: 2745// 0: This expression is an ICE if it can be evaluated by Evaluate. 2746// 1: This expression is not an ICE, but if it isn't evaluated, it's 2747// a legal subexpression for an ICE. This return value is used to handle 2748// the comma operator in C99 mode. 2749// 2: This expression is not an ICE, and is not a legal subexpression for one. 2750 2751namespace { 2752 2753struct ICEDiag { 2754 unsigned Val; 2755 SourceLocation Loc; 2756 2757 public: 2758 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {} 2759 ICEDiag() : Val(0) {} 2760}; 2761 2762} 2763 2764static ICEDiag NoDiag() { return ICEDiag(); } 2765 2766static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) { 2767 Expr::EvalResult EVResult; 2768 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects || 2769 !EVResult.Val.isInt()) { 2770 return ICEDiag(2, E->getLocStart()); 2771 } 2772 return NoDiag(); 2773} 2774 2775static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) { 2776 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 2777 if (!E->getType()->isIntegralOrEnumerationType()) { 2778 return ICEDiag(2, E->getLocStart()); 2779 } 2780 2781 switch (E->getStmtClass()) { 2782#define ABSTRACT_STMT(Node) 2783#define STMT(Node, Base) case Expr::Node##Class: 2784#define EXPR(Node, Base) 2785#include "clang/AST/StmtNodes.inc" 2786 case Expr::PredefinedExprClass: 2787 case Expr::FloatingLiteralClass: 2788 case Expr::ImaginaryLiteralClass: 2789 case Expr::StringLiteralClass: 2790 case Expr::ArraySubscriptExprClass: 2791 case Expr::MemberExprClass: 2792 case Expr::CompoundAssignOperatorClass: 2793 case Expr::CompoundLiteralExprClass: 2794 case Expr::ExtVectorElementExprClass: 2795 case Expr::InitListExprClass: 2796 case Expr::DesignatedInitExprClass: 2797 case Expr::ImplicitValueInitExprClass: 2798 case Expr::ParenListExprClass: 2799 case Expr::VAArgExprClass: 2800 case Expr::AddrLabelExprClass: 2801 case Expr::StmtExprClass: 2802 case Expr::CXXMemberCallExprClass: 2803 case Expr::CUDAKernelCallExprClass: 2804 case Expr::CXXDynamicCastExprClass: 2805 case Expr::CXXTypeidExprClass: 2806 case Expr::CXXUuidofExprClass: 2807 case Expr::CXXNullPtrLiteralExprClass: 2808 case Expr::CXXThisExprClass: 2809 case Expr::CXXThrowExprClass: 2810 case Expr::CXXNewExprClass: 2811 case Expr::CXXDeleteExprClass: 2812 case Expr::CXXPseudoDestructorExprClass: 2813 case Expr::UnresolvedLookupExprClass: 2814 case Expr::DependentScopeDeclRefExprClass: 2815 case Expr::CXXConstructExprClass: 2816 case Expr::CXXBindTemporaryExprClass: 2817 case Expr::ExprWithCleanupsClass: 2818 case Expr::CXXTemporaryObjectExprClass: 2819 case Expr::CXXUnresolvedConstructExprClass: 2820 case Expr::CXXDependentScopeMemberExprClass: 2821 case Expr::UnresolvedMemberExprClass: 2822 case Expr::ObjCStringLiteralClass: 2823 case Expr::ObjCEncodeExprClass: 2824 case Expr::ObjCMessageExprClass: 2825 case Expr::ObjCSelectorExprClass: 2826 case Expr::ObjCProtocolExprClass: 2827 case Expr::ObjCIvarRefExprClass: 2828 case Expr::ObjCPropertyRefExprClass: 2829 case Expr::ObjCIsaExprClass: 2830 case Expr::ShuffleVectorExprClass: 2831 case Expr::BlockExprClass: 2832 case Expr::BlockDeclRefExprClass: 2833 case Expr::NoStmtClass: 2834 case Expr::OpaqueValueExprClass: 2835 case Expr::PackExpansionExprClass: 2836 case Expr::SubstNonTypeTemplateParmPackExprClass: 2837 return ICEDiag(2, E->getLocStart()); 2838 2839 case Expr::SizeOfPackExprClass: 2840 case Expr::GNUNullExprClass: 2841 // GCC considers the GNU __null value to be an integral constant expression. 2842 return NoDiag(); 2843 2844 case Expr::ParenExprClass: 2845 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 2846 case Expr::IntegerLiteralClass: 2847 case Expr::CharacterLiteralClass: 2848 case Expr::CXXBoolLiteralExprClass: 2849 case Expr::CXXScalarValueInitExprClass: 2850 case Expr::UnaryTypeTraitExprClass: 2851 case Expr::BinaryTypeTraitExprClass: 2852 case Expr::CXXNoexceptExprClass: 2853 return NoDiag(); 2854 case Expr::CallExprClass: 2855 case Expr::CXXOperatorCallExprClass: { 2856 const CallExpr *CE = cast<CallExpr>(E); 2857 if (CE->isBuiltinCall(Ctx)) 2858 return CheckEvalInICE(E, Ctx); 2859 return ICEDiag(2, E->getLocStart()); 2860 } 2861 case Expr::DeclRefExprClass: 2862 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 2863 return NoDiag(); 2864 if (Ctx.getLangOptions().CPlusPlus && 2865 E->getType().getCVRQualifiers() == Qualifiers::Const) { 2866 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 2867 2868 // Parameter variables are never constants. Without this check, 2869 // getAnyInitializer() can find a default argument, which leads 2870 // to chaos. 2871 if (isa<ParmVarDecl>(D)) 2872 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 2873 2874 // C++ 7.1.5.1p2 2875 // A variable of non-volatile const-qualified integral or enumeration 2876 // type initialized by an ICE can be used in ICEs. 2877 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 2878 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers(); 2879 if (Quals.hasVolatile() || !Quals.hasConst()) 2880 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 2881 2882 // Look for a declaration of this variable that has an initializer. 2883 const VarDecl *ID = 0; 2884 const Expr *Init = Dcl->getAnyInitializer(ID); 2885 if (Init) { 2886 if (ID->isInitKnownICE()) { 2887 // We have already checked whether this subexpression is an 2888 // integral constant expression. 2889 if (ID->isInitICE()) 2890 return NoDiag(); 2891 else 2892 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 2893 } 2894 2895 // It's an ICE whether or not the definition we found is 2896 // out-of-line. See DR 721 and the discussion in Clang PR 2897 // 6206 for details. 2898 2899 if (Dcl->isCheckingICE()) { 2900 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 2901 } 2902 2903 Dcl->setCheckingICE(); 2904 ICEDiag Result = CheckICE(Init, Ctx); 2905 // Cache the result of the ICE test. 2906 Dcl->setInitKnownICE(Result.Val == 0); 2907 return Result; 2908 } 2909 } 2910 } 2911 return ICEDiag(2, E->getLocStart()); 2912 case Expr::UnaryOperatorClass: { 2913 const UnaryOperator *Exp = cast<UnaryOperator>(E); 2914 switch (Exp->getOpcode()) { 2915 case UO_PostInc: 2916 case UO_PostDec: 2917 case UO_PreInc: 2918 case UO_PreDec: 2919 case UO_AddrOf: 2920 case UO_Deref: 2921 return ICEDiag(2, E->getLocStart()); 2922 case UO_Extension: 2923 case UO_LNot: 2924 case UO_Plus: 2925 case UO_Minus: 2926 case UO_Not: 2927 case UO_Real: 2928 case UO_Imag: 2929 return CheckICE(Exp->getSubExpr(), Ctx); 2930 } 2931 2932 // OffsetOf falls through here. 2933 } 2934 case Expr::OffsetOfExprClass: { 2935 // Note that per C99, offsetof must be an ICE. And AFAIK, using 2936 // Evaluate matches the proposed gcc behavior for cases like 2937 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect 2938 // compliance: we should warn earlier for offsetof expressions with 2939 // array subscripts that aren't ICEs, and if the array subscripts 2940 // are ICEs, the value of the offsetof must be an integer constant. 2941 return CheckEvalInICE(E, Ctx); 2942 } 2943 case Expr::UnaryExprOrTypeTraitExprClass: { 2944 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 2945 if ((Exp->getKind() == UETT_SizeOf) && 2946 Exp->getTypeOfArgument()->isVariableArrayType()) 2947 return ICEDiag(2, E->getLocStart()); 2948 return NoDiag(); 2949 } 2950 case Expr::BinaryOperatorClass: { 2951 const BinaryOperator *Exp = cast<BinaryOperator>(E); 2952 switch (Exp->getOpcode()) { 2953 case BO_PtrMemD: 2954 case BO_PtrMemI: 2955 case BO_Assign: 2956 case BO_MulAssign: 2957 case BO_DivAssign: 2958 case BO_RemAssign: 2959 case BO_AddAssign: 2960 case BO_SubAssign: 2961 case BO_ShlAssign: 2962 case BO_ShrAssign: 2963 case BO_AndAssign: 2964 case BO_XorAssign: 2965 case BO_OrAssign: 2966 return ICEDiag(2, E->getLocStart()); 2967 2968 case BO_Mul: 2969 case BO_Div: 2970 case BO_Rem: 2971 case BO_Add: 2972 case BO_Sub: 2973 case BO_Shl: 2974 case BO_Shr: 2975 case BO_LT: 2976 case BO_GT: 2977 case BO_LE: 2978 case BO_GE: 2979 case BO_EQ: 2980 case BO_NE: 2981 case BO_And: 2982 case BO_Xor: 2983 case BO_Or: 2984 case BO_Comma: { 2985 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 2986 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 2987 if (Exp->getOpcode() == BO_Div || 2988 Exp->getOpcode() == BO_Rem) { 2989 // Evaluate gives an error for undefined Div/Rem, so make sure 2990 // we don't evaluate one. 2991 if (LHSResult.Val == 0 && RHSResult.Val == 0) { 2992 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx); 2993 if (REval == 0) 2994 return ICEDiag(1, E->getLocStart()); 2995 if (REval.isSigned() && REval.isAllOnesValue()) { 2996 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx); 2997 if (LEval.isMinSignedValue()) 2998 return ICEDiag(1, E->getLocStart()); 2999 } 3000 } 3001 } 3002 if (Exp->getOpcode() == BO_Comma) { 3003 if (Ctx.getLangOptions().C99) { 3004 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 3005 // if it isn't evaluated. 3006 if (LHSResult.Val == 0 && RHSResult.Val == 0) 3007 return ICEDiag(1, E->getLocStart()); 3008 } else { 3009 // In both C89 and C++, commas in ICEs are illegal. 3010 return ICEDiag(2, E->getLocStart()); 3011 } 3012 } 3013 if (LHSResult.Val >= RHSResult.Val) 3014 return LHSResult; 3015 return RHSResult; 3016 } 3017 case BO_LAnd: 3018 case BO_LOr: { 3019 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 3020 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 3021 if (LHSResult.Val == 0 && RHSResult.Val == 1) { 3022 // Rare case where the RHS has a comma "side-effect"; we need 3023 // to actually check the condition to see whether the side 3024 // with the comma is evaluated. 3025 if ((Exp->getOpcode() == BO_LAnd) != 3026 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0)) 3027 return RHSResult; 3028 return NoDiag(); 3029 } 3030 3031 if (LHSResult.Val >= RHSResult.Val) 3032 return LHSResult; 3033 return RHSResult; 3034 } 3035 } 3036 } 3037 case Expr::ImplicitCastExprClass: 3038 case Expr::CStyleCastExprClass: 3039 case Expr::CXXFunctionalCastExprClass: 3040 case Expr::CXXStaticCastExprClass: 3041 case Expr::CXXReinterpretCastExprClass: 3042 case Expr::CXXConstCastExprClass: { 3043 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 3044 if (SubExpr->getType()->isIntegralOrEnumerationType()) 3045 return CheckICE(SubExpr, Ctx); 3046 if (isa<FloatingLiteral>(SubExpr->IgnoreParens())) 3047 return NoDiag(); 3048 return ICEDiag(2, E->getLocStart()); 3049 } 3050 case Expr::BinaryConditionalOperatorClass: { 3051 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 3052 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 3053 if (CommonResult.Val == 2) return CommonResult; 3054 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 3055 if (FalseResult.Val == 2) return FalseResult; 3056 if (CommonResult.Val == 1) return CommonResult; 3057 if (FalseResult.Val == 1 && 3058 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag(); 3059 return FalseResult; 3060 } 3061 case Expr::ConditionalOperatorClass: { 3062 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 3063 // If the condition (ignoring parens) is a __builtin_constant_p call, 3064 // then only the true side is actually considered in an integer constant 3065 // expression, and it is fully evaluated. This is an important GNU 3066 // extension. See GCC PR38377 for discussion. 3067 if (const CallExpr *CallCE 3068 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 3069 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) { 3070 Expr::EvalResult EVResult; 3071 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects || 3072 !EVResult.Val.isInt()) { 3073 return ICEDiag(2, E->getLocStart()); 3074 } 3075 return NoDiag(); 3076 } 3077 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 3078 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 3079 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 3080 if (CondResult.Val == 2) 3081 return CondResult; 3082 if (TrueResult.Val == 2) 3083 return TrueResult; 3084 if (FalseResult.Val == 2) 3085 return FalseResult; 3086 if (CondResult.Val == 1) 3087 return CondResult; 3088 if (TrueResult.Val == 0 && FalseResult.Val == 0) 3089 return NoDiag(); 3090 // Rare case where the diagnostics depend on which side is evaluated 3091 // Note that if we get here, CondResult is 0, and at least one of 3092 // TrueResult and FalseResult is non-zero. 3093 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) { 3094 return FalseResult; 3095 } 3096 return TrueResult; 3097 } 3098 case Expr::CXXDefaultArgExprClass: 3099 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 3100 case Expr::ChooseExprClass: { 3101 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx); 3102 } 3103 } 3104 3105 // Silence a GCC warning 3106 return ICEDiag(2, E->getLocStart()); 3107} 3108 3109bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx, 3110 SourceLocation *Loc, bool isEvaluated) const { 3111 ICEDiag d = CheckICE(this, Ctx); 3112 if (d.Val != 0) { 3113 if (Loc) *Loc = d.Loc; 3114 return false; 3115 } 3116 EvalResult EvalResult; 3117 if (!Evaluate(EvalResult, Ctx)) 3118 llvm_unreachable("ICE cannot be evaluated!"); 3119 assert(!EvalResult.HasSideEffects && "ICE with side effects!"); 3120 assert(EvalResult.Val.isInt() && "ICE that isn't integer!"); 3121 Result = EvalResult.Val.getInt(); 3122 return true; 3123} 3124