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