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