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