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 /// Find the path length and type of the most-derived subobject in the given 80 /// path, and find the size of the containing array, if any. 81 static 82 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base, 83 ArrayRef<APValue::LValuePathEntry> Path, 84 uint64_t &ArraySize, QualType &Type) { 85 unsigned MostDerivedLength = 0; 86 Type = Base; 87 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 88 if (Type->isArrayType()) { 89 const ConstantArrayType *CAT = 90 cast<ConstantArrayType>(Ctx.getAsArrayType(Type)); 91 Type = CAT->getElementType(); 92 ArraySize = CAT->getSize().getZExtValue(); 93 MostDerivedLength = I + 1; 94 } else if (const FieldDecl *FD = getAsField(Path[I])) { 95 Type = FD->getType(); 96 ArraySize = 0; 97 MostDerivedLength = I + 1; 98 } else { 99 // Path[I] describes a base class. 100 ArraySize = 0; 101 } 102 } 103 return MostDerivedLength; 104 } 105 106 // The order of this enum is important for diagnostics. 107 enum CheckSubobjectKind { 108 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex 109 }; 110 111 /// A path from a glvalue to a subobject of that glvalue. 112 struct SubobjectDesignator { 113 /// True if the subobject was named in a manner not supported by C++11. Such 114 /// lvalues can still be folded, but they are not core constant expressions 115 /// and we cannot perform lvalue-to-rvalue conversions on them. 116 bool Invalid : 1; 117 118 /// Is this a pointer one past the end of an object? 119 bool IsOnePastTheEnd : 1; 120 121 /// The length of the path to the most-derived object of which this is a 122 /// subobject. 123 unsigned MostDerivedPathLength : 30; 124 125 /// The size of the array of which the most-derived object is an element, or 126 /// 0 if the most-derived object is not an array element. 127 uint64_t MostDerivedArraySize; 128 129 /// The type of the most derived object referred to by this address. 130 QualType MostDerivedType; 131 132 typedef APValue::LValuePathEntry PathEntry; 133 134 /// The entries on the path from the glvalue to the designated subobject. 135 SmallVector<PathEntry, 8> Entries; 136 137 SubobjectDesignator() : Invalid(true) {} 138 139 explicit SubobjectDesignator(QualType T) 140 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0), 141 MostDerivedArraySize(0), MostDerivedType(T) {} 142 143 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 144 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 145 MostDerivedPathLength(0), MostDerivedArraySize(0) { 146 if (!Invalid) { 147 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 148 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 149 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 150 if (V.getLValueBase()) 151 MostDerivedPathLength = 152 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()), 153 V.getLValuePath(), MostDerivedArraySize, 154 MostDerivedType); 155 } 156 } 157 158 void setInvalid() { 159 Invalid = true; 160 Entries.clear(); 161 } 162 163 /// Determine whether this is a one-past-the-end pointer. 164 bool isOnePastTheEnd() const { 165 if (IsOnePastTheEnd) 166 return true; 167 if (MostDerivedArraySize && 168 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize) 169 return true; 170 return false; 171 } 172 173 /// Check that this refers to a valid subobject. 174 bool isValidSubobject() const { 175 if (Invalid) 176 return false; 177 return !isOnePastTheEnd(); 178 } 179 /// Check that this refers to a valid subobject, and if not, produce a 180 /// relevant diagnostic and set the designator as invalid. 181 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 182 183 /// Update this designator to refer to the first element within this array. 184 void addArrayUnchecked(const ConstantArrayType *CAT) { 185 PathEntry Entry; 186 Entry.ArrayIndex = 0; 187 Entries.push_back(Entry); 188 189 // This is a most-derived object. 190 MostDerivedType = CAT->getElementType(); 191 MostDerivedArraySize = CAT->getSize().getZExtValue(); 192 MostDerivedPathLength = Entries.size(); 193 } 194 /// Update this designator to refer to the given base or member of this 195 /// object. 196 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 197 PathEntry Entry; 198 APValue::BaseOrMemberType Value(D, Virtual); 199 Entry.BaseOrMember = Value.getOpaqueValue(); 200 Entries.push_back(Entry); 201 202 // If this isn't a base class, it's a new most-derived object. 203 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 204 MostDerivedType = FD->getType(); 205 MostDerivedArraySize = 0; 206 MostDerivedPathLength = Entries.size(); 207 } 208 } 209 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N); 210 /// Add N to the address of this subobject. 211 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) { 212 if (Invalid) return; 213 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) { 214 Entries.back().ArrayIndex += N; 215 if (Entries.back().ArrayIndex > MostDerivedArraySize) { 216 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex); 217 setInvalid(); 218 } 219 return; 220 } 221 // [expr.add]p4: For the purposes of these operators, a pointer to a 222 // nonarray object behaves the same as a pointer to the first element of 223 // an array of length one with the type of the object as its element type. 224 if (IsOnePastTheEnd && N == (uint64_t)-1) 225 IsOnePastTheEnd = false; 226 else if (!IsOnePastTheEnd && N == 1) 227 IsOnePastTheEnd = true; 228 else if (N != 0) { 229 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N); 230 setInvalid(); 231 } 232 } 233 }; 234 235 /// A core constant value. This can be the value of any constant expression, 236 /// or a pointer or reference to a non-static object or function parameter. 237 /// 238 /// For an LValue, the base and offset are stored in the APValue subobject, 239 /// but the other information is stored in the SubobjectDesignator. For all 240 /// other value kinds, the value is stored directly in the APValue subobject. 241 class CCValue : public APValue { 242 typedef llvm::APSInt APSInt; 243 typedef llvm::APFloat APFloat; 244 /// If the value is a reference or pointer into a parameter or temporary, 245 /// this is the corresponding call stack frame. 246 CallStackFrame *CallFrame; 247 /// If the value is a reference or pointer, this is a description of how the 248 /// subobject was specified. 249 SubobjectDesignator Designator; 250 public: 251 struct GlobalValue {}; 252 253 CCValue() {} 254 explicit CCValue(const APSInt &I) : APValue(I) {} 255 explicit CCValue(const APFloat &F) : APValue(F) {} 256 CCValue(const APValue *E, unsigned N) : APValue(E, N) {} 257 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {} 258 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {} 259 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {} 260 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F, 261 const SubobjectDesignator &D) : 262 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {} 263 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) : 264 APValue(V), CallFrame(0), Designator(Ctx, V) {} 265 CCValue(const ValueDecl *D, bool IsDerivedMember, 266 ArrayRef<const CXXRecordDecl*> Path) : 267 APValue(D, IsDerivedMember, Path) {} 268 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) : 269 APValue(LHSExpr, RHSExpr) {} 270 271 CallStackFrame *getLValueFrame() const { 272 assert(getKind() == LValue); 273 return CallFrame; 274 } 275 SubobjectDesignator &getLValueDesignator() { 276 assert(getKind() == LValue); 277 return Designator; 278 } 279 const SubobjectDesignator &getLValueDesignator() const { 280 return const_cast<CCValue*>(this)->getLValueDesignator(); 281 } 282 }; 283 284 /// A stack frame in the constexpr call stack. 285 struct CallStackFrame { 286 EvalInfo &Info; 287 288 /// Parent - The caller of this stack frame. 289 CallStackFrame *Caller; 290 291 /// CallLoc - The location of the call expression for this call. 292 SourceLocation CallLoc; 293 294 /// Callee - The function which was called. 295 const FunctionDecl *Callee; 296 297 /// This - The binding for the this pointer in this call, if any. 298 const LValue *This; 299 300 /// ParmBindings - Parameter bindings for this function call, indexed by 301 /// parameters' function scope indices. 302 const CCValue *Arguments; 303 304 typedef llvm::DenseMap<const Expr*, CCValue> MapTy; 305 typedef MapTy::const_iterator temp_iterator; 306 /// Temporaries - Temporary lvalues materialized within this stack frame. 307 MapTy Temporaries; 308 309 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 310 const FunctionDecl *Callee, const LValue *This, 311 const CCValue *Arguments); 312 ~CallStackFrame(); 313 }; 314 315 /// A partial diagnostic which we might know in advance that we are not going 316 /// to emit. 317 class OptionalDiagnostic { 318 PartialDiagnostic *Diag; 319 320 public: 321 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {} 322 323 template<typename T> 324 OptionalDiagnostic &operator<<(const T &v) { 325 if (Diag) 326 *Diag << v; 327 return *this; 328 } 329 }; 330 331 struct EvalInfo { 332 ASTContext &Ctx; 333 334 /// EvalStatus - Contains information about the evaluation. 335 Expr::EvalStatus &EvalStatus; 336 337 /// CurrentCall - The top of the constexpr call stack. 338 CallStackFrame *CurrentCall; 339 340 /// CallStackDepth - The number of calls in the call stack right now. 341 unsigned CallStackDepth; 342 343 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy; 344 /// OpaqueValues - Values used as the common expression in a 345 /// BinaryConditionalOperator. 346 MapTy OpaqueValues; 347 348 /// BottomFrame - The frame in which evaluation started. This must be 349 /// initialized last. 350 CallStackFrame BottomFrame; 351 352 /// EvaluatingDecl - This is the declaration whose initializer is being 353 /// evaluated, if any. 354 const VarDecl *EvaluatingDecl; 355 356 /// EvaluatingDeclValue - This is the value being constructed for the 357 /// declaration whose initializer is being evaluated, if any. 358 APValue *EvaluatingDeclValue; 359 360 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 361 /// notes attached to it will also be stored, otherwise they will not be. 362 bool HasActiveDiagnostic; 363 364 365 EvalInfo(const ASTContext &C, Expr::EvalStatus &S) 366 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0), 367 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0), 368 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {} 369 370 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const { 371 MapTy::const_iterator i = OpaqueValues.find(e); 372 if (i == OpaqueValues.end()) return 0; 373 return &i->second; 374 } 375 376 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) { 377 EvaluatingDecl = VD; 378 EvaluatingDeclValue = &Value; 379 } 380 381 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); } 382 383 bool CheckCallLimit(SourceLocation Loc) { 384 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 385 return true; 386 Diag(Loc, diag::note_constexpr_depth_limit_exceeded) 387 << getLangOpts().ConstexprCallDepth; 388 return false; 389 } 390 391 private: 392 /// Add a diagnostic to the diagnostics list. 393 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 394 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 395 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 396 return EvalStatus.Diag->back().second; 397 } 398 399 /// Add notes containing a call stack to the current point of evaluation. 400 void addCallStack(unsigned Limit); 401 402 public: 403 /// Diagnose that the evaluation cannot be folded. 404 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId 405 = diag::note_invalid_subexpr_in_const_expr, 406 unsigned ExtraNotes = 0) { 407 // If we have a prior diagnostic, it will be noting that the expression 408 // isn't a constant expression. This diagnostic is more important. 409 // FIXME: We might want to show both diagnostics to the user. 410 if (EvalStatus.Diag) { 411 unsigned CallStackNotes = CallStackDepth - 1; 412 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 413 if (Limit) 414 CallStackNotes = std::min(CallStackNotes, Limit + 1); 415 416 HasActiveDiagnostic = true; 417 EvalStatus.Diag->clear(); 418 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 419 addDiag(Loc, DiagId); 420 addCallStack(Limit); 421 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 422 } 423 HasActiveDiagnostic = false; 424 return OptionalDiagnostic(); 425 } 426 427 /// Diagnose that the evaluation does not produce a C++11 core constant 428 /// expression. 429 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 430 = diag::note_invalid_subexpr_in_const_expr, 431 unsigned ExtraNotes = 0) { 432 // Don't override a previous diagnostic. 433 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) 434 return OptionalDiagnostic(); 435 return Diag(Loc, DiagId, ExtraNotes); 436 } 437 438 /// Add a note to a prior diagnostic. 439 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 440 if (!HasActiveDiagnostic) 441 return OptionalDiagnostic(); 442 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 443 } 444 445 /// Add a stack of notes to a prior diagnostic. 446 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 447 if (HasActiveDiagnostic) { 448 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 449 Diags.begin(), Diags.end()); 450 } 451 } 452 }; 453 } 454 455 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 456 CheckSubobjectKind CSK) { 457 if (Invalid) 458 return false; 459 if (isOnePastTheEnd()) { 460 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject) 461 << CSK; 462 setInvalid(); 463 return false; 464 } 465 return true; 466 } 467 468 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 469 const Expr *E, uint64_t N) { 470 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) 471 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index) 472 << static_cast<int>(N) << /*array*/ 0 473 << static_cast<unsigned>(MostDerivedArraySize); 474 else 475 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index) 476 << static_cast<int>(N) << /*non-array*/ 1; 477 setInvalid(); 478 } 479 480 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 481 const FunctionDecl *Callee, const LValue *This, 482 const CCValue *Arguments) 483 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee), 484 This(This), Arguments(Arguments) { 485 Info.CurrentCall = this; 486 ++Info.CallStackDepth; 487 } 488 489 CallStackFrame::~CallStackFrame() { 490 assert(Info.CurrentCall == this && "calls retired out of order"); 491 --Info.CallStackDepth; 492 Info.CurrentCall = Caller; 493 } 494 495 /// Produce a string describing the given constexpr call. 496 static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) { 497 unsigned ArgIndex = 0; 498 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 499 !isa<CXXConstructorDecl>(Frame->Callee); 500 501 if (!IsMemberCall) 502 Out << *Frame->Callee << '('; 503 504 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 505 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 506 if (ArgIndex > IsMemberCall) 507 Out << ", "; 508 509 const ParmVarDecl *Param = *I; 510 const CCValue &Arg = Frame->Arguments[ArgIndex]; 511 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid) 512 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 513 else { 514 // Deliberately slice off the frame to form an APValue we can print. 515 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(), 516 Arg.getLValueDesignator().Entries, 517 Arg.getLValueDesignator().IsOnePastTheEnd); 518 Value.printPretty(Out, Frame->Info.Ctx, Param->getType()); 519 } 520 521 if (ArgIndex == 0 && IsMemberCall) 522 Out << "->" << *Frame->Callee << '('; 523 } 524 525 Out << ')'; 526 } 527 528 void EvalInfo::addCallStack(unsigned Limit) { 529 // Determine which calls to skip, if any. 530 unsigned ActiveCalls = CallStackDepth - 1; 531 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 532 if (Limit && Limit < ActiveCalls) { 533 SkipStart = Limit / 2 + Limit % 2; 534 SkipEnd = ActiveCalls - Limit / 2; 535 } 536 537 // Walk the call stack and add the diagnostics. 538 unsigned CallIdx = 0; 539 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 540 Frame = Frame->Caller, ++CallIdx) { 541 // Skip this call? 542 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 543 if (CallIdx == SkipStart) { 544 // Note that we're skipping calls. 545 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 546 << unsigned(ActiveCalls - Limit); 547 } 548 continue; 549 } 550 551 llvm::SmallVector<char, 128> Buffer; 552 llvm::raw_svector_ostream Out(Buffer); 553 describeCall(Frame, Out); 554 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 555 } 556 } 557 558 namespace { 559 struct ComplexValue { 560 private: 561 bool IsInt; 562 563 public: 564 APSInt IntReal, IntImag; 565 APFloat FloatReal, FloatImag; 566 567 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {} 568 569 void makeComplexFloat() { IsInt = false; } 570 bool isComplexFloat() const { return !IsInt; } 571 APFloat &getComplexFloatReal() { return FloatReal; } 572 APFloat &getComplexFloatImag() { return FloatImag; } 573 574 void makeComplexInt() { IsInt = true; } 575 bool isComplexInt() const { return IsInt; } 576 APSInt &getComplexIntReal() { return IntReal; } 577 APSInt &getComplexIntImag() { return IntImag; } 578 579 void moveInto(CCValue &v) const { 580 if (isComplexFloat()) 581 v = CCValue(FloatReal, FloatImag); 582 else 583 v = CCValue(IntReal, IntImag); 584 } 585 void setFrom(const CCValue &v) { 586 assert(v.isComplexFloat() || v.isComplexInt()); 587 if (v.isComplexFloat()) { 588 makeComplexFloat(); 589 FloatReal = v.getComplexFloatReal(); 590 FloatImag = v.getComplexFloatImag(); 591 } else { 592 makeComplexInt(); 593 IntReal = v.getComplexIntReal(); 594 IntImag = v.getComplexIntImag(); 595 } 596 } 597 }; 598 599 struct LValue { 600 APValue::LValueBase Base; 601 CharUnits Offset; 602 CallStackFrame *Frame; 603 SubobjectDesignator Designator; 604 605 const APValue::LValueBase getLValueBase() const { return Base; } 606 CharUnits &getLValueOffset() { return Offset; } 607 const CharUnits &getLValueOffset() const { return Offset; } 608 CallStackFrame *getLValueFrame() const { return Frame; } 609 SubobjectDesignator &getLValueDesignator() { return Designator; } 610 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 611 612 void moveInto(CCValue &V) const { 613 V = CCValue(Base, Offset, Frame, Designator); 614 } 615 void setFrom(const CCValue &V) { 616 assert(V.isLValue()); 617 Base = V.getLValueBase(); 618 Offset = V.getLValueOffset(); 619 Frame = V.getLValueFrame(); 620 Designator = V.getLValueDesignator(); 621 } 622 623 void set(APValue::LValueBase B, CallStackFrame *F = 0) { 624 Base = B; 625 Offset = CharUnits::Zero(); 626 Frame = F; 627 Designator = SubobjectDesignator(getType(B)); 628 } 629 630 // Check that this LValue is not based on a null pointer. If it is, produce 631 // a diagnostic and mark the designator as invalid. 632 bool checkNullPointer(EvalInfo &Info, const Expr *E, 633 CheckSubobjectKind CSK) { 634 if (Designator.Invalid) 635 return false; 636 if (!Base) { 637 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject) 638 << CSK; 639 Designator.setInvalid(); 640 return false; 641 } 642 return true; 643 } 644 645 // Check this LValue refers to an object. If not, set the designator to be 646 // invalid and emit a diagnostic. 647 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 648 return checkNullPointer(Info, E, CSK) && 649 Designator.checkSubobject(Info, E, CSK); 650 } 651 652 void addDecl(EvalInfo &Info, const Expr *E, 653 const Decl *D, bool Virtual = false) { 654 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base); 655 Designator.addDeclUnchecked(D, Virtual); 656 } 657 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 658 checkSubobject(Info, E, CSK_ArrayToPointer); 659 Designator.addArrayUnchecked(CAT); 660 } 661 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) { 662 if (!checkNullPointer(Info, E, CSK_ArrayIndex)) 663 return; 664 Designator.adjustIndex(Info, E, N); 665 } 666 }; 667 668 struct MemberPtr { 669 MemberPtr() {} 670 explicit MemberPtr(const ValueDecl *Decl) : 671 DeclAndIsDerivedMember(Decl, false), Path() {} 672 673 /// The member or (direct or indirect) field referred to by this member 674 /// pointer, or 0 if this is a null member pointer. 675 const ValueDecl *getDecl() const { 676 return DeclAndIsDerivedMember.getPointer(); 677 } 678 /// Is this actually a member of some type derived from the relevant class? 679 bool isDerivedMember() const { 680 return DeclAndIsDerivedMember.getInt(); 681 } 682 /// Get the class which the declaration actually lives in. 683 const CXXRecordDecl *getContainingRecord() const { 684 return cast<CXXRecordDecl>( 685 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 686 } 687 688 void moveInto(CCValue &V) const { 689 V = CCValue(getDecl(), isDerivedMember(), Path); 690 } 691 void setFrom(const CCValue &V) { 692 assert(V.isMemberPointer()); 693 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 694 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 695 Path.clear(); 696 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 697 Path.insert(Path.end(), P.begin(), P.end()); 698 } 699 700 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 701 /// whether the member is a member of some class derived from the class type 702 /// of the member pointer. 703 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 704 /// Path - The path of base/derived classes from the member declaration's 705 /// class (exclusive) to the class type of the member pointer (inclusive). 706 SmallVector<const CXXRecordDecl*, 4> Path; 707 708 /// Perform a cast towards the class of the Decl (either up or down the 709 /// hierarchy). 710 bool castBack(const CXXRecordDecl *Class) { 711 assert(!Path.empty()); 712 const CXXRecordDecl *Expected; 713 if (Path.size() >= 2) 714 Expected = Path[Path.size() - 2]; 715 else 716 Expected = getContainingRecord(); 717 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 718 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 719 // if B does not contain the original member and is not a base or 720 // derived class of the class containing the original member, the result 721 // of the cast is undefined. 722 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 723 // (D::*). We consider that to be a language defect. 724 return false; 725 } 726 Path.pop_back(); 727 return true; 728 } 729 /// Perform a base-to-derived member pointer cast. 730 bool castToDerived(const CXXRecordDecl *Derived) { 731 if (!getDecl()) 732 return true; 733 if (!isDerivedMember()) { 734 Path.push_back(Derived); 735 return true; 736 } 737 if (!castBack(Derived)) 738 return false; 739 if (Path.empty()) 740 DeclAndIsDerivedMember.setInt(false); 741 return true; 742 } 743 /// Perform a derived-to-base member pointer cast. 744 bool castToBase(const CXXRecordDecl *Base) { 745 if (!getDecl()) 746 return true; 747 if (Path.empty()) 748 DeclAndIsDerivedMember.setInt(true); 749 if (isDerivedMember()) { 750 Path.push_back(Base); 751 return true; 752 } 753 return castBack(Base); 754 } 755 }; 756 757 /// Kinds of constant expression checking, for diagnostics. 758 enum CheckConstantExpressionKind { 759 CCEK_Constant, ///< A normal constant. 760 CCEK_ReturnValue, ///< A constexpr function return value. 761 CCEK_MemberInit ///< A constexpr constructor mem-initializer. 762 }; 763 } 764 765 static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E); 766 static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info, 767 const LValue &This, const Expr *E, 768 CheckConstantExpressionKind CCEK 769 = CCEK_Constant); 770 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info); 771 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info); 772 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 773 EvalInfo &Info); 774 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 775 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 776 static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result, 777 EvalInfo &Info); 778 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 779 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 780 781 //===----------------------------------------------------------------------===// 782 // Misc utilities 783 //===----------------------------------------------------------------------===// 784 785 /// Should this call expression be treated as a string literal? 786 static bool IsStringLiteralCall(const CallExpr *E) { 787 unsigned Builtin = E->isBuiltinCall(); 788 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 789 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 790 } 791 792 static bool IsGlobalLValue(APValue::LValueBase B) { 793 // C++11 [expr.const]p3 An address constant expression is a prvalue core 794 // constant expression of pointer type that evaluates to... 795 796 // ... a null pointer value, or a prvalue core constant expression of type 797 // std::nullptr_t. 798 if (!B) return true; 799 800 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 801 // ... the address of an object with static storage duration, 802 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 803 return VD->hasGlobalStorage(); 804 // ... the address of a function, 805 return isa<FunctionDecl>(D); 806 } 807 808 const Expr *E = B.get<const Expr*>(); 809 switch (E->getStmtClass()) { 810 default: 811 return false; 812 case Expr::CompoundLiteralExprClass: 813 return cast<CompoundLiteralExpr>(E)->isFileScope(); 814 // A string literal has static storage duration. 815 case Expr::StringLiteralClass: 816 case Expr::PredefinedExprClass: 817 case Expr::ObjCStringLiteralClass: 818 case Expr::ObjCEncodeExprClass: 819 case Expr::CXXTypeidExprClass: 820 return true; 821 case Expr::CallExprClass: 822 return IsStringLiteralCall(cast<CallExpr>(E)); 823 // For GCC compatibility, &&label has static storage duration. 824 case Expr::AddrLabelExprClass: 825 return true; 826 // A Block literal expression may be used as the initialization value for 827 // Block variables at global or local static scope. 828 case Expr::BlockExprClass: 829 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 830 } 831 } 832 833 /// Check that this reference or pointer core constant expression is a valid 834 /// value for an address or reference constant expression. Type T should be 835 /// either LValue or CCValue. Return true if we can fold this expression, 836 /// whether or not it's a constant expression. 837 template<typename T> 838 static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E, 839 const T &LVal, APValue &Value, 840 CheckConstantExpressionKind CCEK) { 841 APValue::LValueBase Base = LVal.getLValueBase(); 842 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 843 844 if (!IsGlobalLValue(Base)) { 845 if (Info.getLangOpts().CPlusPlus0x) { 846 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 847 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1) 848 << E->isGLValue() << !Designator.Entries.empty() 849 << !!VD << CCEK << VD; 850 if (VD) 851 Info.Note(VD->getLocation(), diag::note_declared_at); 852 else 853 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(), 854 diag::note_constexpr_temporary_here); 855 } else { 856 Info.Diag(E->getExprLoc()); 857 } 858 // Don't allow references to temporaries to escape. 859 return false; 860 } 861 862 bool IsReferenceType = E->isGLValue(); 863 864 if (Designator.Invalid) { 865 // This is not a core constant expression. An appropriate diagnostic will 866 // have already been produced. 867 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(), 868 APValue::NoLValuePath()); 869 return true; 870 } 871 872 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(), 873 Designator.Entries, Designator.IsOnePastTheEnd); 874 875 // Allow address constant expressions to be past-the-end pointers. This is 876 // an extension: the standard requires them to point to an object. 877 if (!IsReferenceType) 878 return true; 879 880 // A reference constant expression must refer to an object. 881 if (!Base) { 882 // FIXME: diagnostic 883 Info.CCEDiag(E->getExprLoc()); 884 return true; 885 } 886 887 // Does this refer one past the end of some object? 888 if (Designator.isOnePastTheEnd()) { 889 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 890 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1) 891 << !Designator.Entries.empty() << !!VD << VD; 892 if (VD) 893 Info.Note(VD->getLocation(), diag::note_declared_at); 894 else 895 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(), 896 diag::note_constexpr_temporary_here); 897 } 898 899 return true; 900 } 901 902 /// Check that this core constant expression is of literal type, and if not, 903 /// produce an appropriate diagnostic. 904 static bool CheckLiteralType(EvalInfo &Info, const Expr *E) { 905 if (!E->isRValue() || E->getType()->isLiteralType()) 906 return true; 907 908 // Prvalue constant expressions must be of literal types. 909 if (Info.getLangOpts().CPlusPlus0x) 910 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) 911 << E->getType(); 912 else 913 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 914 return false; 915 } 916 917 /// Check that this core constant expression value is a valid value for a 918 /// constant expression, and if it is, produce the corresponding constant value. 919 /// If not, report an appropriate diagnostic. Does not check that the expression 920 /// is of literal type. 921 static bool CheckConstantExpression(EvalInfo &Info, const Expr *E, 922 const CCValue &CCValue, APValue &Value, 923 CheckConstantExpressionKind CCEK 924 = CCEK_Constant) { 925 if (!CCValue.isLValue()) { 926 Value = CCValue; 927 return true; 928 } 929 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK); 930 } 931 932 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 933 return LVal.Base.dyn_cast<const ValueDecl*>(); 934 } 935 936 static bool IsLiteralLValue(const LValue &Value) { 937 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame; 938 } 939 940 static bool IsWeakLValue(const LValue &Value) { 941 const ValueDecl *Decl = GetLValueBaseDecl(Value); 942 return Decl && Decl->isWeak(); 943 } 944 945 static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) { 946 // A null base expression indicates a null pointer. These are always 947 // evaluatable, and they are false unless the offset is zero. 948 if (!Value.getLValueBase()) { 949 Result = !Value.getLValueOffset().isZero(); 950 return true; 951 } 952 953 // Require the base expression to be a global l-value. 954 // FIXME: C++11 requires such conversions. Remove this check. 955 if (!IsGlobalLValue(Value.getLValueBase())) return false; 956 957 // We have a non-null base. These are generally known to be true, but if it's 958 // a weak declaration it can be null at runtime. 959 Result = true; 960 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 961 return !Decl || !Decl->isWeak(); 962 } 963 964 static bool HandleConversionToBool(const CCValue &Val, bool &Result) { 965 switch (Val.getKind()) { 966 case APValue::Uninitialized: 967 return false; 968 case APValue::Int: 969 Result = Val.getInt().getBoolValue(); 970 return true; 971 case APValue::Float: 972 Result = !Val.getFloat().isZero(); 973 return true; 974 case APValue::ComplexInt: 975 Result = Val.getComplexIntReal().getBoolValue() || 976 Val.getComplexIntImag().getBoolValue(); 977 return true; 978 case APValue::ComplexFloat: 979 Result = !Val.getComplexFloatReal().isZero() || 980 !Val.getComplexFloatImag().isZero(); 981 return true; 982 case APValue::LValue: 983 return EvalPointerValueAsBool(Val, Result); 984 case APValue::MemberPointer: 985 Result = Val.getMemberPointerDecl(); 986 return true; 987 case APValue::Vector: 988 case APValue::Array: 989 case APValue::Struct: 990 case APValue::Union: 991 case APValue::AddrLabelDiff: 992 return false; 993 } 994 995 llvm_unreachable("unknown APValue kind"); 996 } 997 998 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 999 EvalInfo &Info) { 1000 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 1001 CCValue Val; 1002 if (!Evaluate(Val, Info, E)) 1003 return false; 1004 return HandleConversionToBool(Val, Result); 1005 } 1006 1007 template<typename T> 1008 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 1009 const T &SrcValue, QualType DestType) { 1010 llvm::SmallVector<char, 32> Buffer; 1011 SrcValue.toString(Buffer); 1012 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow) 1013 << StringRef(Buffer.data(), Buffer.size()) << DestType; 1014 return false; 1015 } 1016 1017 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 1018 QualType SrcType, const APFloat &Value, 1019 QualType DestType, APSInt &Result) { 1020 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 1021 // Determine whether we are converting to unsigned or signed. 1022 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 1023 1024 Result = APSInt(DestWidth, !DestSigned); 1025 bool ignored; 1026 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 1027 & APFloat::opInvalidOp) 1028 return HandleOverflow(Info, E, Value, DestType); 1029 return true; 1030 } 1031 1032 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 1033 QualType SrcType, QualType DestType, 1034 APFloat &Result) { 1035 APFloat Value = Result; 1036 bool ignored; 1037 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 1038 APFloat::rmNearestTiesToEven, &ignored) 1039 & APFloat::opOverflow) 1040 return HandleOverflow(Info, E, Value, DestType); 1041 return true; 1042 } 1043 1044 static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType, 1045 APSInt &Value, const ASTContext &Ctx) { 1046 unsigned DestWidth = Ctx.getIntWidth(DestType); 1047 APSInt Result = Value; 1048 // Figure out if this is a truncate, extend or noop cast. 1049 // If the input is signed, do a sign extend, noop, or truncate. 1050 Result = Result.extOrTrunc(DestWidth); 1051 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 1052 return Result; 1053 } 1054 1055 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 1056 QualType SrcType, const APSInt &Value, 1057 QualType DestType, APFloat &Result) { 1058 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 1059 if (Result.convertFromAPInt(Value, Value.isSigned(), 1060 APFloat::rmNearestTiesToEven) 1061 & APFloat::opOverflow) 1062 return HandleOverflow(Info, E, Value, DestType); 1063 return true; 1064 } 1065 1066 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 1067 llvm::APInt &Res) { 1068 CCValue SVal; 1069 if (!Evaluate(SVal, Info, E)) 1070 return false; 1071 if (SVal.isInt()) { 1072 Res = SVal.getInt(); 1073 return true; 1074 } 1075 if (SVal.isFloat()) { 1076 Res = SVal.getFloat().bitcastToAPInt(); 1077 return true; 1078 } 1079 if (SVal.isVector()) { 1080 QualType VecTy = E->getType(); 1081 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 1082 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 1083 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 1084 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 1085 Res = llvm::APInt::getNullValue(VecSize); 1086 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 1087 APValue &Elt = SVal.getVectorElt(i); 1088 llvm::APInt EltAsInt; 1089 if (Elt.isInt()) { 1090 EltAsInt = Elt.getInt(); 1091 } else if (Elt.isFloat()) { 1092 EltAsInt = Elt.getFloat().bitcastToAPInt(); 1093 } else { 1094 // Don't try to handle vectors of anything other than int or float 1095 // (not sure if it's possible to hit this case). 1096 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 1097 return false; 1098 } 1099 unsigned BaseEltSize = EltAsInt.getBitWidth(); 1100 if (BigEndian) 1101 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 1102 else 1103 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 1104 } 1105 return true; 1106 } 1107 // Give up if the input isn't an int, float, or vector. For example, we 1108 // reject "(v4i16)(intptr_t)&a". 1109 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 1110 return false; 1111 } 1112 1113 /// Cast an lvalue referring to a base subobject to a derived class, by 1114 /// truncating the lvalue's path to the given length. 1115 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 1116 const RecordDecl *TruncatedType, 1117 unsigned TruncatedElements) { 1118 SubobjectDesignator &D = Result.Designator; 1119 1120 // Check we actually point to a derived class object. 1121 if (TruncatedElements == D.Entries.size()) 1122 return true; 1123 assert(TruncatedElements >= D.MostDerivedPathLength && 1124 "not casting to a derived class"); 1125 if (!Result.checkSubobject(Info, E, CSK_Derived)) 1126 return false; 1127 1128 // Truncate the path to the subobject, and remove any derived-to-base offsets. 1129 const RecordDecl *RD = TruncatedType; 1130 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 1131 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 1132 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 1133 if (isVirtualBaseClass(D.Entries[I])) 1134 Result.Offset -= Layout.getVBaseClassOffset(Base); 1135 else 1136 Result.Offset -= Layout.getBaseClassOffset(Base); 1137 RD = Base; 1138 } 1139 D.Entries.resize(TruncatedElements); 1140 return true; 1141 } 1142 1143 static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 1144 const CXXRecordDecl *Derived, 1145 const CXXRecordDecl *Base, 1146 const ASTRecordLayout *RL = 0) { 1147 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived); 1148 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 1149 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 1150 } 1151 1152 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 1153 const CXXRecordDecl *DerivedDecl, 1154 const CXXBaseSpecifier *Base) { 1155 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 1156 1157 if (!Base->isVirtual()) { 1158 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 1159 return true; 1160 } 1161 1162 SubobjectDesignator &D = Obj.Designator; 1163 if (D.Invalid) 1164 return false; 1165 1166 // Extract most-derived object and corresponding type. 1167 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 1168 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 1169 return false; 1170 1171 // Find the virtual base class. 1172 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 1173 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 1174 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 1175 return true; 1176 } 1177 1178 /// Update LVal to refer to the given field, which must be a member of the type 1179 /// currently described by LVal. 1180 static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 1181 const FieldDecl *FD, 1182 const ASTRecordLayout *RL = 0) { 1183 if (!RL) 1184 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 1185 1186 unsigned I = FD->getFieldIndex(); 1187 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)); 1188 LVal.addDecl(Info, E, FD); 1189 } 1190 1191 /// Get the size of the given type in char units. 1192 static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) { 1193 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 1194 // extension. 1195 if (Type->isVoidType() || Type->isFunctionType()) { 1196 Size = CharUnits::One(); 1197 return true; 1198 } 1199 1200 if (!Type->isConstantSizeType()) { 1201 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 1202 // FIXME: Diagnostic. 1203 return false; 1204 } 1205 1206 Size = Info.Ctx.getTypeSizeInChars(Type); 1207 return true; 1208 } 1209 1210 /// Update a pointer value to model pointer arithmetic. 1211 /// \param Info - Information about the ongoing evaluation. 1212 /// \param E - The expression being evaluated, for diagnostic purposes. 1213 /// \param LVal - The pointer value to be updated. 1214 /// \param EltTy - The pointee type represented by LVal. 1215 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 1216 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 1217 LValue &LVal, QualType EltTy, 1218 int64_t Adjustment) { 1219 CharUnits SizeOfPointee; 1220 if (!HandleSizeof(Info, EltTy, SizeOfPointee)) 1221 return false; 1222 1223 // Compute the new offset in the appropriate width. 1224 LVal.Offset += Adjustment * SizeOfPointee; 1225 LVal.adjustIndex(Info, E, Adjustment); 1226 return true; 1227 } 1228 1229 /// Try to evaluate the initializer for a variable declaration. 1230 static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E, 1231 const VarDecl *VD, 1232 CallStackFrame *Frame, CCValue &Result) { 1233 // If this is a parameter to an active constexpr function call, perform 1234 // argument substitution. 1235 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 1236 if (!Frame || !Frame->Arguments) { 1237 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 1238 return false; 1239 } 1240 Result = Frame->Arguments[PVD->getFunctionScopeIndex()]; 1241 return true; 1242 } 1243 1244 // Dig out the initializer, and use the declaration which it's attached to. 1245 const Expr *Init = VD->getAnyInitializer(VD); 1246 if (!Init || Init->isValueDependent()) { 1247 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 1248 return false; 1249 } 1250 1251 // If we're currently evaluating the initializer of this declaration, use that 1252 // in-flight value. 1253 if (Info.EvaluatingDecl == VD) { 1254 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue, 1255 CCValue::GlobalValue()); 1256 return !Result.isUninit(); 1257 } 1258 1259 // Never evaluate the initializer of a weak variable. We can't be sure that 1260 // this is the definition which will be used. 1261 if (VD->isWeak()) { 1262 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 1263 return false; 1264 } 1265 1266 // Check that we can fold the initializer. In C++, we will have already done 1267 // this in the cases where it matters for conformance. 1268 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 1269 if (!VD->evaluateValue(Notes)) { 1270 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant, 1271 Notes.size() + 1) << VD; 1272 Info.Note(VD->getLocation(), diag::note_declared_at); 1273 Info.addNotes(Notes); 1274 return false; 1275 } else if (!VD->checkInitIsICE()) { 1276 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant, 1277 Notes.size() + 1) << VD; 1278 Info.Note(VD->getLocation(), diag::note_declared_at); 1279 Info.addNotes(Notes); 1280 } 1281 1282 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue()); 1283 return true; 1284 } 1285 1286 static bool IsConstNonVolatile(QualType T) { 1287 Qualifiers Quals = T.getQualifiers(); 1288 return Quals.hasConst() && !Quals.hasVolatile(); 1289 } 1290 1291 /// Get the base index of the given base class within an APValue representing 1292 /// the given derived class. 1293 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 1294 const CXXRecordDecl *Base) { 1295 Base = Base->getCanonicalDecl(); 1296 unsigned Index = 0; 1297 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 1298 E = Derived->bases_end(); I != E; ++I, ++Index) { 1299 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 1300 return Index; 1301 } 1302 1303 llvm_unreachable("base class missing from derived class's bases list"); 1304 } 1305 1306 /// Extract the designated sub-object of an rvalue. 1307 static bool ExtractSubobject(EvalInfo &Info, const Expr *E, 1308 CCValue &Obj, QualType ObjType, 1309 const SubobjectDesignator &Sub, QualType SubType) { 1310 if (Sub.Invalid) 1311 // A diagnostic will have already been produced. 1312 return false; 1313 if (Sub.isOnePastTheEnd()) { 1314 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ? 1315 (unsigned)diag::note_constexpr_read_past_end : 1316 (unsigned)diag::note_invalid_subexpr_in_const_expr); 1317 return false; 1318 } 1319 if (Sub.Entries.empty()) 1320 return true; 1321 1322 assert(!Obj.isLValue() && "extracting subobject of lvalue"); 1323 const APValue *O = &Obj; 1324 // Walk the designator's path to find the subobject. 1325 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) { 1326 if (ObjType->isArrayType()) { 1327 // Next subobject is an array element. 1328 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 1329 assert(CAT && "vla in literal type?"); 1330 uint64_t Index = Sub.Entries[I].ArrayIndex; 1331 if (CAT->getSize().ule(Index)) { 1332 // Note, it should not be possible to form a pointer with a valid 1333 // designator which points more than one past the end of the array. 1334 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ? 1335 (unsigned)diag::note_constexpr_read_past_end : 1336 (unsigned)diag::note_invalid_subexpr_in_const_expr); 1337 return false; 1338 } 1339 if (O->getArrayInitializedElts() > Index) 1340 O = &O->getArrayInitializedElt(Index); 1341 else 1342 O = &O->getArrayFiller(); 1343 ObjType = CAT->getElementType(); 1344 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 1345 // Next subobject is a class, struct or union field. 1346 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 1347 if (RD->isUnion()) { 1348 const FieldDecl *UnionField = O->getUnionField(); 1349 if (!UnionField || 1350 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 1351 Info.Diag(E->getExprLoc(), 1352 diag::note_constexpr_read_inactive_union_member) 1353 << Field << !UnionField << UnionField; 1354 return false; 1355 } 1356 O = &O->getUnionValue(); 1357 } else 1358 O = &O->getStructField(Field->getFieldIndex()); 1359 ObjType = Field->getType(); 1360 1361 if (ObjType.isVolatileQualified()) { 1362 if (Info.getLangOpts().CPlusPlus) { 1363 // FIXME: Include a description of the path to the volatile subobject. 1364 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1) 1365 << 2 << Field; 1366 Info.Note(Field->getLocation(), diag::note_declared_at); 1367 } else { 1368 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 1369 } 1370 return false; 1371 } 1372 } else { 1373 // Next subobject is a base class. 1374 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 1375 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 1376 O = &O->getStructBase(getBaseIndex(Derived, Base)); 1377 ObjType = Info.Ctx.getRecordType(Base); 1378 } 1379 1380 if (O->isUninit()) { 1381 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit); 1382 return false; 1383 } 1384 } 1385 1386 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue()); 1387 return true; 1388 } 1389 1390 /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on 1391 /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions 1392 /// for looking up the glvalue referred to by an entity of reference type. 1393 /// 1394 /// \param Info - Information about the ongoing evaluation. 1395 /// \param Conv - The expression for which we are performing the conversion. 1396 /// Used for diagnostics. 1397 /// \param Type - The type we expect this conversion to produce. 1398 /// \param LVal - The glvalue on which we are attempting to perform this action. 1399 /// \param RVal - The produced value will be placed here. 1400 static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 1401 QualType Type, 1402 const LValue &LVal, CCValue &RVal) { 1403 // In C, an lvalue-to-rvalue conversion is never a constant expression. 1404 if (!Info.getLangOpts().CPlusPlus) 1405 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 1406 1407 if (LVal.Designator.Invalid) 1408 // A diagnostic will have already been produced. 1409 return false; 1410 1411 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 1412 CallStackFrame *Frame = LVal.Frame; 1413 SourceLocation Loc = Conv->getExprLoc(); 1414 1415 if (!LVal.Base) { 1416 // FIXME: Indirection through a null pointer deserves a specific diagnostic. 1417 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr); 1418 return false; 1419 } 1420 1421 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 1422 // is not a constant expression (even if the object is non-volatile). We also 1423 // apply this rule to C++98, in order to conform to the expected 'volatile' 1424 // semantics. 1425 if (Type.isVolatileQualified()) { 1426 if (Info.getLangOpts().CPlusPlus) 1427 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type; 1428 else 1429 Info.Diag(Loc); 1430 return false; 1431 } 1432 1433 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 1434 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 1435 // In C++11, constexpr, non-volatile variables initialized with constant 1436 // expressions are constant expressions too. Inside constexpr functions, 1437 // parameters are constant expressions even if they're non-const. 1438 // In C, such things can also be folded, although they are not ICEs. 1439 const VarDecl *VD = dyn_cast<VarDecl>(D); 1440 if (!VD || VD->isInvalidDecl()) { 1441 Info.Diag(Loc); 1442 return false; 1443 } 1444 1445 // DR1313: If the object is volatile-qualified but the glvalue was not, 1446 // behavior is undefined so the result is not a constant expression. 1447 QualType VT = VD->getType(); 1448 if (VT.isVolatileQualified()) { 1449 if (Info.getLangOpts().CPlusPlus) { 1450 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD; 1451 Info.Note(VD->getLocation(), diag::note_declared_at); 1452 } else { 1453 Info.Diag(Loc); 1454 } 1455 return false; 1456 } 1457 1458 if (!isa<ParmVarDecl>(VD)) { 1459 if (VD->isConstexpr()) { 1460 // OK, we can read this variable. 1461 } else if (VT->isIntegralOrEnumerationType()) { 1462 if (!VT.isConstQualified()) { 1463 if (Info.getLangOpts().CPlusPlus) { 1464 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD; 1465 Info.Note(VD->getLocation(), diag::note_declared_at); 1466 } else { 1467 Info.Diag(Loc); 1468 } 1469 return false; 1470 } 1471 } else if (VT->isFloatingType() && VT.isConstQualified()) { 1472 // We support folding of const floating-point types, in order to make 1473 // static const data members of such types (supported as an extension) 1474 // more useful. 1475 if (Info.getLangOpts().CPlusPlus0x) { 1476 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 1477 Info.Note(VD->getLocation(), diag::note_declared_at); 1478 } else { 1479 Info.CCEDiag(Loc); 1480 } 1481 } else { 1482 // FIXME: Allow folding of values of any literal type in all languages. 1483 if (Info.getLangOpts().CPlusPlus0x) { 1484 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 1485 Info.Note(VD->getLocation(), diag::note_declared_at); 1486 } else { 1487 Info.Diag(Loc); 1488 } 1489 return false; 1490 } 1491 } 1492 1493 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal)) 1494 return false; 1495 1496 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue()) 1497 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type); 1498 1499 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue 1500 // conversion. This happens when the declaration and the lvalue should be 1501 // considered synonymous, for instance when initializing an array of char 1502 // from a string literal. Continue as if the initializer lvalue was the 1503 // value we were originally given. 1504 assert(RVal.getLValueOffset().isZero() && 1505 "offset for lvalue init of non-reference"); 1506 Base = RVal.getLValueBase().get<const Expr*>(); 1507 Frame = RVal.getLValueFrame(); 1508 } 1509 1510 // Volatile temporary objects cannot be read in constant expressions. 1511 if (Base->getType().isVolatileQualified()) { 1512 if (Info.getLangOpts().CPlusPlus) { 1513 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0; 1514 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here); 1515 } else { 1516 Info.Diag(Loc); 1517 } 1518 return false; 1519 } 1520 1521 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant 1522 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) { 1523 const SubobjectDesignator &Designator = LVal.Designator; 1524 if (Designator.Invalid || Designator.Entries.size() != 1) { 1525 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 1526 return false; 1527 } 1528 1529 assert(Type->isIntegerType() && "string element not integer type"); 1530 uint64_t Index = Designator.Entries[0].ArrayIndex; 1531 const ConstantArrayType *CAT = 1532 Info.Ctx.getAsConstantArrayType(S->getType()); 1533 if (Index >= CAT->getSize().getZExtValue()) { 1534 // Note, it should not be possible to form a pointer which points more 1535 // than one past the end of the array without producing a prior const expr 1536 // diagnostic. 1537 Info.Diag(Loc, diag::note_constexpr_read_past_end); 1538 return false; 1539 } 1540 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 1541 Type->isUnsignedIntegerType()); 1542 if (Index < S->getLength()) 1543 Value = S->getCodeUnit(Index); 1544 RVal = CCValue(Value); 1545 return true; 1546 } 1547 1548 if (Frame) { 1549 // If this is a temporary expression with a nontrivial initializer, grab the 1550 // value from the relevant stack frame. 1551 RVal = Frame->Temporaries[Base]; 1552 } else if (const CompoundLiteralExpr *CLE 1553 = dyn_cast<CompoundLiteralExpr>(Base)) { 1554 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 1555 // initializer until now for such expressions. Such an expression can't be 1556 // an ICE in C, so this only matters for fold. 1557 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?"); 1558 if (!Evaluate(RVal, Info, CLE->getInitializer())) 1559 return false; 1560 } else { 1561 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 1562 return false; 1563 } 1564 1565 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator, 1566 Type); 1567 } 1568 1569 /// Build an lvalue for the object argument of a member function call. 1570 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 1571 LValue &This) { 1572 if (Object->getType()->isPointerType()) 1573 return EvaluatePointer(Object, This, Info); 1574 1575 if (Object->isGLValue()) 1576 return EvaluateLValue(Object, This, Info); 1577 1578 if (Object->getType()->isLiteralType()) 1579 return EvaluateTemporary(Object, This, Info); 1580 1581 return false; 1582 } 1583 1584 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 1585 /// lvalue referring to the result. 1586 /// 1587 /// \param Info - Information about the ongoing evaluation. 1588 /// \param BO - The member pointer access operation. 1589 /// \param LV - Filled in with a reference to the resulting object. 1590 /// \param IncludeMember - Specifies whether the member itself is included in 1591 /// the resulting LValue subobject designator. This is not possible when 1592 /// creating a bound member function. 1593 /// \return The field or method declaration to which the member pointer refers, 1594 /// or 0 if evaluation fails. 1595 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 1596 const BinaryOperator *BO, 1597 LValue &LV, 1598 bool IncludeMember = true) { 1599 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 1600 1601 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) 1602 return 0; 1603 1604 MemberPtr MemPtr; 1605 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info)) 1606 return 0; 1607 1608 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 1609 // member value, the behavior is undefined. 1610 if (!MemPtr.getDecl()) 1611 return 0; 1612 1613 if (MemPtr.isDerivedMember()) { 1614 // This is a member of some derived class. Truncate LV appropriately. 1615 // The end of the derived-to-base path for the base object must match the 1616 // derived-to-base path for the member pointer. 1617 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 1618 LV.Designator.Entries.size()) 1619 return 0; 1620 unsigned PathLengthToMember = 1621 LV.Designator.Entries.size() - MemPtr.Path.size(); 1622 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 1623 const CXXRecordDecl *LVDecl = getAsBaseClass( 1624 LV.Designator.Entries[PathLengthToMember + I]); 1625 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 1626 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) 1627 return 0; 1628 } 1629 1630 // Truncate the lvalue to the appropriate derived class. 1631 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(), 1632 PathLengthToMember)) 1633 return 0; 1634 } else if (!MemPtr.Path.empty()) { 1635 // Extend the LValue path with the member pointer's path. 1636 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 1637 MemPtr.Path.size() + IncludeMember); 1638 1639 // Walk down to the appropriate base class. 1640 QualType LVType = BO->getLHS()->getType(); 1641 if (const PointerType *PT = LVType->getAs<PointerType>()) 1642 LVType = PT->getPointeeType(); 1643 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 1644 assert(RD && "member pointer access on non-class-type expression"); 1645 // The first class in the path is that of the lvalue. 1646 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 1647 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 1648 HandleLValueDirectBase(Info, BO, LV, RD, Base); 1649 RD = Base; 1650 } 1651 // Finally cast to the class containing the member. 1652 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()); 1653 } 1654 1655 // Add the member. Note that we cannot build bound member functions here. 1656 if (IncludeMember) { 1657 // FIXME: Deal with IndirectFieldDecls. 1658 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()); 1659 if (!FD) return 0; 1660 HandleLValueMember(Info, BO, LV, FD); 1661 } 1662 1663 return MemPtr.getDecl(); 1664 } 1665 1666 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 1667 /// the provided lvalue, which currently refers to the base object. 1668 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 1669 LValue &Result) { 1670 SubobjectDesignator &D = Result.Designator; 1671 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 1672 return false; 1673 1674 QualType TargetQT = E->getType(); 1675 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 1676 TargetQT = PT->getPointeeType(); 1677 1678 // Check this cast lands within the final derived-to-base subobject path. 1679 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 1680 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast) 1681 << D.MostDerivedType << TargetQT; 1682 return false; 1683 } 1684 1685 // Check the type of the final cast. We don't need to check the path, 1686 // since a cast can only be formed if the path is unique. 1687 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 1688 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 1689 const CXXRecordDecl *FinalType; 1690 if (NewEntriesSize == D.MostDerivedPathLength) 1691 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 1692 else 1693 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 1694 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 1695 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast) 1696 << D.MostDerivedType << TargetQT; 1697 return false; 1698 } 1699 1700 // Truncate the lvalue to the appropriate derived class. 1701 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 1702 } 1703 1704 namespace { 1705 enum EvalStmtResult { 1706 /// Evaluation failed. 1707 ESR_Failed, 1708 /// Hit a 'return' statement. 1709 ESR_Returned, 1710 /// Evaluation succeeded. 1711 ESR_Succeeded 1712 }; 1713 } 1714 1715 // Evaluate a statement. 1716 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info, 1717 const Stmt *S) { 1718 switch (S->getStmtClass()) { 1719 default: 1720 return ESR_Failed; 1721 1722 case Stmt::NullStmtClass: 1723 case Stmt::DeclStmtClass: 1724 return ESR_Succeeded; 1725 1726 case Stmt::ReturnStmtClass: { 1727 CCValue CCResult; 1728 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 1729 if (!Evaluate(CCResult, Info, RetExpr) || 1730 !CheckConstantExpression(Info, RetExpr, CCResult, Result, 1731 CCEK_ReturnValue)) 1732 return ESR_Failed; 1733 return ESR_Returned; 1734 } 1735 1736 case Stmt::CompoundStmtClass: { 1737 const CompoundStmt *CS = cast<CompoundStmt>(S); 1738 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 1739 BE = CS->body_end(); BI != BE; ++BI) { 1740 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 1741 if (ESR != ESR_Succeeded) 1742 return ESR; 1743 } 1744 return ESR_Succeeded; 1745 } 1746 } 1747 } 1748 1749 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 1750 /// default constructor. If so, we'll fold it whether or not it's marked as 1751 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 1752 /// so we need special handling. 1753 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 1754 const CXXConstructorDecl *CD, 1755 bool IsValueInitialization) { 1756 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 1757 return false; 1758 1759 // Value-initialization does not call a trivial default constructor, so such a 1760 // call is a core constant expression whether or not the constructor is 1761 // constexpr. 1762 if (!CD->isConstexpr() && !IsValueInitialization) { 1763 if (Info.getLangOpts().CPlusPlus0x) { 1764 // FIXME: If DiagDecl is an implicitly-declared special member function, 1765 // we should be much more explicit about why it's not constexpr. 1766 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 1767 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 1768 Info.Note(CD->getLocation(), diag::note_declared_at); 1769 } else { 1770 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 1771 } 1772 } 1773 return true; 1774 } 1775 1776 /// CheckConstexprFunction - Check that a function can be called in a constant 1777 /// expression. 1778 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 1779 const FunctionDecl *Declaration, 1780 const FunctionDecl *Definition) { 1781 // Can we evaluate this function call? 1782 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl()) 1783 return true; 1784 1785 if (Info.getLangOpts().CPlusPlus0x) { 1786 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 1787 // FIXME: If DiagDecl is an implicitly-declared special member function, we 1788 // should be much more explicit about why it's not constexpr. 1789 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1) 1790 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl) 1791 << DiagDecl; 1792 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 1793 } else { 1794 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 1795 } 1796 return false; 1797 } 1798 1799 namespace { 1800 typedef SmallVector<CCValue, 8> ArgVector; 1801 } 1802 1803 /// EvaluateArgs - Evaluate the arguments to a function call. 1804 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 1805 EvalInfo &Info) { 1806 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 1807 I != E; ++I) 1808 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) 1809 return false; 1810 return true; 1811 } 1812 1813 /// Evaluate a function call. 1814 static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee, 1815 const LValue *This, 1816 ArrayRef<const Expr*> Args, const Stmt *Body, 1817 EvalInfo &Info, APValue &Result) { 1818 if (!Info.CheckCallLimit(CallExpr->getExprLoc())) 1819 return false; 1820 1821 ArgVector ArgValues(Args.size()); 1822 if (!EvaluateArgs(Args, ArgValues, Info)) 1823 return false; 1824 1825 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This, 1826 ArgValues.data()); 1827 return EvaluateStmt(Result, Info, Body) == ESR_Returned; 1828 } 1829 1830 /// Evaluate a constructor call. 1831 static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This, 1832 ArrayRef<const Expr*> Args, 1833 const CXXConstructorDecl *Definition, 1834 EvalInfo &Info, APValue &Result) { 1835 if (!Info.CheckCallLimit(CallExpr->getExprLoc())) 1836 return false; 1837 1838 ArgVector ArgValues(Args.size()); 1839 if (!EvaluateArgs(Args, ArgValues, Info)) 1840 return false; 1841 1842 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition, 1843 &This, ArgValues.data()); 1844 1845 // If it's a delegating constructor, just delegate. 1846 if (Definition->isDelegatingConstructor()) { 1847 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 1848 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit()); 1849 } 1850 1851 // For a trivial copy or move constructor, perform an APValue copy. This is 1852 // essential for unions, where the operations performed by the constructor 1853 // cannot be represented by ctor-initializers. 1854 const CXXRecordDecl *RD = Definition->getParent(); 1855 if (Definition->isDefaulted() && 1856 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) || 1857 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) { 1858 LValue RHS; 1859 RHS.setFrom(ArgValues[0]); 1860 CCValue Value; 1861 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 1862 RHS, Value) && 1863 CheckConstantExpression(Info, CallExpr, Value, Result); 1864 } 1865 1866 // Reserve space for the struct members. 1867 if (!RD->isUnion() && Result.isUninit()) 1868 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 1869 std::distance(RD->field_begin(), RD->field_end())); 1870 1871 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 1872 1873 unsigned BasesSeen = 0; 1874 #ifndef NDEBUG 1875 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 1876 #endif 1877 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(), 1878 E = Definition->init_end(); I != E; ++I) { 1879 if ((*I)->isBaseInitializer()) { 1880 QualType BaseType((*I)->getBaseClass(), 0); 1881 #ifndef NDEBUG 1882 // Non-virtual base classes are initialized in the order in the class 1883 // definition. We cannot have a virtual base class for a literal type. 1884 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 1885 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 1886 "base class initializers not in expected order"); 1887 ++BaseIt; 1888 #endif 1889 LValue Subobject = This; 1890 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD, 1891 BaseType->getAsCXXRecordDecl(), &Layout); 1892 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info, 1893 Subobject, (*I)->getInit())) 1894 return false; 1895 } else if (FieldDecl *FD = (*I)->getMember()) { 1896 LValue Subobject = This; 1897 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout); 1898 if (RD->isUnion()) { 1899 Result = APValue(FD); 1900 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject, 1901 (*I)->getInit(), CCEK_MemberInit)) 1902 return false; 1903 } else if (!EvaluateConstantExpression( 1904 Result.getStructField(FD->getFieldIndex()), 1905 Info, Subobject, (*I)->getInit(), CCEK_MemberInit)) 1906 return false; 1907 } else { 1908 // FIXME: handle indirect field initializers 1909 Info.Diag((*I)->getInit()->getExprLoc(), 1910 diag::note_invalid_subexpr_in_const_expr); 1911 return false; 1912 } 1913 } 1914 1915 return true; 1916 } 1917 1918 namespace { 1919 class HasSideEffect 1920 : public ConstStmtVisitor<HasSideEffect, bool> { 1921 const ASTContext &Ctx; 1922 public: 1923 1924 HasSideEffect(const ASTContext &C) : Ctx(C) {} 1925 1926 // Unhandled nodes conservatively default to having side effects. 1927 bool VisitStmt(const Stmt *S) { 1928 return true; 1929 } 1930 1931 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); } 1932 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) { 1933 return Visit(E->getResultExpr()); 1934 } 1935 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1936 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 1937 return true; 1938 return false; 1939 } 1940 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) { 1941 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 1942 return true; 1943 return false; 1944 } 1945 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) { 1946 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 1947 return true; 1948 return false; 1949 } 1950 1951 // We don't want to evaluate BlockExprs multiple times, as they generate 1952 // a ton of code. 1953 bool VisitBlockExpr(const BlockExpr *E) { return true; } 1954 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; } 1955 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) 1956 { return Visit(E->getInitializer()); } 1957 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); } 1958 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; } 1959 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; } 1960 bool VisitStringLiteral(const StringLiteral *E) { return false; } 1961 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; } 1962 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) 1963 { return false; } 1964 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E) 1965 { return Visit(E->getLHS()) || Visit(E->getRHS()); } 1966 bool VisitChooseExpr(const ChooseExpr *E) 1967 { return Visit(E->getChosenSubExpr(Ctx)); } 1968 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); } 1969 bool VisitBinAssign(const BinaryOperator *E) { return true; } 1970 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; } 1971 bool VisitBinaryOperator(const BinaryOperator *E) 1972 { return Visit(E->getLHS()) || Visit(E->getRHS()); } 1973 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; } 1974 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; } 1975 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; } 1976 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; } 1977 bool VisitUnaryDeref(const UnaryOperator *E) { 1978 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified()) 1979 return true; 1980 return Visit(E->getSubExpr()); 1981 } 1982 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); } 1983 1984 // Has side effects if any element does. 1985 bool VisitInitListExpr(const InitListExpr *E) { 1986 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i) 1987 if (Visit(E->getInit(i))) return true; 1988 if (const Expr *filler = E->getArrayFiller()) 1989 return Visit(filler); 1990 return false; 1991 } 1992 1993 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; } 1994 }; 1995 1996 class OpaqueValueEvaluation { 1997 EvalInfo &info; 1998 OpaqueValueExpr *opaqueValue; 1999 2000 public: 2001 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue, 2002 Expr *value) 2003 : info(info), opaqueValue(opaqueValue) { 2004 2005 // If evaluation fails, fail immediately. 2006 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) { 2007 this->opaqueValue = 0; 2008 return; 2009 } 2010 } 2011 2012 bool hasError() const { return opaqueValue == 0; } 2013 2014 ~OpaqueValueEvaluation() { 2015 // FIXME: This will not work for recursive constexpr functions using opaque 2016 // values. Restore the former value. 2017 if (opaqueValue) info.OpaqueValues.erase(opaqueValue); 2018 } 2019 }; 2020 2021 } // end anonymous namespace 2022 2023 //===----------------------------------------------------------------------===// 2024 // Generic Evaluation 2025 //===----------------------------------------------------------------------===// 2026 namespace { 2027 2028 // FIXME: RetTy is always bool. Remove it. 2029 template <class Derived, typename RetTy=bool> 2030 class ExprEvaluatorBase 2031 : public ConstStmtVisitor<Derived, RetTy> { 2032 private: 2033 RetTy DerivedSuccess(const CCValue &V, const Expr *E) { 2034 return static_cast<Derived*>(this)->Success(V, E); 2035 } 2036 RetTy DerivedZeroInitialization(const Expr *E) { 2037 return static_cast<Derived*>(this)->ZeroInitialization(E); 2038 } 2039 2040 protected: 2041 EvalInfo &Info; 2042 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy; 2043 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 2044 2045 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 2046 return Info.CCEDiag(E->getExprLoc(), D); 2047 } 2048 2049 /// Report an evaluation error. This should only be called when an error is 2050 /// first discovered. When propagating an error, just return false. 2051 bool Error(const Expr *E, diag::kind D) { 2052 Info.Diag(E->getExprLoc(), D); 2053 return false; 2054 } 2055 bool Error(const Expr *E) { 2056 return Error(E, diag::note_invalid_subexpr_in_const_expr); 2057 } 2058 2059 RetTy ZeroInitialization(const Expr *E) { return Error(E); } 2060 2061 public: 2062 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 2063 2064 RetTy VisitStmt(const Stmt *) { 2065 llvm_unreachable("Expression evaluator should not be called on stmts"); 2066 } 2067 RetTy VisitExpr(const Expr *E) { 2068 return Error(E); 2069 } 2070 2071 RetTy VisitParenExpr(const ParenExpr *E) 2072 { return StmtVisitorTy::Visit(E->getSubExpr()); } 2073 RetTy VisitUnaryExtension(const UnaryOperator *E) 2074 { return StmtVisitorTy::Visit(E->getSubExpr()); } 2075 RetTy VisitUnaryPlus(const UnaryOperator *E) 2076 { return StmtVisitorTy::Visit(E->getSubExpr()); } 2077 RetTy VisitChooseExpr(const ChooseExpr *E) 2078 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); } 2079 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E) 2080 { return StmtVisitorTy::Visit(E->getResultExpr()); } 2081 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 2082 { return StmtVisitorTy::Visit(E->getReplacement()); } 2083 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) 2084 { return StmtVisitorTy::Visit(E->getExpr()); } 2085 // We cannot create any objects for which cleanups are required, so there is 2086 // nothing to do here; all cleanups must come from unevaluated subexpressions. 2087 RetTy VisitExprWithCleanups(const ExprWithCleanups *E) 2088 { return StmtVisitorTy::Visit(E->getSubExpr()); } 2089 2090 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 2091 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 2092 return static_cast<Derived*>(this)->VisitCastExpr(E); 2093 } 2094 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 2095 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 2096 return static_cast<Derived*>(this)->VisitCastExpr(E); 2097 } 2098 2099 RetTy VisitBinaryOperator(const BinaryOperator *E) { 2100 switch (E->getOpcode()) { 2101 default: 2102 return Error(E); 2103 2104 case BO_Comma: 2105 VisitIgnoredValue(E->getLHS()); 2106 return StmtVisitorTy::Visit(E->getRHS()); 2107 2108 case BO_PtrMemD: 2109 case BO_PtrMemI: { 2110 LValue Obj; 2111 if (!HandleMemberPointerAccess(Info, E, Obj)) 2112 return false; 2113 CCValue Result; 2114 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 2115 return false; 2116 return DerivedSuccess(Result, E); 2117 } 2118 } 2119 } 2120 2121 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 2122 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon()); 2123 if (opaque.hasError()) 2124 return false; 2125 2126 bool cond; 2127 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info)) 2128 return false; 2129 2130 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr()); 2131 } 2132 2133 RetTy VisitConditionalOperator(const ConditionalOperator *E) { 2134 bool BoolResult; 2135 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) 2136 return false; 2137 2138 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 2139 return StmtVisitorTy::Visit(EvalExpr); 2140 } 2141 2142 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 2143 const CCValue *Value = Info.getOpaqueValue(E); 2144 if (!Value) { 2145 const Expr *Source = E->getSourceExpr(); 2146 if (!Source) 2147 return Error(E); 2148 if (Source == E) { // sanity checking. 2149 assert(0 && "OpaqueValueExpr recursively refers to itself"); 2150 return Error(E); 2151 } 2152 return StmtVisitorTy::Visit(Source); 2153 } 2154 return DerivedSuccess(*Value, E); 2155 } 2156 2157 RetTy VisitCallExpr(const CallExpr *E) { 2158 const Expr *Callee = E->getCallee()->IgnoreParens(); 2159 QualType CalleeType = Callee->getType(); 2160 2161 const FunctionDecl *FD = 0; 2162 LValue *This = 0, ThisVal; 2163 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs()); 2164 2165 // Extract function decl and 'this' pointer from the callee. 2166 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 2167 const ValueDecl *Member = 0; 2168 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 2169 // Explicit bound member calls, such as x.f() or p->g(); 2170 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 2171 return false; 2172 Member = ME->getMemberDecl(); 2173 This = &ThisVal; 2174 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 2175 // Indirect bound member calls ('.*' or '->*'). 2176 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false); 2177 if (!Member) return false; 2178 This = &ThisVal; 2179 } else 2180 return Error(Callee); 2181 2182 FD = dyn_cast<FunctionDecl>(Member); 2183 if (!FD) 2184 return Error(Callee); 2185 } else if (CalleeType->isFunctionPointerType()) { 2186 LValue Call; 2187 if (!EvaluatePointer(Callee, Call, Info)) 2188 return false; 2189 2190 if (!Call.getLValueOffset().isZero()) 2191 return Error(Callee); 2192 FD = dyn_cast_or_null<FunctionDecl>( 2193 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 2194 if (!FD) 2195 return Error(Callee); 2196 2197 // Overloaded operator calls to member functions are represented as normal 2198 // calls with '*this' as the first argument. 2199 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 2200 if (MD && !MD->isStatic()) { 2201 // FIXME: When selecting an implicit conversion for an overloaded 2202 // operator delete, we sometimes try to evaluate calls to conversion 2203 // operators without a 'this' parameter! 2204 if (Args.empty()) 2205 return Error(E); 2206 2207 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 2208 return false; 2209 This = &ThisVal; 2210 Args = Args.slice(1); 2211 } 2212 2213 // Don't call function pointers which have been cast to some other type. 2214 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType())) 2215 return Error(E); 2216 } else 2217 return Error(E); 2218 2219 const FunctionDecl *Definition = 0; 2220 Stmt *Body = FD->getBody(Definition); 2221 APValue Result; 2222 2223 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) || 2224 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result)) 2225 return false; 2226 2227 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E); 2228 } 2229 2230 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 2231 return StmtVisitorTy::Visit(E->getInitializer()); 2232 } 2233 RetTy VisitInitListExpr(const InitListExpr *E) { 2234 if (E->getNumInits() == 0) 2235 return DerivedZeroInitialization(E); 2236 if (E->getNumInits() == 1) 2237 return StmtVisitorTy::Visit(E->getInit(0)); 2238 return Error(E); 2239 } 2240 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 2241 return DerivedZeroInitialization(E); 2242 } 2243 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 2244 return DerivedZeroInitialization(E); 2245 } 2246 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 2247 return DerivedZeroInitialization(E); 2248 } 2249 2250 /// A member expression where the object is a prvalue is itself a prvalue. 2251 RetTy VisitMemberExpr(const MemberExpr *E) { 2252 assert(!E->isArrow() && "missing call to bound member function?"); 2253 2254 CCValue Val; 2255 if (!Evaluate(Val, Info, E->getBase())) 2256 return false; 2257 2258 QualType BaseTy = E->getBase()->getType(); 2259 2260 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 2261 if (!FD) return Error(E); 2262 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 2263 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 2264 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 2265 2266 SubobjectDesignator Designator(BaseTy); 2267 Designator.addDeclUnchecked(FD); 2268 2269 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) && 2270 DerivedSuccess(Val, E); 2271 } 2272 2273 RetTy VisitCastExpr(const CastExpr *E) { 2274 switch (E->getCastKind()) { 2275 default: 2276 break; 2277 2278 case CK_AtomicToNonAtomic: 2279 case CK_NonAtomicToAtomic: 2280 case CK_NoOp: 2281 case CK_UserDefinedConversion: 2282 return StmtVisitorTy::Visit(E->getSubExpr()); 2283 2284 case CK_LValueToRValue: { 2285 LValue LVal; 2286 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 2287 return false; 2288 CCValue RVal; 2289 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal)) 2290 return false; 2291 return DerivedSuccess(RVal, E); 2292 } 2293 } 2294 2295 return Error(E); 2296 } 2297 2298 /// Visit a value which is evaluated, but whose value is ignored. 2299 void VisitIgnoredValue(const Expr *E) { 2300 CCValue Scratch; 2301 if (!Evaluate(Scratch, Info, E)) 2302 Info.EvalStatus.HasSideEffects = true; 2303 } 2304 }; 2305 2306 } 2307 2308 //===----------------------------------------------------------------------===// 2309 // Common base class for lvalue and temporary evaluation. 2310 //===----------------------------------------------------------------------===// 2311 namespace { 2312 template<class Derived> 2313 class LValueExprEvaluatorBase 2314 : public ExprEvaluatorBase<Derived, bool> { 2315 protected: 2316 LValue &Result; 2317 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 2318 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy; 2319 2320 bool Success(APValue::LValueBase B) { 2321 Result.set(B); 2322 return true; 2323 } 2324 2325 public: 2326 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) : 2327 ExprEvaluatorBaseTy(Info), Result(Result) {} 2328 2329 bool Success(const CCValue &V, const Expr *E) { 2330 Result.setFrom(V); 2331 return true; 2332 } 2333 2334 bool VisitMemberExpr(const MemberExpr *E) { 2335 // Handle non-static data members. 2336 QualType BaseTy; 2337 if (E->isArrow()) { 2338 if (!EvaluatePointer(E->getBase(), Result, this->Info)) 2339 return false; 2340 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType(); 2341 } else if (E->getBase()->isRValue()) { 2342 assert(E->getBase()->getType()->isRecordType()); 2343 if (!EvaluateTemporary(E->getBase(), Result, this->Info)) 2344 return false; 2345 BaseTy = E->getBase()->getType(); 2346 } else { 2347 if (!this->Visit(E->getBase())) 2348 return false; 2349 BaseTy = E->getBase()->getType(); 2350 } 2351 2352 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 2353 // FIXME: Handle IndirectFieldDecls 2354 if (!FD) return this->Error(E); 2355 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 2356 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 2357 (void)BaseTy; 2358 2359 HandleLValueMember(this->Info, E, Result, FD); 2360 2361 if (FD->getType()->isReferenceType()) { 2362 CCValue RefValue; 2363 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result, 2364 RefValue)) 2365 return false; 2366 return Success(RefValue, E); 2367 } 2368 return true; 2369 } 2370 2371 bool VisitBinaryOperator(const BinaryOperator *E) { 2372 switch (E->getOpcode()) { 2373 default: 2374 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 2375 2376 case BO_PtrMemD: 2377 case BO_PtrMemI: 2378 return HandleMemberPointerAccess(this->Info, E, Result); 2379 } 2380 } 2381 2382 bool VisitCastExpr(const CastExpr *E) { 2383 switch (E->getCastKind()) { 2384 default: 2385 return ExprEvaluatorBaseTy::VisitCastExpr(E); 2386 2387 case CK_DerivedToBase: 2388 case CK_UncheckedDerivedToBase: { 2389 if (!this->Visit(E->getSubExpr())) 2390 return false; 2391 2392 // Now figure out the necessary offset to add to the base LV to get from 2393 // the derived class to the base class. 2394 QualType Type = E->getSubExpr()->getType(); 2395 2396 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2397 PathE = E->path_end(); PathI != PathE; ++PathI) { 2398 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(), 2399 *PathI)) 2400 return false; 2401 Type = (*PathI)->getType(); 2402 } 2403 2404 return true; 2405 } 2406 } 2407 } 2408 }; 2409 } 2410 2411 //===----------------------------------------------------------------------===// 2412 // LValue Evaluation 2413 // 2414 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 2415 // function designators (in C), decl references to void objects (in C), and 2416 // temporaries (if building with -Wno-address-of-temporary). 2417 // 2418 // LValue evaluation produces values comprising a base expression of one of the 2419 // following types: 2420 // - Declarations 2421 // * VarDecl 2422 // * FunctionDecl 2423 // - Literals 2424 // * CompoundLiteralExpr in C 2425 // * StringLiteral 2426 // * CXXTypeidExpr 2427 // * PredefinedExpr 2428 // * ObjCStringLiteralExpr 2429 // * ObjCEncodeExpr 2430 // * AddrLabelExpr 2431 // * BlockExpr 2432 // * CallExpr for a MakeStringConstant builtin 2433 // - Locals and temporaries 2434 // * Any Expr, with a Frame indicating the function in which the temporary was 2435 // evaluated. 2436 // plus an offset in bytes. 2437 //===----------------------------------------------------------------------===// 2438 namespace { 2439 class LValueExprEvaluator 2440 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 2441 public: 2442 LValueExprEvaluator(EvalInfo &Info, LValue &Result) : 2443 LValueExprEvaluatorBaseTy(Info, Result) {} 2444 2445 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 2446 2447 bool VisitDeclRefExpr(const DeclRefExpr *E); 2448 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 2449 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 2450 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 2451 bool VisitMemberExpr(const MemberExpr *E); 2452 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 2453 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 2454 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 2455 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 2456 bool VisitUnaryDeref(const UnaryOperator *E); 2457 2458 bool VisitCastExpr(const CastExpr *E) { 2459 switch (E->getCastKind()) { 2460 default: 2461 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 2462 2463 case CK_LValueBitCast: 2464 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 2465 if (!Visit(E->getSubExpr())) 2466 return false; 2467 Result.Designator.setInvalid(); 2468 return true; 2469 2470 case CK_BaseToDerived: 2471 if (!Visit(E->getSubExpr())) 2472 return false; 2473 return HandleBaseToDerivedCast(Info, E, Result); 2474 } 2475 } 2476 2477 // FIXME: Missing: __real__, __imag__ 2478 2479 }; 2480 } // end anonymous namespace 2481 2482 /// Evaluate an expression as an lvalue. This can be legitimately called on 2483 /// expressions which are not glvalues, in a few cases: 2484 /// * function designators in C, 2485 /// * "extern void" objects, 2486 /// * temporaries, if building with -Wno-address-of-temporary. 2487 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) { 2488 assert((E->isGLValue() || E->getType()->isFunctionType() || 2489 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) && 2490 "can't evaluate expression as an lvalue"); 2491 return LValueExprEvaluator(Info, Result).Visit(E); 2492 } 2493 2494 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 2495 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 2496 return Success(FD); 2497 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 2498 return VisitVarDecl(E, VD); 2499 return Error(E); 2500 } 2501 2502 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 2503 if (!VD->getType()->isReferenceType()) { 2504 if (isa<ParmVarDecl>(VD)) { 2505 Result.set(VD, Info.CurrentCall); 2506 return true; 2507 } 2508 return Success(VD); 2509 } 2510 2511 CCValue V; 2512 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V)) 2513 return false; 2514 return Success(V, E); 2515 } 2516 2517 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 2518 const MaterializeTemporaryExpr *E) { 2519 if (E->GetTemporaryExpr()->isRValue()) { 2520 if (E->getType()->isRecordType()) 2521 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info); 2522 2523 Result.set(E, Info.CurrentCall); 2524 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info, 2525 Result, E->GetTemporaryExpr()); 2526 } 2527 2528 // Materialization of an lvalue temporary occurs when we need to force a copy 2529 // (for instance, if it's a bitfield). 2530 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases. 2531 if (!Visit(E->GetTemporaryExpr())) 2532 return false; 2533 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result, 2534 Info.CurrentCall->Temporaries[E])) 2535 return false; 2536 Result.set(E, Info.CurrentCall); 2537 return true; 2538 } 2539 2540 bool 2541 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 2542 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?"); 2543 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 2544 // only see this when folding in C, so there's no standard to follow here. 2545 return Success(E); 2546 } 2547 2548 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 2549 if (E->isTypeOperand()) 2550 return Success(E); 2551 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl(); 2552 if (RD && RD->isPolymorphic()) { 2553 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic) 2554 << E->getExprOperand()->getType() 2555 << E->getExprOperand()->getSourceRange(); 2556 return false; 2557 } 2558 return Success(E); 2559 } 2560 2561 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 2562 // Handle static data members. 2563 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 2564 VisitIgnoredValue(E->getBase()); 2565 return VisitVarDecl(E, VD); 2566 } 2567 2568 // Handle static member functions. 2569 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 2570 if (MD->isStatic()) { 2571 VisitIgnoredValue(E->getBase()); 2572 return Success(MD); 2573 } 2574 } 2575 2576 // Handle non-static data members. 2577 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 2578 } 2579 2580 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 2581 // FIXME: Deal with vectors as array subscript bases. 2582 if (E->getBase()->getType()->isVectorType()) 2583 return Error(E); 2584 2585 if (!EvaluatePointer(E->getBase(), Result, Info)) 2586 return false; 2587 2588 APSInt Index; 2589 if (!EvaluateInteger(E->getIdx(), Index, Info)) 2590 return false; 2591 int64_t IndexValue 2592 = Index.isSigned() ? Index.getSExtValue() 2593 : static_cast<int64_t>(Index.getZExtValue()); 2594 2595 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue); 2596 } 2597 2598 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 2599 return EvaluatePointer(E->getSubExpr(), Result, Info); 2600 } 2601 2602 //===----------------------------------------------------------------------===// 2603 // Pointer Evaluation 2604 //===----------------------------------------------------------------------===// 2605 2606 namespace { 2607 class PointerExprEvaluator 2608 : public ExprEvaluatorBase<PointerExprEvaluator, bool> { 2609 LValue &Result; 2610 2611 bool Success(const Expr *E) { 2612 Result.set(E); 2613 return true; 2614 } 2615 public: 2616 2617 PointerExprEvaluator(EvalInfo &info, LValue &Result) 2618 : ExprEvaluatorBaseTy(info), Result(Result) {} 2619 2620 bool Success(const CCValue &V, const Expr *E) { 2621 Result.setFrom(V); 2622 return true; 2623 } 2624 bool ZeroInitialization(const Expr *E) { 2625 return Success((Expr*)0); 2626 } 2627 2628 bool VisitBinaryOperator(const BinaryOperator *E); 2629 bool VisitCastExpr(const CastExpr* E); 2630 bool VisitUnaryAddrOf(const UnaryOperator *E); 2631 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 2632 { return Success(E); } 2633 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 2634 { return Success(E); } 2635 bool VisitCallExpr(const CallExpr *E); 2636 bool VisitBlockExpr(const BlockExpr *E) { 2637 if (!E->getBlockDecl()->hasCaptures()) 2638 return Success(E); 2639 return Error(E); 2640 } 2641 bool VisitCXXThisExpr(const CXXThisExpr *E) { 2642 if (!Info.CurrentCall->This) 2643 return Error(E); 2644 Result = *Info.CurrentCall->This; 2645 return true; 2646 } 2647 2648 // FIXME: Missing: @protocol, @selector 2649 }; 2650 } // end anonymous namespace 2651 2652 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) { 2653 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 2654 return PointerExprEvaluator(Info, Result).Visit(E); 2655 } 2656 2657 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 2658 if (E->getOpcode() != BO_Add && 2659 E->getOpcode() != BO_Sub) 2660 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 2661 2662 const Expr *PExp = E->getLHS(); 2663 const Expr *IExp = E->getRHS(); 2664 if (IExp->getType()->isPointerType()) 2665 std::swap(PExp, IExp); 2666 2667 if (!EvaluatePointer(PExp, Result, Info)) 2668 return false; 2669 2670 llvm::APSInt Offset; 2671 if (!EvaluateInteger(IExp, Offset, Info)) 2672 return false; 2673 int64_t AdditionalOffset 2674 = Offset.isSigned() ? Offset.getSExtValue() 2675 : static_cast<int64_t>(Offset.getZExtValue()); 2676 if (E->getOpcode() == BO_Sub) 2677 AdditionalOffset = -AdditionalOffset; 2678 2679 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType(); 2680 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, 2681 AdditionalOffset); 2682 } 2683 2684 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 2685 return EvaluateLValue(E->getSubExpr(), Result, Info); 2686 } 2687 2688 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { 2689 const Expr* SubExpr = E->getSubExpr(); 2690 2691 switch (E->getCastKind()) { 2692 default: 2693 break; 2694 2695 case CK_BitCast: 2696 case CK_CPointerToObjCPointerCast: 2697 case CK_BlockPointerToObjCPointerCast: 2698 case CK_AnyPointerToBlockPointerCast: 2699 if (!Visit(SubExpr)) 2700 return false; 2701 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 2702 // permitted in constant expressions in C++11. Bitcasts from cv void* are 2703 // also static_casts, but we disallow them as a resolution to DR1312. 2704 if (!E->getType()->isVoidPointerType()) { 2705 Result.Designator.setInvalid(); 2706 if (SubExpr->getType()->isVoidPointerType()) 2707 CCEDiag(E, diag::note_constexpr_invalid_cast) 2708 << 3 << SubExpr->getType(); 2709 else 2710 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 2711 } 2712 return true; 2713 2714 case CK_DerivedToBase: 2715 case CK_UncheckedDerivedToBase: { 2716 if (!EvaluatePointer(E->getSubExpr(), Result, Info)) 2717 return false; 2718 if (!Result.Base && Result.Offset.isZero()) 2719 return true; 2720 2721 // Now figure out the necessary offset to add to the base LV to get from 2722 // the derived class to the base class. 2723 QualType Type = 2724 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType(); 2725 2726 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2727 PathE = E->path_end(); PathI != PathE; ++PathI) { 2728 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2729 *PathI)) 2730 return false; 2731 Type = (*PathI)->getType(); 2732 } 2733 2734 return true; 2735 } 2736 2737 case CK_BaseToDerived: 2738 if (!Visit(E->getSubExpr())) 2739 return false; 2740 if (!Result.Base && Result.Offset.isZero()) 2741 return true; 2742 return HandleBaseToDerivedCast(Info, E, Result); 2743 2744 case CK_NullToPointer: 2745 return ZeroInitialization(E); 2746 2747 case CK_IntegralToPointer: { 2748 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 2749 2750 CCValue Value; 2751 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 2752 break; 2753 2754 if (Value.isInt()) { 2755 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 2756 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 2757 Result.Base = (Expr*)0; 2758 Result.Offset = CharUnits::fromQuantity(N); 2759 Result.Frame = 0; 2760 Result.Designator.setInvalid(); 2761 return true; 2762 } else { 2763 // Cast is of an lvalue, no need to change value. 2764 Result.setFrom(Value); 2765 return true; 2766 } 2767 } 2768 case CK_ArrayToPointerDecay: 2769 if (SubExpr->isGLValue()) { 2770 if (!EvaluateLValue(SubExpr, Result, Info)) 2771 return false; 2772 } else { 2773 Result.set(SubExpr, Info.CurrentCall); 2774 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr], 2775 Info, Result, SubExpr)) 2776 return false; 2777 } 2778 // The result is a pointer to the first element of the array. 2779 if (const ConstantArrayType *CAT 2780 = Info.Ctx.getAsConstantArrayType(SubExpr->getType())) 2781 Result.addArray(Info, E, CAT); 2782 else 2783 Result.Designator.setInvalid(); 2784 return true; 2785 2786 case CK_FunctionToPointerDecay: 2787 return EvaluateLValue(SubExpr, Result, Info); 2788 } 2789 2790 return ExprEvaluatorBaseTy::VisitCastExpr(E); 2791 } 2792 2793 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 2794 if (IsStringLiteralCall(E)) 2795 return Success(E); 2796 2797 return ExprEvaluatorBaseTy::VisitCallExpr(E); 2798 } 2799 2800 //===----------------------------------------------------------------------===// 2801 // Member Pointer Evaluation 2802 //===----------------------------------------------------------------------===// 2803 2804 namespace { 2805 class MemberPointerExprEvaluator 2806 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> { 2807 MemberPtr &Result; 2808 2809 bool Success(const ValueDecl *D) { 2810 Result = MemberPtr(D); 2811 return true; 2812 } 2813 public: 2814 2815 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 2816 : ExprEvaluatorBaseTy(Info), Result(Result) {} 2817 2818 bool Success(const CCValue &V, const Expr *E) { 2819 Result.setFrom(V); 2820 return true; 2821 } 2822 bool ZeroInitialization(const Expr *E) { 2823 return Success((const ValueDecl*)0); 2824 } 2825 2826 bool VisitCastExpr(const CastExpr *E); 2827 bool VisitUnaryAddrOf(const UnaryOperator *E); 2828 }; 2829 } // end anonymous namespace 2830 2831 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 2832 EvalInfo &Info) { 2833 assert(E->isRValue() && E->getType()->isMemberPointerType()); 2834 return MemberPointerExprEvaluator(Info, Result).Visit(E); 2835 } 2836 2837 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 2838 switch (E->getCastKind()) { 2839 default: 2840 return ExprEvaluatorBaseTy::VisitCastExpr(E); 2841 2842 case CK_NullToMemberPointer: 2843 return ZeroInitialization(E); 2844 2845 case CK_BaseToDerivedMemberPointer: { 2846 if (!Visit(E->getSubExpr())) 2847 return false; 2848 if (E->path_empty()) 2849 return true; 2850 // Base-to-derived member pointer casts store the path in derived-to-base 2851 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 2852 // the wrong end of the derived->base arc, so stagger the path by one class. 2853 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 2854 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 2855 PathI != PathE; ++PathI) { 2856 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 2857 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 2858 if (!Result.castToDerived(Derived)) 2859 return Error(E); 2860 } 2861 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 2862 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 2863 return Error(E); 2864 return true; 2865 } 2866 2867 case CK_DerivedToBaseMemberPointer: 2868 if (!Visit(E->getSubExpr())) 2869 return false; 2870 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2871 PathE = E->path_end(); PathI != PathE; ++PathI) { 2872 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 2873 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 2874 if (!Result.castToBase(Base)) 2875 return Error(E); 2876 } 2877 return true; 2878 } 2879 } 2880 2881 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 2882 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 2883 // member can be formed. 2884 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 2885 } 2886 2887 //===----------------------------------------------------------------------===// 2888 // Record Evaluation 2889 //===----------------------------------------------------------------------===// 2890 2891 namespace { 2892 class RecordExprEvaluator 2893 : public ExprEvaluatorBase<RecordExprEvaluator, bool> { 2894 const LValue &This; 2895 APValue &Result; 2896 public: 2897 2898 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 2899 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 2900 2901 bool Success(const CCValue &V, const Expr *E) { 2902 return CheckConstantExpression(Info, E, V, Result); 2903 } 2904 bool ZeroInitialization(const Expr *E); 2905 2906 bool VisitCastExpr(const CastExpr *E); 2907 bool VisitInitListExpr(const InitListExpr *E); 2908 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 2909 }; 2910 } 2911 2912 /// Perform zero-initialization on an object of non-union class type. 2913 /// C++11 [dcl.init]p5: 2914 /// To zero-initialize an object or reference of type T means: 2915 /// [...] 2916 /// -- if T is a (possibly cv-qualified) non-union class type, 2917 /// each non-static data member and each base-class subobject is 2918 /// zero-initialized 2919 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 2920 const RecordDecl *RD, 2921 const LValue &This, APValue &Result) { 2922 assert(!RD->isUnion() && "Expected non-union class type"); 2923 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 2924 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 2925 std::distance(RD->field_begin(), RD->field_end())); 2926 2927 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2928 2929 if (CD) { 2930 unsigned Index = 0; 2931 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 2932 End = CD->bases_end(); I != End; ++I, ++Index) { 2933 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 2934 LValue Subobject = This; 2935 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout); 2936 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 2937 Result.getStructBase(Index))) 2938 return false; 2939 } 2940 } 2941 2942 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end(); 2943 I != End; ++I) { 2944 // -- if T is a reference type, no initialization is performed. 2945 if ((*I)->getType()->isReferenceType()) 2946 continue; 2947 2948 LValue Subobject = This; 2949 HandleLValueMember(Info, E, Subobject, *I, &Layout); 2950 2951 ImplicitValueInitExpr VIE((*I)->getType()); 2952 if (!EvaluateConstantExpression( 2953 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE)) 2954 return false; 2955 } 2956 2957 return true; 2958 } 2959 2960 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) { 2961 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 2962 if (RD->isUnion()) { 2963 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 2964 // object's first non-static named data member is zero-initialized 2965 RecordDecl::field_iterator I = RD->field_begin(); 2966 if (I == RD->field_end()) { 2967 Result = APValue((const FieldDecl*)0); 2968 return true; 2969 } 2970 2971 LValue Subobject = This; 2972 HandleLValueMember(Info, E, Subobject, *I); 2973 Result = APValue(*I); 2974 ImplicitValueInitExpr VIE((*I)->getType()); 2975 return EvaluateConstantExpression(Result.getUnionValue(), Info, 2976 Subobject, &VIE); 2977 } 2978 2979 return HandleClassZeroInitialization(Info, E, RD, This, Result); 2980 } 2981 2982 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 2983 switch (E->getCastKind()) { 2984 default: 2985 return ExprEvaluatorBaseTy::VisitCastExpr(E); 2986 2987 case CK_ConstructorConversion: 2988 return Visit(E->getSubExpr()); 2989 2990 case CK_DerivedToBase: 2991 case CK_UncheckedDerivedToBase: { 2992 CCValue DerivedObject; 2993 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 2994 return false; 2995 if (!DerivedObject.isStruct()) 2996 return Error(E->getSubExpr()); 2997 2998 // Derived-to-base rvalue conversion: just slice off the derived part. 2999 APValue *Value = &DerivedObject; 3000 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 3001 for (CastExpr::path_const_iterator PathI = E->path_begin(), 3002 PathE = E->path_end(); PathI != PathE; ++PathI) { 3003 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 3004 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 3005 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 3006 RD = Base; 3007 } 3008 Result = *Value; 3009 return true; 3010 } 3011 } 3012 } 3013 3014 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 3015 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 3016 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 3017 3018 if (RD->isUnion()) { 3019 const FieldDecl *Field = E->getInitializedFieldInUnion(); 3020 Result = APValue(Field); 3021 if (!Field) 3022 return true; 3023 3024 // If the initializer list for a union does not contain any elements, the 3025 // first element of the union is value-initialized. 3026 ImplicitValueInitExpr VIE(Field->getType()); 3027 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 3028 3029 LValue Subobject = This; 3030 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout); 3031 return EvaluateConstantExpression(Result.getUnionValue(), Info, 3032 Subobject, InitExpr); 3033 } 3034 3035 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) && 3036 "initializer list for class with base classes"); 3037 Result = APValue(APValue::UninitStruct(), 0, 3038 std::distance(RD->field_begin(), RD->field_end())); 3039 unsigned ElementNo = 0; 3040 for (RecordDecl::field_iterator Field = RD->field_begin(), 3041 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) { 3042 // Anonymous bit-fields are not considered members of the class for 3043 // purposes of aggregate initialization. 3044 if (Field->isUnnamedBitfield()) 3045 continue; 3046 3047 LValue Subobject = This; 3048 3049 if (ElementNo < E->getNumInits()) { 3050 HandleLValueMember(Info, E->getInit(ElementNo), Subobject, *Field, 3051 &Layout); 3052 if (!EvaluateConstantExpression( 3053 Result.getStructField((*Field)->getFieldIndex()), 3054 Info, Subobject, E->getInit(ElementNo++))) 3055 return false; 3056 } else { 3057 // Perform an implicit value-initialization for members beyond the end of 3058 // the initializer list. 3059 HandleLValueMember(Info, E, Subobject, *Field, &Layout); 3060 ImplicitValueInitExpr VIE(Field->getType()); 3061 if (!EvaluateConstantExpression( 3062 Result.getStructField((*Field)->getFieldIndex()), 3063 Info, Subobject, &VIE)) 3064 return false; 3065 } 3066 } 3067 3068 return true; 3069 } 3070 3071 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 3072 const CXXConstructorDecl *FD = E->getConstructor(); 3073 bool ZeroInit = E->requiresZeroInitialization(); 3074 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 3075 // If we've already performed zero-initialization, we're already done. 3076 if (!Result.isUninit()) 3077 return true; 3078 3079 if (ZeroInit) 3080 return ZeroInitialization(E); 3081 3082 const CXXRecordDecl *RD = FD->getParent(); 3083 if (RD->isUnion()) 3084 Result = APValue((FieldDecl*)0); 3085 else 3086 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 3087 std::distance(RD->field_begin(), RD->field_end())); 3088 return true; 3089 } 3090 3091 const FunctionDecl *Definition = 0; 3092 FD->getBody(Definition); 3093 3094 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition)) 3095 return false; 3096 3097 // Avoid materializing a temporary for an elidable copy/move constructor. 3098 if (E->isElidable() && !ZeroInit) 3099 if (const MaterializeTemporaryExpr *ME 3100 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 3101 return Visit(ME->GetTemporaryExpr()); 3102 3103 if (ZeroInit && !ZeroInitialization(E)) 3104 return false; 3105 3106 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs()); 3107 return HandleConstructorCall(E, This, Args, 3108 cast<CXXConstructorDecl>(Definition), Info, 3109 Result); 3110 } 3111 3112 static bool EvaluateRecord(const Expr *E, const LValue &This, 3113 APValue &Result, EvalInfo &Info) { 3114 assert(E->isRValue() && E->getType()->isRecordType() && 3115 "can't evaluate expression as a record rvalue"); 3116 return RecordExprEvaluator(Info, This, Result).Visit(E); 3117 } 3118 3119 //===----------------------------------------------------------------------===// 3120 // Temporary Evaluation 3121 // 3122 // Temporaries are represented in the AST as rvalues, but generally behave like 3123 // lvalues. The full-object of which the temporary is a subobject is implicitly 3124 // materialized so that a reference can bind to it. 3125 //===----------------------------------------------------------------------===// 3126 namespace { 3127 class TemporaryExprEvaluator 3128 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 3129 public: 3130 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 3131 LValueExprEvaluatorBaseTy(Info, Result) {} 3132 3133 /// Visit an expression which constructs the value of this temporary. 3134 bool VisitConstructExpr(const Expr *E) { 3135 Result.set(E, Info.CurrentCall); 3136 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info, 3137 Result, E); 3138 } 3139 3140 bool VisitCastExpr(const CastExpr *E) { 3141 switch (E->getCastKind()) { 3142 default: 3143 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 3144 3145 case CK_ConstructorConversion: 3146 return VisitConstructExpr(E->getSubExpr()); 3147 } 3148 } 3149 bool VisitInitListExpr(const InitListExpr *E) { 3150 return VisitConstructExpr(E); 3151 } 3152 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 3153 return VisitConstructExpr(E); 3154 } 3155 bool VisitCallExpr(const CallExpr *E) { 3156 return VisitConstructExpr(E); 3157 } 3158 }; 3159 } // end anonymous namespace 3160 3161 /// Evaluate an expression of record type as a temporary. 3162 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 3163 assert(E->isRValue() && E->getType()->isRecordType()); 3164 return TemporaryExprEvaluator(Info, Result).Visit(E); 3165 } 3166 3167 //===----------------------------------------------------------------------===// 3168 // Vector Evaluation 3169 //===----------------------------------------------------------------------===// 3170 3171 namespace { 3172 class VectorExprEvaluator 3173 : public ExprEvaluatorBase<VectorExprEvaluator, bool> { 3174 APValue &Result; 3175 public: 3176 3177 VectorExprEvaluator(EvalInfo &info, APValue &Result) 3178 : ExprEvaluatorBaseTy(info), Result(Result) {} 3179 3180 bool Success(const ArrayRef<APValue> &V, const Expr *E) { 3181 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 3182 // FIXME: remove this APValue copy. 3183 Result = APValue(V.data(), V.size()); 3184 return true; 3185 } 3186 bool Success(const CCValue &V, const Expr *E) { 3187 assert(V.isVector()); 3188 Result = V; 3189 return true; 3190 } 3191 bool ZeroInitialization(const Expr *E); 3192 3193 bool VisitUnaryReal(const UnaryOperator *E) 3194 { return Visit(E->getSubExpr()); } 3195 bool VisitCastExpr(const CastExpr* E); 3196 bool VisitInitListExpr(const InitListExpr *E); 3197 bool VisitUnaryImag(const UnaryOperator *E); 3198 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 3199 // binary comparisons, binary and/or/xor, 3200 // shufflevector, ExtVectorElementExpr 3201 }; 3202 } // end anonymous namespace 3203 3204 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 3205 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 3206 return VectorExprEvaluator(Info, Result).Visit(E); 3207 } 3208 3209 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) { 3210 const VectorType *VTy = E->getType()->castAs<VectorType>(); 3211 unsigned NElts = VTy->getNumElements(); 3212 3213 const Expr *SE = E->getSubExpr(); 3214 QualType SETy = SE->getType(); 3215 3216 switch (E->getCastKind()) { 3217 case CK_VectorSplat: { 3218 APValue Val = APValue(); 3219 if (SETy->isIntegerType()) { 3220 APSInt IntResult; 3221 if (!EvaluateInteger(SE, IntResult, Info)) 3222 return false; 3223 Val = APValue(IntResult); 3224 } else if (SETy->isRealFloatingType()) { 3225 APFloat F(0.0); 3226 if (!EvaluateFloat(SE, F, Info)) 3227 return false; 3228 Val = APValue(F); 3229 } else { 3230 return Error(E); 3231 } 3232 3233 // Splat and create vector APValue. 3234 SmallVector<APValue, 4> Elts(NElts, Val); 3235 return Success(Elts, E); 3236 } 3237 case CK_BitCast: { 3238 // Evaluate the operand into an APInt we can extract from. 3239 llvm::APInt SValInt; 3240 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 3241 return false; 3242 // Extract the elements 3243 QualType EltTy = VTy->getElementType(); 3244 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 3245 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 3246 SmallVector<APValue, 4> Elts; 3247 if (EltTy->isRealFloatingType()) { 3248 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 3249 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble; 3250 unsigned FloatEltSize = EltSize; 3251 if (&Sem == &APFloat::x87DoubleExtended) 3252 FloatEltSize = 80; 3253 for (unsigned i = 0; i < NElts; i++) { 3254 llvm::APInt Elt; 3255 if (BigEndian) 3256 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 3257 else 3258 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 3259 Elts.push_back(APValue(APFloat(Elt, isIEESem))); 3260 } 3261 } else if (EltTy->isIntegerType()) { 3262 for (unsigned i = 0; i < NElts; i++) { 3263 llvm::APInt Elt; 3264 if (BigEndian) 3265 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 3266 else 3267 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 3268 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 3269 } 3270 } else { 3271 return Error(E); 3272 } 3273 return Success(Elts, E); 3274 } 3275 default: 3276 return ExprEvaluatorBaseTy::VisitCastExpr(E); 3277 } 3278 } 3279 3280 bool 3281 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 3282 const VectorType *VT = E->getType()->castAs<VectorType>(); 3283 unsigned NumInits = E->getNumInits(); 3284 unsigned NumElements = VT->getNumElements(); 3285 3286 QualType EltTy = VT->getElementType(); 3287 SmallVector<APValue, 4> Elements; 3288 3289 // The number of initializers can be less than the number of 3290 // vector elements. For OpenCL, this can be due to nested vector 3291 // initialization. For GCC compatibility, missing trailing elements 3292 // should be initialized with zeroes. 3293 unsigned CountInits = 0, CountElts = 0; 3294 while (CountElts < NumElements) { 3295 // Handle nested vector initialization. 3296 if (CountInits < NumInits 3297 && E->getInit(CountInits)->getType()->isExtVectorType()) { 3298 APValue v; 3299 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 3300 return Error(E); 3301 unsigned vlen = v.getVectorLength(); 3302 for (unsigned j = 0; j < vlen; j++) 3303 Elements.push_back(v.getVectorElt(j)); 3304 CountElts += vlen; 3305 } else if (EltTy->isIntegerType()) { 3306 llvm::APSInt sInt(32); 3307 if (CountInits < NumInits) { 3308 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 3309 return Error(E); 3310 } else // trailing integer zero. 3311 sInt = Info.Ctx.MakeIntValue(0, EltTy); 3312 Elements.push_back(APValue(sInt)); 3313 CountElts++; 3314 } else { 3315 llvm::APFloat f(0.0); 3316 if (CountInits < NumInits) { 3317 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 3318 return Error(E); 3319 } else // trailing float zero. 3320 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 3321 Elements.push_back(APValue(f)); 3322 CountElts++; 3323 } 3324 CountInits++; 3325 } 3326 return Success(Elements, E); 3327 } 3328 3329 bool 3330 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 3331 const VectorType *VT = E->getType()->getAs<VectorType>(); 3332 QualType EltTy = VT->getElementType(); 3333 APValue ZeroElement; 3334 if (EltTy->isIntegerType()) 3335 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 3336 else 3337 ZeroElement = 3338 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 3339 3340 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 3341 return Success(Elements, E); 3342 } 3343 3344 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 3345 VisitIgnoredValue(E->getSubExpr()); 3346 return ZeroInitialization(E); 3347 } 3348 3349 //===----------------------------------------------------------------------===// 3350 // Array Evaluation 3351 //===----------------------------------------------------------------------===// 3352 3353 namespace { 3354 class ArrayExprEvaluator 3355 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> { 3356 const LValue &This; 3357 APValue &Result; 3358 public: 3359 3360 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 3361 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 3362 3363 bool Success(const APValue &V, const Expr *E) { 3364 assert(V.isArray() && "Expected array type"); 3365 Result = V; 3366 return true; 3367 } 3368 3369 bool ZeroInitialization(const Expr *E) { 3370 const ConstantArrayType *CAT = 3371 Info.Ctx.getAsConstantArrayType(E->getType()); 3372 if (!CAT) 3373 return Error(E); 3374 3375 Result = APValue(APValue::UninitArray(), 0, 3376 CAT->getSize().getZExtValue()); 3377 if (!Result.hasArrayFiller()) return true; 3378 3379 // Zero-initialize all elements. 3380 LValue Subobject = This; 3381 Subobject.addArray(Info, E, CAT); 3382 ImplicitValueInitExpr VIE(CAT->getElementType()); 3383 return EvaluateConstantExpression(Result.getArrayFiller(), Info, 3384 Subobject, &VIE); 3385 } 3386 3387 bool VisitInitListExpr(const InitListExpr *E); 3388 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 3389 }; 3390 } // end anonymous namespace 3391 3392 static bool EvaluateArray(const Expr *E, const LValue &This, 3393 APValue &Result, EvalInfo &Info) { 3394 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 3395 return ArrayExprEvaluator(Info, This, Result).Visit(E); 3396 } 3397 3398 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 3399 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 3400 if (!CAT) 3401 return Error(E); 3402 3403 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 3404 // an appropriately-typed string literal enclosed in braces. 3405 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() && 3406 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) { 3407 LValue LV; 3408 if (!EvaluateLValue(E->getInit(0), LV, Info)) 3409 return false; 3410 uint64_t NumElements = CAT->getSize().getZExtValue(); 3411 Result = APValue(APValue::UninitArray(), NumElements, NumElements); 3412 3413 // Copy the string literal into the array. FIXME: Do this better. 3414 LV.addArray(Info, E, CAT); 3415 for (uint64_t I = 0; I < NumElements; ++I) { 3416 CCValue Char; 3417 if (!HandleLValueToRValueConversion(Info, E->getInit(0), 3418 CAT->getElementType(), LV, Char)) 3419 return false; 3420 if (!CheckConstantExpression(Info, E->getInit(0), Char, 3421 Result.getArrayInitializedElt(I))) 3422 return false; 3423 if (!HandleLValueArrayAdjustment(Info, E->getInit(0), LV, 3424 CAT->getElementType(), 1)) 3425 return false; 3426 } 3427 return true; 3428 } 3429 3430 Result = APValue(APValue::UninitArray(), E->getNumInits(), 3431 CAT->getSize().getZExtValue()); 3432 LValue Subobject = This; 3433 Subobject.addArray(Info, E, CAT); 3434 unsigned Index = 0; 3435 for (InitListExpr::const_iterator I = E->begin(), End = E->end(); 3436 I != End; ++I, ++Index) { 3437 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index), 3438 Info, Subobject, cast<Expr>(*I))) 3439 return false; 3440 if (!HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject, 3441 CAT->getElementType(), 1)) 3442 return false; 3443 } 3444 3445 if (!Result.hasArrayFiller()) return true; 3446 assert(E->hasArrayFiller() && "no array filler for incomplete init list"); 3447 // FIXME: The Subobject here isn't necessarily right. This rarely matters, 3448 // but sometimes does: 3449 // struct S { constexpr S() : p(&p) {} void *p; }; 3450 // S s[10] = {}; 3451 return EvaluateConstantExpression(Result.getArrayFiller(), Info, 3452 Subobject, E->getArrayFiller()); 3453 } 3454 3455 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 3456 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 3457 if (!CAT) 3458 return Error(E); 3459 3460 bool HadZeroInit = !Result.isUninit(); 3461 if (!HadZeroInit) 3462 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue()); 3463 if (!Result.hasArrayFiller()) 3464 return true; 3465 3466 const CXXConstructorDecl *FD = E->getConstructor(); 3467 3468 bool ZeroInit = E->requiresZeroInitialization(); 3469 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 3470 if (HadZeroInit) 3471 return true; 3472 3473 if (ZeroInit) { 3474 LValue Subobject = This; 3475 Subobject.addArray(Info, E, CAT); 3476 ImplicitValueInitExpr VIE(CAT->getElementType()); 3477 return EvaluateConstantExpression(Result.getArrayFiller(), Info, 3478 Subobject, &VIE); 3479 } 3480 3481 const CXXRecordDecl *RD = FD->getParent(); 3482 if (RD->isUnion()) 3483 Result.getArrayFiller() = APValue((FieldDecl*)0); 3484 else 3485 Result.getArrayFiller() = 3486 APValue(APValue::UninitStruct(), RD->getNumBases(), 3487 std::distance(RD->field_begin(), RD->field_end())); 3488 return true; 3489 } 3490 3491 const FunctionDecl *Definition = 0; 3492 FD->getBody(Definition); 3493 3494 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition)) 3495 return false; 3496 3497 // FIXME: The Subobject here isn't necessarily right. This rarely matters, 3498 // but sometimes does: 3499 // struct S { constexpr S() : p(&p) {} void *p; }; 3500 // S s[10]; 3501 LValue Subobject = This; 3502 Subobject.addArray(Info, E, CAT); 3503 3504 if (ZeroInit && !HadZeroInit) { 3505 ImplicitValueInitExpr VIE(CAT->getElementType()); 3506 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject, 3507 &VIE)) 3508 return false; 3509 } 3510 3511 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs()); 3512 return HandleConstructorCall(E, Subobject, Args, 3513 cast<CXXConstructorDecl>(Definition), 3514 Info, Result.getArrayFiller()); 3515 } 3516 3517 //===----------------------------------------------------------------------===// 3518 // Integer Evaluation 3519 // 3520 // As a GNU extension, we support casting pointers to sufficiently-wide integer 3521 // types and back in constant folding. Integer values are thus represented 3522 // either as an integer-valued APValue, or as an lvalue-valued APValue. 3523 //===----------------------------------------------------------------------===// 3524 3525 namespace { 3526 class IntExprEvaluator 3527 : public ExprEvaluatorBase<IntExprEvaluator, bool> { 3528 CCValue &Result; 3529 public: 3530 IntExprEvaluator(EvalInfo &info, CCValue &result) 3531 : ExprEvaluatorBaseTy(info), Result(result) {} 3532 3533 bool Success(const llvm::APSInt &SI, const Expr *E) { 3534 assert(E->getType()->isIntegralOrEnumerationType() && 3535 "Invalid evaluation result."); 3536 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 3537 "Invalid evaluation result."); 3538 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 3539 "Invalid evaluation result."); 3540 Result = CCValue(SI); 3541 return true; 3542 } 3543 3544 bool Success(const llvm::APInt &I, const Expr *E) { 3545 assert(E->getType()->isIntegralOrEnumerationType() && 3546 "Invalid evaluation result."); 3547 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 3548 "Invalid evaluation result."); 3549 Result = CCValue(APSInt(I)); 3550 Result.getInt().setIsUnsigned( 3551 E->getType()->isUnsignedIntegerOrEnumerationType()); 3552 return true; 3553 } 3554 3555 bool Success(uint64_t Value, const Expr *E) { 3556 assert(E->getType()->isIntegralOrEnumerationType() && 3557 "Invalid evaluation result."); 3558 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType())); 3559 return true; 3560 } 3561 3562 bool Success(CharUnits Size, const Expr *E) { 3563 return Success(Size.getQuantity(), E); 3564 } 3565 3566 bool Success(const CCValue &V, const Expr *E) { 3567 if (V.isLValue() || V.isAddrLabelDiff()) { 3568 Result = V; 3569 return true; 3570 } 3571 return Success(V.getInt(), E); 3572 } 3573 3574 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 3575 3576 //===--------------------------------------------------------------------===// 3577 // Visitor Methods 3578 //===--------------------------------------------------------------------===// 3579 3580 bool VisitIntegerLiteral(const IntegerLiteral *E) { 3581 return Success(E->getValue(), E); 3582 } 3583 bool VisitCharacterLiteral(const CharacterLiteral *E) { 3584 return Success(E->getValue(), E); 3585 } 3586 3587 bool CheckReferencedDecl(const Expr *E, const Decl *D); 3588 bool VisitDeclRefExpr(const DeclRefExpr *E) { 3589 if (CheckReferencedDecl(E, E->getDecl())) 3590 return true; 3591 3592 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 3593 } 3594 bool VisitMemberExpr(const MemberExpr *E) { 3595 if (CheckReferencedDecl(E, E->getMemberDecl())) { 3596 VisitIgnoredValue(E->getBase()); 3597 return true; 3598 } 3599 3600 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 3601 } 3602 3603 bool VisitCallExpr(const CallExpr *E); 3604 bool VisitBinaryOperator(const BinaryOperator *E); 3605 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 3606 bool VisitUnaryOperator(const UnaryOperator *E); 3607 3608 bool VisitCastExpr(const CastExpr* E); 3609 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 3610 3611 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 3612 return Success(E->getValue(), E); 3613 } 3614 3615 // Note, GNU defines __null as an integer, not a pointer. 3616 bool VisitGNUNullExpr(const GNUNullExpr *E) { 3617 return ZeroInitialization(E); 3618 } 3619 3620 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) { 3621 return Success(E->getValue(), E); 3622 } 3623 3624 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) { 3625 return Success(E->getValue(), E); 3626 } 3627 3628 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 3629 return Success(E->getValue(), E); 3630 } 3631 3632 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 3633 return Success(E->getValue(), E); 3634 } 3635 3636 bool VisitUnaryReal(const UnaryOperator *E); 3637 bool VisitUnaryImag(const UnaryOperator *E); 3638 3639 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 3640 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 3641 3642 private: 3643 CharUnits GetAlignOfExpr(const Expr *E); 3644 CharUnits GetAlignOfType(QualType T); 3645 static QualType GetObjectType(APValue::LValueBase B); 3646 bool TryEvaluateBuiltinObjectSize(const CallExpr *E); 3647 // FIXME: Missing: array subscript of vector, member of vector 3648 }; 3649 } // end anonymous namespace 3650 3651 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 3652 /// produce either the integer value or a pointer. 3653 /// 3654 /// GCC has a heinous extension which folds casts between pointer types and 3655 /// pointer-sized integral types. We support this by allowing the evaluation of 3656 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 3657 /// Some simple arithmetic on such values is supported (they are treated much 3658 /// like char*). 3659 static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result, 3660 EvalInfo &Info) { 3661 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 3662 return IntExprEvaluator(Info, Result).Visit(E); 3663 } 3664 3665 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 3666 CCValue Val; 3667 if (!EvaluateIntegerOrLValue(E, Val, Info)) 3668 return false; 3669 if (!Val.isInt()) { 3670 // FIXME: It would be better to produce the diagnostic for casting 3671 // a pointer to an integer. 3672 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 3673 return false; 3674 } 3675 Result = Val.getInt(); 3676 return true; 3677 } 3678 3679 /// Check whether the given declaration can be directly converted to an integral 3680 /// rvalue. If not, no diagnostic is produced; there are other things we can 3681 /// try. 3682 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 3683 // Enums are integer constant exprs. 3684 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 3685 // Check for signedness/width mismatches between E type and ECD value. 3686 bool SameSign = (ECD->getInitVal().isSigned() 3687 == E->getType()->isSignedIntegerOrEnumerationType()); 3688 bool SameWidth = (ECD->getInitVal().getBitWidth() 3689 == Info.Ctx.getIntWidth(E->getType())); 3690 if (SameSign && SameWidth) 3691 return Success(ECD->getInitVal(), E); 3692 else { 3693 // Get rid of mismatch (otherwise Success assertions will fail) 3694 // by computing a new value matching the type of E. 3695 llvm::APSInt Val = ECD->getInitVal(); 3696 if (!SameSign) 3697 Val.setIsSigned(!ECD->getInitVal().isSigned()); 3698 if (!SameWidth) 3699 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 3700 return Success(Val, E); 3701 } 3702 } 3703 return false; 3704 } 3705 3706 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 3707 /// as GCC. 3708 static int EvaluateBuiltinClassifyType(const CallExpr *E) { 3709 // The following enum mimics the values returned by GCC. 3710 // FIXME: Does GCC differ between lvalue and rvalue references here? 3711 enum gcc_type_class { 3712 no_type_class = -1, 3713 void_type_class, integer_type_class, char_type_class, 3714 enumeral_type_class, boolean_type_class, 3715 pointer_type_class, reference_type_class, offset_type_class, 3716 real_type_class, complex_type_class, 3717 function_type_class, method_type_class, 3718 record_type_class, union_type_class, 3719 array_type_class, string_type_class, 3720 lang_type_class 3721 }; 3722 3723 // If no argument was supplied, default to "no_type_class". This isn't 3724 // ideal, however it is what gcc does. 3725 if (E->getNumArgs() == 0) 3726 return no_type_class; 3727 3728 QualType ArgTy = E->getArg(0)->getType(); 3729 if (ArgTy->isVoidType()) 3730 return void_type_class; 3731 else if (ArgTy->isEnumeralType()) 3732 return enumeral_type_class; 3733 else if (ArgTy->isBooleanType()) 3734 return boolean_type_class; 3735 else if (ArgTy->isCharType()) 3736 return string_type_class; // gcc doesn't appear to use char_type_class 3737 else if (ArgTy->isIntegerType()) 3738 return integer_type_class; 3739 else if (ArgTy->isPointerType()) 3740 return pointer_type_class; 3741 else if (ArgTy->isReferenceType()) 3742 return reference_type_class; 3743 else if (ArgTy->isRealType()) 3744 return real_type_class; 3745 else if (ArgTy->isComplexType()) 3746 return complex_type_class; 3747 else if (ArgTy->isFunctionType()) 3748 return function_type_class; 3749 else if (ArgTy->isStructureOrClassType()) 3750 return record_type_class; 3751 else if (ArgTy->isUnionType()) 3752 return union_type_class; 3753 else if (ArgTy->isArrayType()) 3754 return array_type_class; 3755 else if (ArgTy->isUnionType()) 3756 return union_type_class; 3757 else // FIXME: offset_type_class, method_type_class, & lang_type_class? 3758 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 3759 } 3760 3761 /// EvaluateBuiltinConstantPForLValue - Determine the result of 3762 /// __builtin_constant_p when applied to the given lvalue. 3763 /// 3764 /// An lvalue is only "constant" if it is a pointer or reference to the first 3765 /// character of a string literal. 3766 template<typename LValue> 3767 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) { 3768 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>(); 3769 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero(); 3770 } 3771 3772 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 3773 /// GCC as we can manage. 3774 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) { 3775 QualType ArgType = Arg->getType(); 3776 3777 // __builtin_constant_p always has one operand. The rules which gcc follows 3778 // are not precisely documented, but are as follows: 3779 // 3780 // - If the operand is of integral, floating, complex or enumeration type, 3781 // and can be folded to a known value of that type, it returns 1. 3782 // - If the operand and can be folded to a pointer to the first character 3783 // of a string literal (or such a pointer cast to an integral type), it 3784 // returns 1. 3785 // 3786 // Otherwise, it returns 0. 3787 // 3788 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 3789 // its support for this does not currently work. 3790 if (ArgType->isIntegralOrEnumerationType()) { 3791 Expr::EvalResult Result; 3792 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects) 3793 return false; 3794 3795 APValue &V = Result.Val; 3796 if (V.getKind() == APValue::Int) 3797 return true; 3798 3799 return EvaluateBuiltinConstantPForLValue(V); 3800 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) { 3801 return Arg->isEvaluatable(Ctx); 3802 } else if (ArgType->isPointerType() || Arg->isGLValue()) { 3803 LValue LV; 3804 Expr::EvalStatus Status; 3805 EvalInfo Info(Ctx, Status); 3806 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info) 3807 : EvaluatePointer(Arg, LV, Info)) && 3808 !Status.HasSideEffects) 3809 return EvaluateBuiltinConstantPForLValue(LV); 3810 } 3811 3812 // Anything else isn't considered to be sufficiently constant. 3813 return false; 3814 } 3815 3816 /// Retrieves the "underlying object type" of the given expression, 3817 /// as used by __builtin_object_size. 3818 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) { 3819 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 3820 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 3821 return VD->getType(); 3822 } else if (const Expr *E = B.get<const Expr*>()) { 3823 if (isa<CompoundLiteralExpr>(E)) 3824 return E->getType(); 3825 } 3826 3827 return QualType(); 3828 } 3829 3830 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) { 3831 // TODO: Perhaps we should let LLVM lower this? 3832 LValue Base; 3833 if (!EvaluatePointer(E->getArg(0), Base, Info)) 3834 return false; 3835 3836 // If we can prove the base is null, lower to zero now. 3837 if (!Base.getLValueBase()) return Success(0, E); 3838 3839 QualType T = GetObjectType(Base.getLValueBase()); 3840 if (T.isNull() || 3841 T->isIncompleteType() || 3842 T->isFunctionType() || 3843 T->isVariablyModifiedType() || 3844 T->isDependentType()) 3845 return Error(E); 3846 3847 CharUnits Size = Info.Ctx.getTypeSizeInChars(T); 3848 CharUnits Offset = Base.getLValueOffset(); 3849 3850 if (!Offset.isNegative() && Offset <= Size) 3851 Size -= Offset; 3852 else 3853 Size = CharUnits::Zero(); 3854 return Success(Size, E); 3855 } 3856 3857 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 3858 switch (E->isBuiltinCall()) { 3859 default: 3860 return ExprEvaluatorBaseTy::VisitCallExpr(E); 3861 3862 case Builtin::BI__builtin_object_size: { 3863 if (TryEvaluateBuiltinObjectSize(E)) 3864 return true; 3865 3866 // If evaluating the argument has side-effects we can't determine 3867 // the size of the object and lower it to unknown now. 3868 if (E->getArg(0)->HasSideEffects(Info.Ctx)) { 3869 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1) 3870 return Success(-1ULL, E); 3871 return Success(0, E); 3872 } 3873 3874 return Error(E); 3875 } 3876 3877 case Builtin::BI__builtin_classify_type: 3878 return Success(EvaluateBuiltinClassifyType(E), E); 3879 3880 case Builtin::BI__builtin_constant_p: 3881 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E); 3882 3883 case Builtin::BI__builtin_eh_return_data_regno: { 3884 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 3885 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 3886 return Success(Operand, E); 3887 } 3888 3889 case Builtin::BI__builtin_expect: 3890 return Visit(E->getArg(0)); 3891 3892 case Builtin::BIstrlen: 3893 // A call to strlen is not a constant expression. 3894 if (Info.getLangOpts().CPlusPlus0x) 3895 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function) 3896 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'"; 3897 else 3898 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 3899 // Fall through. 3900 case Builtin::BI__builtin_strlen: 3901 // As an extension, we support strlen() and __builtin_strlen() as constant 3902 // expressions when the argument is a string literal. 3903 if (const StringLiteral *S 3904 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) { 3905 // The string literal may have embedded null characters. Find the first 3906 // one and truncate there. 3907 StringRef Str = S->getString(); 3908 StringRef::size_type Pos = Str.find(0); 3909 if (Pos != StringRef::npos) 3910 Str = Str.substr(0, Pos); 3911 3912 return Success(Str.size(), E); 3913 } 3914 3915 return Error(E); 3916 3917 case Builtin::BI__atomic_is_lock_free: { 3918 APSInt SizeVal; 3919 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 3920 return false; 3921 3922 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 3923 // of two less than the maximum inline atomic width, we know it is 3924 // lock-free. If the size isn't a power of two, or greater than the 3925 // maximum alignment where we promote atomics, we know it is not lock-free 3926 // (at least not in the sense of atomic_is_lock_free). Otherwise, 3927 // the answer can only be determined at runtime; for example, 16-byte 3928 // atomics have lock-free implementations on some, but not all, 3929 // x86-64 processors. 3930 3931 // Check power-of-two. 3932 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 3933 if (!Size.isPowerOfTwo()) 3934 #if 0 3935 // FIXME: Suppress this folding until the ABI for the promotion width 3936 // settles. 3937 return Success(0, E); 3938 #else 3939 return Error(E); 3940 #endif 3941 3942 #if 0 3943 // Check against promotion width. 3944 // FIXME: Suppress this folding until the ABI for the promotion width 3945 // settles. 3946 unsigned PromoteWidthBits = 3947 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth(); 3948 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits)) 3949 return Success(0, E); 3950 #endif 3951 3952 // Check against inlining width. 3953 unsigned InlineWidthBits = 3954 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 3955 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) 3956 return Success(1, E); 3957 3958 return Error(E); 3959 } 3960 } 3961 } 3962 3963 static bool HasSameBase(const LValue &A, const LValue &B) { 3964 if (!A.getLValueBase()) 3965 return !B.getLValueBase(); 3966 if (!B.getLValueBase()) 3967 return false; 3968 3969 if (A.getLValueBase().getOpaqueValue() != 3970 B.getLValueBase().getOpaqueValue()) { 3971 const Decl *ADecl = GetLValueBaseDecl(A); 3972 if (!ADecl) 3973 return false; 3974 const Decl *BDecl = GetLValueBaseDecl(B); 3975 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 3976 return false; 3977 } 3978 3979 return IsGlobalLValue(A.getLValueBase()) || 3980 A.getLValueFrame() == B.getLValueFrame(); 3981 } 3982 3983 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 3984 if (E->isAssignmentOp()) 3985 return Error(E); 3986 3987 if (E->getOpcode() == BO_Comma) { 3988 VisitIgnoredValue(E->getLHS()); 3989 return Visit(E->getRHS()); 3990 } 3991 3992 if (E->isLogicalOp()) { 3993 // These need to be handled specially because the operands aren't 3994 // necessarily integral 3995 bool lhsResult, rhsResult; 3996 3997 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) { 3998 // We were able to evaluate the LHS, see if we can get away with not 3999 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 4000 if (lhsResult == (E->getOpcode() == BO_LOr)) 4001 return Success(lhsResult, E); 4002 4003 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) { 4004 if (E->getOpcode() == BO_LOr) 4005 return Success(lhsResult || rhsResult, E); 4006 else 4007 return Success(lhsResult && rhsResult, E); 4008 } 4009 } else { 4010 // FIXME: If both evaluations fail, we should produce the diagnostic from 4011 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's 4012 // less clear how to diagnose this. 4013 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) { 4014 // We can't evaluate the LHS; however, sometimes the result 4015 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 4016 if (rhsResult == (E->getOpcode() == BO_LOr)) { 4017 // Since we weren't able to evaluate the left hand side, it 4018 // must have had side effects. 4019 Info.EvalStatus.HasSideEffects = true; 4020 4021 return Success(rhsResult, E); 4022 } 4023 } 4024 } 4025 4026 return false; 4027 } 4028 4029 QualType LHSTy = E->getLHS()->getType(); 4030 QualType RHSTy = E->getRHS()->getType(); 4031 4032 if (LHSTy->isAnyComplexType()) { 4033 assert(RHSTy->isAnyComplexType() && "Invalid comparison"); 4034 ComplexValue LHS, RHS; 4035 4036 if (!EvaluateComplex(E->getLHS(), LHS, Info)) 4037 return false; 4038 4039 if (!EvaluateComplex(E->getRHS(), RHS, Info)) 4040 return false; 4041 4042 if (LHS.isComplexFloat()) { 4043 APFloat::cmpResult CR_r = 4044 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 4045 APFloat::cmpResult CR_i = 4046 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 4047 4048 if (E->getOpcode() == BO_EQ) 4049 return Success((CR_r == APFloat::cmpEqual && 4050 CR_i == APFloat::cmpEqual), E); 4051 else { 4052 assert(E->getOpcode() == BO_NE && 4053 "Invalid complex comparison."); 4054 return Success(((CR_r == APFloat::cmpGreaterThan || 4055 CR_r == APFloat::cmpLessThan || 4056 CR_r == APFloat::cmpUnordered) || 4057 (CR_i == APFloat::cmpGreaterThan || 4058 CR_i == APFloat::cmpLessThan || 4059 CR_i == APFloat::cmpUnordered)), E); 4060 } 4061 } else { 4062 if (E->getOpcode() == BO_EQ) 4063 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() && 4064 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E); 4065 else { 4066 assert(E->getOpcode() == BO_NE && 4067 "Invalid compex comparison."); 4068 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() || 4069 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E); 4070 } 4071 } 4072 } 4073 4074 if (LHSTy->isRealFloatingType() && 4075 RHSTy->isRealFloatingType()) { 4076 APFloat RHS(0.0), LHS(0.0); 4077 4078 if (!EvaluateFloat(E->getRHS(), RHS, Info)) 4079 return false; 4080 4081 if (!EvaluateFloat(E->getLHS(), LHS, Info)) 4082 return false; 4083 4084 APFloat::cmpResult CR = LHS.compare(RHS); 4085 4086 switch (E->getOpcode()) { 4087 default: 4088 llvm_unreachable("Invalid binary operator!"); 4089 case BO_LT: 4090 return Success(CR == APFloat::cmpLessThan, E); 4091 case BO_GT: 4092 return Success(CR == APFloat::cmpGreaterThan, E); 4093 case BO_LE: 4094 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E); 4095 case BO_GE: 4096 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual, 4097 E); 4098 case BO_EQ: 4099 return Success(CR == APFloat::cmpEqual, E); 4100 case BO_NE: 4101 return Success(CR == APFloat::cmpGreaterThan 4102 || CR == APFloat::cmpLessThan 4103 || CR == APFloat::cmpUnordered, E); 4104 } 4105 } 4106 4107 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 4108 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) { 4109 LValue LHSValue; 4110 if (!EvaluatePointer(E->getLHS(), LHSValue, Info)) 4111 return false; 4112 4113 LValue RHSValue; 4114 if (!EvaluatePointer(E->getRHS(), RHSValue, Info)) 4115 return false; 4116 4117 // Reject differing bases from the normal codepath; we special-case 4118 // comparisons to null. 4119 if (!HasSameBase(LHSValue, RHSValue)) { 4120 if (E->getOpcode() == BO_Sub) { 4121 // Handle &&A - &&B. 4122 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 4123 return false; 4124 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>(); 4125 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>(); 4126 if (!LHSExpr || !RHSExpr) 4127 return false; 4128 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 4129 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 4130 if (!LHSAddrExpr || !RHSAddrExpr) 4131 return false; 4132 // Make sure both labels come from the same function. 4133 if (LHSAddrExpr->getLabel()->getDeclContext() != 4134 RHSAddrExpr->getLabel()->getDeclContext()) 4135 return false; 4136 Result = CCValue(LHSAddrExpr, RHSAddrExpr); 4137 return true; 4138 } 4139 // Inequalities and subtractions between unrelated pointers have 4140 // unspecified or undefined behavior. 4141 if (!E->isEqualityOp()) 4142 return Error(E); 4143 // A constant address may compare equal to the address of a symbol. 4144 // The one exception is that address of an object cannot compare equal 4145 // to a null pointer constant. 4146 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 4147 (!RHSValue.Base && !RHSValue.Offset.isZero())) 4148 return Error(E); 4149 // It's implementation-defined whether distinct literals will have 4150 // distinct addresses. In clang, we do not guarantee the addresses are 4151 // distinct. However, we do know that the address of a literal will be 4152 // non-null. 4153 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 4154 LHSValue.Base && RHSValue.Base) 4155 return Error(E); 4156 // We can't tell whether weak symbols will end up pointing to the same 4157 // object. 4158 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 4159 return Error(E); 4160 // Pointers with different bases cannot represent the same object. 4161 // (Note that clang defaults to -fmerge-all-constants, which can 4162 // lead to inconsistent results for comparisons involving the address 4163 // of a constant; this generally doesn't matter in practice.) 4164 return Success(E->getOpcode() == BO_NE, E); 4165 } 4166 4167 // FIXME: Implement the C++11 restrictions: 4168 // - Pointer subtractions must be on elements of the same array. 4169 // - Pointer comparisons must be between members with the same access. 4170 4171 if (E->getOpcode() == BO_Sub) { 4172 QualType Type = E->getLHS()->getType(); 4173 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 4174 4175 CharUnits ElementSize; 4176 if (!HandleSizeof(Info, ElementType, ElementSize)) 4177 return false; 4178 4179 CharUnits Diff = LHSValue.getLValueOffset() - 4180 RHSValue.getLValueOffset(); 4181 return Success(Diff / ElementSize, E); 4182 } 4183 4184 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 4185 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 4186 switch (E->getOpcode()) { 4187 default: llvm_unreachable("missing comparison operator"); 4188 case BO_LT: return Success(LHSOffset < RHSOffset, E); 4189 case BO_GT: return Success(LHSOffset > RHSOffset, E); 4190 case BO_LE: return Success(LHSOffset <= RHSOffset, E); 4191 case BO_GE: return Success(LHSOffset >= RHSOffset, E); 4192 case BO_EQ: return Success(LHSOffset == RHSOffset, E); 4193 case BO_NE: return Success(LHSOffset != RHSOffset, E); 4194 } 4195 } 4196 } 4197 if (!LHSTy->isIntegralOrEnumerationType() || 4198 !RHSTy->isIntegralOrEnumerationType()) { 4199 // We can't continue from here for non-integral types. 4200 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 4201 } 4202 4203 // The LHS of a constant expr is always evaluated and needed. 4204 CCValue LHSVal; 4205 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info)) 4206 return false; 4207 4208 if (!Visit(E->getRHS())) 4209 return false; 4210 CCValue &RHSVal = Result; 4211 4212 // Handle cases like (unsigned long)&a + 4. 4213 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 4214 CharUnits AdditionalOffset = CharUnits::fromQuantity( 4215 RHSVal.getInt().getZExtValue()); 4216 if (E->getOpcode() == BO_Add) 4217 LHSVal.getLValueOffset() += AdditionalOffset; 4218 else 4219 LHSVal.getLValueOffset() -= AdditionalOffset; 4220 Result = LHSVal; 4221 return true; 4222 } 4223 4224 // Handle cases like 4 + (unsigned long)&a 4225 if (E->getOpcode() == BO_Add && 4226 RHSVal.isLValue() && LHSVal.isInt()) { 4227 RHSVal.getLValueOffset() += CharUnits::fromQuantity( 4228 LHSVal.getInt().getZExtValue()); 4229 // Note that RHSVal is Result. 4230 return true; 4231 } 4232 4233 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 4234 // Handle (intptr_t)&&A - (intptr_t)&&B. 4235 if (!LHSVal.getLValueOffset().isZero() || 4236 !RHSVal.getLValueOffset().isZero()) 4237 return false; 4238 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 4239 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 4240 if (!LHSExpr || !RHSExpr) 4241 return false; 4242 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 4243 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 4244 if (!LHSAddrExpr || !RHSAddrExpr) 4245 return false; 4246 // Make sure both labels come from the same function. 4247 if (LHSAddrExpr->getLabel()->getDeclContext() != 4248 RHSAddrExpr->getLabel()->getDeclContext()) 4249 return false; 4250 Result = CCValue(LHSAddrExpr, RHSAddrExpr); 4251 return true; 4252 } 4253 4254 // All the following cases expect both operands to be an integer 4255 if (!LHSVal.isInt() || !RHSVal.isInt()) 4256 return Error(E); 4257 4258 APSInt &LHS = LHSVal.getInt(); 4259 APSInt &RHS = RHSVal.getInt(); 4260 4261 switch (E->getOpcode()) { 4262 default: 4263 return Error(E); 4264 case BO_Mul: return Success(LHS * RHS, E); 4265 case BO_Add: return Success(LHS + RHS, E); 4266 case BO_Sub: return Success(LHS - RHS, E); 4267 case BO_And: return Success(LHS & RHS, E); 4268 case BO_Xor: return Success(LHS ^ RHS, E); 4269 case BO_Or: return Success(LHS | RHS, E); 4270 case BO_Div: 4271 if (RHS == 0) 4272 return Error(E, diag::note_expr_divide_by_zero); 4273 return Success(LHS / RHS, E); 4274 case BO_Rem: 4275 if (RHS == 0) 4276 return Error(E, diag::note_expr_divide_by_zero); 4277 return Success(LHS % RHS, E); 4278 case BO_Shl: { 4279 // During constant-folding, a negative shift is an opposite shift. 4280 if (RHS.isSigned() && RHS.isNegative()) { 4281 RHS = -RHS; 4282 goto shift_right; 4283 } 4284 4285 shift_left: 4286 unsigned SA 4287 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 4288 return Success(LHS << SA, E); 4289 } 4290 case BO_Shr: { 4291 // During constant-folding, a negative shift is an opposite shift. 4292 if (RHS.isSigned() && RHS.isNegative()) { 4293 RHS = -RHS; 4294 goto shift_left; 4295 } 4296 4297 shift_right: 4298 unsigned SA = 4299 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 4300 return Success(LHS >> SA, E); 4301 } 4302 4303 case BO_LT: return Success(LHS < RHS, E); 4304 case BO_GT: return Success(LHS > RHS, E); 4305 case BO_LE: return Success(LHS <= RHS, E); 4306 case BO_GE: return Success(LHS >= RHS, E); 4307 case BO_EQ: return Success(LHS == RHS, E); 4308 case BO_NE: return Success(LHS != RHS, E); 4309 } 4310 } 4311 4312 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) { 4313 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 4314 // the result is the size of the referenced type." 4315 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 4316 // result shall be the alignment of the referenced type." 4317 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 4318 T = Ref->getPointeeType(); 4319 4320 // __alignof is defined to return the preferred alignment. 4321 return Info.Ctx.toCharUnitsFromBits( 4322 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 4323 } 4324 4325 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) { 4326 E = E->IgnoreParens(); 4327 4328 // alignof decl is always accepted, even if it doesn't make sense: we default 4329 // to 1 in those cases. 4330 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 4331 return Info.Ctx.getDeclAlign(DRE->getDecl(), 4332 /*RefAsPointee*/true); 4333 4334 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 4335 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 4336 /*RefAsPointee*/true); 4337 4338 return GetAlignOfType(E->getType()); 4339 } 4340 4341 4342 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 4343 /// a result as the expression's type. 4344 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 4345 const UnaryExprOrTypeTraitExpr *E) { 4346 switch(E->getKind()) { 4347 case UETT_AlignOf: { 4348 if (E->isArgumentType()) 4349 return Success(GetAlignOfType(E->getArgumentType()), E); 4350 else 4351 return Success(GetAlignOfExpr(E->getArgumentExpr()), E); 4352 } 4353 4354 case UETT_VecStep: { 4355 QualType Ty = E->getTypeOfArgument(); 4356 4357 if (Ty->isVectorType()) { 4358 unsigned n = Ty->getAs<VectorType>()->getNumElements(); 4359 4360 // The vec_step built-in functions that take a 3-component 4361 // vector return 4. (OpenCL 1.1 spec 6.11.12) 4362 if (n == 3) 4363 n = 4; 4364 4365 return Success(n, E); 4366 } else 4367 return Success(1, E); 4368 } 4369 4370 case UETT_SizeOf: { 4371 QualType SrcTy = E->getTypeOfArgument(); 4372 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 4373 // the result is the size of the referenced type." 4374 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 4375 // result shall be the alignment of the referenced type." 4376 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 4377 SrcTy = Ref->getPointeeType(); 4378 4379 CharUnits Sizeof; 4380 if (!HandleSizeof(Info, SrcTy, Sizeof)) 4381 return false; 4382 return Success(Sizeof, E); 4383 } 4384 } 4385 4386 llvm_unreachable("unknown expr/type trait"); 4387 } 4388 4389 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 4390 CharUnits Result; 4391 unsigned n = OOE->getNumComponents(); 4392 if (n == 0) 4393 return Error(OOE); 4394 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 4395 for (unsigned i = 0; i != n; ++i) { 4396 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i); 4397 switch (ON.getKind()) { 4398 case OffsetOfExpr::OffsetOfNode::Array: { 4399 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 4400 APSInt IdxResult; 4401 if (!EvaluateInteger(Idx, IdxResult, Info)) 4402 return false; 4403 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 4404 if (!AT) 4405 return Error(OOE); 4406 CurrentType = AT->getElementType(); 4407 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 4408 Result += IdxResult.getSExtValue() * ElementSize; 4409 break; 4410 } 4411 4412 case OffsetOfExpr::OffsetOfNode::Field: { 4413 FieldDecl *MemberDecl = ON.getField(); 4414 const RecordType *RT = CurrentType->getAs<RecordType>(); 4415 if (!RT) 4416 return Error(OOE); 4417 RecordDecl *RD = RT->getDecl(); 4418 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 4419 unsigned i = MemberDecl->getFieldIndex(); 4420 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 4421 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 4422 CurrentType = MemberDecl->getType().getNonReferenceType(); 4423 break; 4424 } 4425 4426 case OffsetOfExpr::OffsetOfNode::Identifier: 4427 llvm_unreachable("dependent __builtin_offsetof"); 4428 4429 case OffsetOfExpr::OffsetOfNode::Base: { 4430 CXXBaseSpecifier *BaseSpec = ON.getBase(); 4431 if (BaseSpec->isVirtual()) 4432 return Error(OOE); 4433 4434 // Find the layout of the class whose base we are looking into. 4435 const RecordType *RT = CurrentType->getAs<RecordType>(); 4436 if (!RT) 4437 return Error(OOE); 4438 RecordDecl *RD = RT->getDecl(); 4439 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 4440 4441 // Find the base class itself. 4442 CurrentType = BaseSpec->getType(); 4443 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 4444 if (!BaseRT) 4445 return Error(OOE); 4446 4447 // Add the offset to the base. 4448 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 4449 break; 4450 } 4451 } 4452 } 4453 return Success(Result, OOE); 4454 } 4455 4456 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 4457 switch (E->getOpcode()) { 4458 default: 4459 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 4460 // See C99 6.6p3. 4461 return Error(E); 4462 case UO_Extension: 4463 // FIXME: Should extension allow i-c-e extension expressions in its scope? 4464 // If so, we could clear the diagnostic ID. 4465 return Visit(E->getSubExpr()); 4466 case UO_Plus: 4467 // The result is just the value. 4468 return Visit(E->getSubExpr()); 4469 case UO_Minus: { 4470 if (!Visit(E->getSubExpr())) 4471 return false; 4472 if (!Result.isInt()) return Error(E); 4473 return Success(-Result.getInt(), E); 4474 } 4475 case UO_Not: { 4476 if (!Visit(E->getSubExpr())) 4477 return false; 4478 if (!Result.isInt()) return Error(E); 4479 return Success(~Result.getInt(), E); 4480 } 4481 case UO_LNot: { 4482 bool bres; 4483 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 4484 return false; 4485 return Success(!bres, E); 4486 } 4487 } 4488 } 4489 4490 /// HandleCast - This is used to evaluate implicit or explicit casts where the 4491 /// result type is integer. 4492 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 4493 const Expr *SubExpr = E->getSubExpr(); 4494 QualType DestType = E->getType(); 4495 QualType SrcType = SubExpr->getType(); 4496 4497 switch (E->getCastKind()) { 4498 case CK_BaseToDerived: 4499 case CK_DerivedToBase: 4500 case CK_UncheckedDerivedToBase: 4501 case CK_Dynamic: 4502 case CK_ToUnion: 4503 case CK_ArrayToPointerDecay: 4504 case CK_FunctionToPointerDecay: 4505 case CK_NullToPointer: 4506 case CK_NullToMemberPointer: 4507 case CK_BaseToDerivedMemberPointer: 4508 case CK_DerivedToBaseMemberPointer: 4509 case CK_ConstructorConversion: 4510 case CK_IntegralToPointer: 4511 case CK_ToVoid: 4512 case CK_VectorSplat: 4513 case CK_IntegralToFloating: 4514 case CK_FloatingCast: 4515 case CK_CPointerToObjCPointerCast: 4516 case CK_BlockPointerToObjCPointerCast: 4517 case CK_AnyPointerToBlockPointerCast: 4518 case CK_ObjCObjectLValueCast: 4519 case CK_FloatingRealToComplex: 4520 case CK_FloatingComplexToReal: 4521 case CK_FloatingComplexCast: 4522 case CK_FloatingComplexToIntegralComplex: 4523 case CK_IntegralRealToComplex: 4524 case CK_IntegralComplexCast: 4525 case CK_IntegralComplexToFloatingComplex: 4526 llvm_unreachable("invalid cast kind for integral value"); 4527 4528 case CK_BitCast: 4529 case CK_Dependent: 4530 case CK_LValueBitCast: 4531 case CK_ARCProduceObject: 4532 case CK_ARCConsumeObject: 4533 case CK_ARCReclaimReturnedObject: 4534 case CK_ARCExtendBlockObject: 4535 return Error(E); 4536 4537 case CK_UserDefinedConversion: 4538 case CK_LValueToRValue: 4539 case CK_AtomicToNonAtomic: 4540 case CK_NonAtomicToAtomic: 4541 case CK_NoOp: 4542 return ExprEvaluatorBaseTy::VisitCastExpr(E); 4543 4544 case CK_MemberPointerToBoolean: 4545 case CK_PointerToBoolean: 4546 case CK_IntegralToBoolean: 4547 case CK_FloatingToBoolean: 4548 case CK_FloatingComplexToBoolean: 4549 case CK_IntegralComplexToBoolean: { 4550 bool BoolResult; 4551 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 4552 return false; 4553 return Success(BoolResult, E); 4554 } 4555 4556 case CK_IntegralCast: { 4557 if (!Visit(SubExpr)) 4558 return false; 4559 4560 if (!Result.isInt()) { 4561 // Allow casts of address-of-label differences if they are no-ops 4562 // or narrowing. (The narrowing case isn't actually guaranteed to 4563 // be constant-evaluatable except in some narrow cases which are hard 4564 // to detect here. We let it through on the assumption the user knows 4565 // what they are doing.) 4566 if (Result.isAddrLabelDiff()) 4567 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 4568 // Only allow casts of lvalues if they are lossless. 4569 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 4570 } 4571 4572 return Success(HandleIntToIntCast(DestType, SrcType, 4573 Result.getInt(), Info.Ctx), E); 4574 } 4575 4576 case CK_PointerToIntegral: { 4577 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 4578 4579 LValue LV; 4580 if (!EvaluatePointer(SubExpr, LV, Info)) 4581 return false; 4582 4583 if (LV.getLValueBase()) { 4584 // Only allow based lvalue casts if they are lossless. 4585 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 4586 return Error(E); 4587 4588 LV.Designator.setInvalid(); 4589 LV.moveInto(Result); 4590 return true; 4591 } 4592 4593 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(), 4594 SrcType); 4595 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E); 4596 } 4597 4598 case CK_IntegralComplexToReal: { 4599 ComplexValue C; 4600 if (!EvaluateComplex(SubExpr, C, Info)) 4601 return false; 4602 return Success(C.getComplexIntReal(), E); 4603 } 4604 4605 case CK_FloatingToIntegral: { 4606 APFloat F(0.0); 4607 if (!EvaluateFloat(SubExpr, F, Info)) 4608 return false; 4609 4610 APSInt Value; 4611 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 4612 return false; 4613 return Success(Value, E); 4614 } 4615 } 4616 4617 llvm_unreachable("unknown cast resulting in integral value"); 4618 } 4619 4620 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 4621 if (E->getSubExpr()->getType()->isAnyComplexType()) { 4622 ComplexValue LV; 4623 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 4624 return false; 4625 if (!LV.isComplexInt()) 4626 return Error(E); 4627 return Success(LV.getComplexIntReal(), E); 4628 } 4629 4630 return Visit(E->getSubExpr()); 4631 } 4632 4633 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 4634 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 4635 ComplexValue LV; 4636 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 4637 return false; 4638 if (!LV.isComplexInt()) 4639 return Error(E); 4640 return Success(LV.getComplexIntImag(), E); 4641 } 4642 4643 VisitIgnoredValue(E->getSubExpr()); 4644 return Success(0, E); 4645 } 4646 4647 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 4648 return Success(E->getPackLength(), E); 4649 } 4650 4651 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 4652 return Success(E->getValue(), E); 4653 } 4654 4655 //===----------------------------------------------------------------------===// 4656 // Float Evaluation 4657 //===----------------------------------------------------------------------===// 4658 4659 namespace { 4660 class FloatExprEvaluator 4661 : public ExprEvaluatorBase<FloatExprEvaluator, bool> { 4662 APFloat &Result; 4663 public: 4664 FloatExprEvaluator(EvalInfo &info, APFloat &result) 4665 : ExprEvaluatorBaseTy(info), Result(result) {} 4666 4667 bool Success(const CCValue &V, const Expr *e) { 4668 Result = V.getFloat(); 4669 return true; 4670 } 4671 4672 bool ZeroInitialization(const Expr *E) { 4673 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 4674 return true; 4675 } 4676 4677 bool VisitCallExpr(const CallExpr *E); 4678 4679 bool VisitUnaryOperator(const UnaryOperator *E); 4680 bool VisitBinaryOperator(const BinaryOperator *E); 4681 bool VisitFloatingLiteral(const FloatingLiteral *E); 4682 bool VisitCastExpr(const CastExpr *E); 4683 4684 bool VisitUnaryReal(const UnaryOperator *E); 4685 bool VisitUnaryImag(const UnaryOperator *E); 4686 4687 // FIXME: Missing: array subscript of vector, member of vector 4688 }; 4689 } // end anonymous namespace 4690 4691 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 4692 assert(E->isRValue() && E->getType()->isRealFloatingType()); 4693 return FloatExprEvaluator(Info, Result).Visit(E); 4694 } 4695 4696 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 4697 QualType ResultTy, 4698 const Expr *Arg, 4699 bool SNaN, 4700 llvm::APFloat &Result) { 4701 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 4702 if (!S) return false; 4703 4704 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 4705 4706 llvm::APInt fill; 4707 4708 // Treat empty strings as if they were zero. 4709 if (S->getString().empty()) 4710 fill = llvm::APInt(32, 0); 4711 else if (S->getString().getAsInteger(0, fill)) 4712 return false; 4713 4714 if (SNaN) 4715 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 4716 else 4717 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 4718 return true; 4719 } 4720 4721 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 4722 switch (E->isBuiltinCall()) { 4723 default: 4724 return ExprEvaluatorBaseTy::VisitCallExpr(E); 4725 4726 case Builtin::BI__builtin_huge_val: 4727 case Builtin::BI__builtin_huge_valf: 4728 case Builtin::BI__builtin_huge_vall: 4729 case Builtin::BI__builtin_inf: 4730 case Builtin::BI__builtin_inff: 4731 case Builtin::BI__builtin_infl: { 4732 const llvm::fltSemantics &Sem = 4733 Info.Ctx.getFloatTypeSemantics(E->getType()); 4734 Result = llvm::APFloat::getInf(Sem); 4735 return true; 4736 } 4737 4738 case Builtin::BI__builtin_nans: 4739 case Builtin::BI__builtin_nansf: 4740 case Builtin::BI__builtin_nansl: 4741 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 4742 true, Result)) 4743 return Error(E); 4744 return true; 4745 4746 case Builtin::BI__builtin_nan: 4747 case Builtin::BI__builtin_nanf: 4748 case Builtin::BI__builtin_nanl: 4749 // If this is __builtin_nan() turn this into a nan, otherwise we 4750 // can't constant fold it. 4751 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 4752 false, Result)) 4753 return Error(E); 4754 return true; 4755 4756 case Builtin::BI__builtin_fabs: 4757 case Builtin::BI__builtin_fabsf: 4758 case Builtin::BI__builtin_fabsl: 4759 if (!EvaluateFloat(E->getArg(0), Result, Info)) 4760 return false; 4761 4762 if (Result.isNegative()) 4763 Result.changeSign(); 4764 return true; 4765 4766 case Builtin::BI__builtin_copysign: 4767 case Builtin::BI__builtin_copysignf: 4768 case Builtin::BI__builtin_copysignl: { 4769 APFloat RHS(0.); 4770 if (!EvaluateFloat(E->getArg(0), Result, Info) || 4771 !EvaluateFloat(E->getArg(1), RHS, Info)) 4772 return false; 4773 Result.copySign(RHS); 4774 return true; 4775 } 4776 } 4777 } 4778 4779 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 4780 if (E->getSubExpr()->getType()->isAnyComplexType()) { 4781 ComplexValue CV; 4782 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 4783 return false; 4784 Result = CV.FloatReal; 4785 return true; 4786 } 4787 4788 return Visit(E->getSubExpr()); 4789 } 4790 4791 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 4792 if (E->getSubExpr()->getType()->isAnyComplexType()) { 4793 ComplexValue CV; 4794 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 4795 return false; 4796 Result = CV.FloatImag; 4797 return true; 4798 } 4799 4800 VisitIgnoredValue(E->getSubExpr()); 4801 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 4802 Result = llvm::APFloat::getZero(Sem); 4803 return true; 4804 } 4805 4806 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 4807 switch (E->getOpcode()) { 4808 default: return Error(E); 4809 case UO_Plus: 4810 return EvaluateFloat(E->getSubExpr(), Result, Info); 4811 case UO_Minus: 4812 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 4813 return false; 4814 Result.changeSign(); 4815 return true; 4816 } 4817 } 4818 4819 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 4820 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 4821 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 4822 4823 APFloat RHS(0.0); 4824 if (!EvaluateFloat(E->getLHS(), Result, Info)) 4825 return false; 4826 if (!EvaluateFloat(E->getRHS(), RHS, Info)) 4827 return false; 4828 4829 switch (E->getOpcode()) { 4830 default: return Error(E); 4831 case BO_Mul: 4832 Result.multiply(RHS, APFloat::rmNearestTiesToEven); 4833 return true; 4834 case BO_Add: 4835 Result.add(RHS, APFloat::rmNearestTiesToEven); 4836 return true; 4837 case BO_Sub: 4838 Result.subtract(RHS, APFloat::rmNearestTiesToEven); 4839 return true; 4840 case BO_Div: 4841 Result.divide(RHS, APFloat::rmNearestTiesToEven); 4842 return true; 4843 } 4844 } 4845 4846 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 4847 Result = E->getValue(); 4848 return true; 4849 } 4850 4851 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 4852 const Expr* SubExpr = E->getSubExpr(); 4853 4854 switch (E->getCastKind()) { 4855 default: 4856 return ExprEvaluatorBaseTy::VisitCastExpr(E); 4857 4858 case CK_IntegralToFloating: { 4859 APSInt IntResult; 4860 return EvaluateInteger(SubExpr, IntResult, Info) && 4861 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 4862 E->getType(), Result); 4863 } 4864 4865 case CK_FloatingCast: { 4866 if (!Visit(SubExpr)) 4867 return false; 4868 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 4869 Result); 4870 } 4871 4872 case CK_FloatingComplexToReal: { 4873 ComplexValue V; 4874 if (!EvaluateComplex(SubExpr, V, Info)) 4875 return false; 4876 Result = V.getComplexFloatReal(); 4877 return true; 4878 } 4879 } 4880 } 4881 4882 //===----------------------------------------------------------------------===// 4883 // Complex Evaluation (for float and integer) 4884 //===----------------------------------------------------------------------===// 4885 4886 namespace { 4887 class ComplexExprEvaluator 4888 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> { 4889 ComplexValue &Result; 4890 4891 public: 4892 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 4893 : ExprEvaluatorBaseTy(info), Result(Result) {} 4894 4895 bool Success(const CCValue &V, const Expr *e) { 4896 Result.setFrom(V); 4897 return true; 4898 } 4899 4900 bool ZeroInitialization(const Expr *E); 4901 4902 //===--------------------------------------------------------------------===// 4903 // Visitor Methods 4904 //===--------------------------------------------------------------------===// 4905 4906 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 4907 bool VisitCastExpr(const CastExpr *E); 4908 bool VisitBinaryOperator(const BinaryOperator *E); 4909 bool VisitUnaryOperator(const UnaryOperator *E); 4910 bool VisitInitListExpr(const InitListExpr *E); 4911 }; 4912 } // end anonymous namespace 4913 4914 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 4915 EvalInfo &Info) { 4916 assert(E->isRValue() && E->getType()->isAnyComplexType()); 4917 return ComplexExprEvaluator(Info, Result).Visit(E); 4918 } 4919 4920 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 4921 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType(); 4922 if (ElemTy->isRealFloatingType()) { 4923 Result.makeComplexFloat(); 4924 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 4925 Result.FloatReal = Zero; 4926 Result.FloatImag = Zero; 4927 } else { 4928 Result.makeComplexInt(); 4929 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 4930 Result.IntReal = Zero; 4931 Result.IntImag = Zero; 4932 } 4933 return true; 4934 } 4935 4936 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 4937 const Expr* SubExpr = E->getSubExpr(); 4938 4939 if (SubExpr->getType()->isRealFloatingType()) { 4940 Result.makeComplexFloat(); 4941 APFloat &Imag = Result.FloatImag; 4942 if (!EvaluateFloat(SubExpr, Imag, Info)) 4943 return false; 4944 4945 Result.FloatReal = APFloat(Imag.getSemantics()); 4946 return true; 4947 } else { 4948 assert(SubExpr->getType()->isIntegerType() && 4949 "Unexpected imaginary literal."); 4950 4951 Result.makeComplexInt(); 4952 APSInt &Imag = Result.IntImag; 4953 if (!EvaluateInteger(SubExpr, Imag, Info)) 4954 return false; 4955 4956 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 4957 return true; 4958 } 4959 } 4960 4961 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 4962 4963 switch (E->getCastKind()) { 4964 case CK_BitCast: 4965 case CK_BaseToDerived: 4966 case CK_DerivedToBase: 4967 case CK_UncheckedDerivedToBase: 4968 case CK_Dynamic: 4969 case CK_ToUnion: 4970 case CK_ArrayToPointerDecay: 4971 case CK_FunctionToPointerDecay: 4972 case CK_NullToPointer: 4973 case CK_NullToMemberPointer: 4974 case CK_BaseToDerivedMemberPointer: 4975 case CK_DerivedToBaseMemberPointer: 4976 case CK_MemberPointerToBoolean: 4977 case CK_ConstructorConversion: 4978 case CK_IntegralToPointer: 4979 case CK_PointerToIntegral: 4980 case CK_PointerToBoolean: 4981 case CK_ToVoid: 4982 case CK_VectorSplat: 4983 case CK_IntegralCast: 4984 case CK_IntegralToBoolean: 4985 case CK_IntegralToFloating: 4986 case CK_FloatingToIntegral: 4987 case CK_FloatingToBoolean: 4988 case CK_FloatingCast: 4989 case CK_CPointerToObjCPointerCast: 4990 case CK_BlockPointerToObjCPointerCast: 4991 case CK_AnyPointerToBlockPointerCast: 4992 case CK_ObjCObjectLValueCast: 4993 case CK_FloatingComplexToReal: 4994 case CK_FloatingComplexToBoolean: 4995 case CK_IntegralComplexToReal: 4996 case CK_IntegralComplexToBoolean: 4997 case CK_ARCProduceObject: 4998 case CK_ARCConsumeObject: 4999 case CK_ARCReclaimReturnedObject: 5000 case CK_ARCExtendBlockObject: 5001 llvm_unreachable("invalid cast kind for complex value"); 5002 5003 case CK_LValueToRValue: 5004 case CK_AtomicToNonAtomic: 5005 case CK_NonAtomicToAtomic: 5006 case CK_NoOp: 5007 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5008 5009 case CK_Dependent: 5010 case CK_LValueBitCast: 5011 case CK_UserDefinedConversion: 5012 return Error(E); 5013 5014 case CK_FloatingRealToComplex: { 5015 APFloat &Real = Result.FloatReal; 5016 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 5017 return false; 5018 5019 Result.makeComplexFloat(); 5020 Result.FloatImag = APFloat(Real.getSemantics()); 5021 return true; 5022 } 5023 5024 case CK_FloatingComplexCast: { 5025 if (!Visit(E->getSubExpr())) 5026 return false; 5027 5028 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 5029 QualType From 5030 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 5031 5032 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 5033 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 5034 } 5035 5036 case CK_FloatingComplexToIntegralComplex: { 5037 if (!Visit(E->getSubExpr())) 5038 return false; 5039 5040 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 5041 QualType From 5042 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 5043 Result.makeComplexInt(); 5044 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 5045 To, Result.IntReal) && 5046 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 5047 To, Result.IntImag); 5048 } 5049 5050 case CK_IntegralRealToComplex: { 5051 APSInt &Real = Result.IntReal; 5052 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 5053 return false; 5054 5055 Result.makeComplexInt(); 5056 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 5057 return true; 5058 } 5059 5060 case CK_IntegralComplexCast: { 5061 if (!Visit(E->getSubExpr())) 5062 return false; 5063 5064 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 5065 QualType From 5066 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 5067 5068 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx); 5069 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx); 5070 return true; 5071 } 5072 5073 case CK_IntegralComplexToFloatingComplex: { 5074 if (!Visit(E->getSubExpr())) 5075 return false; 5076 5077 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 5078 QualType From 5079 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 5080 Result.makeComplexFloat(); 5081 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 5082 To, Result.FloatReal) && 5083 HandleIntToFloatCast(Info, E, From, Result.IntImag, 5084 To, Result.FloatImag); 5085 } 5086 } 5087 5088 llvm_unreachable("unknown cast resulting in complex value"); 5089 } 5090 5091 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 5092 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 5093 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5094 5095 if (!Visit(E->getLHS())) 5096 return false; 5097 5098 ComplexValue RHS; 5099 if (!EvaluateComplex(E->getRHS(), RHS, Info)) 5100 return false; 5101 5102 assert(Result.isComplexFloat() == RHS.isComplexFloat() && 5103 "Invalid operands to binary operator."); 5104 switch (E->getOpcode()) { 5105 default: return Error(E); 5106 case BO_Add: 5107 if (Result.isComplexFloat()) { 5108 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 5109 APFloat::rmNearestTiesToEven); 5110 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 5111 APFloat::rmNearestTiesToEven); 5112 } else { 5113 Result.getComplexIntReal() += RHS.getComplexIntReal(); 5114 Result.getComplexIntImag() += RHS.getComplexIntImag(); 5115 } 5116 break; 5117 case BO_Sub: 5118 if (Result.isComplexFloat()) { 5119 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 5120 APFloat::rmNearestTiesToEven); 5121 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 5122 APFloat::rmNearestTiesToEven); 5123 } else { 5124 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 5125 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 5126 } 5127 break; 5128 case BO_Mul: 5129 if (Result.isComplexFloat()) { 5130 ComplexValue LHS = Result; 5131 APFloat &LHS_r = LHS.getComplexFloatReal(); 5132 APFloat &LHS_i = LHS.getComplexFloatImag(); 5133 APFloat &RHS_r = RHS.getComplexFloatReal(); 5134 APFloat &RHS_i = RHS.getComplexFloatImag(); 5135 5136 APFloat Tmp = LHS_r; 5137 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 5138 Result.getComplexFloatReal() = Tmp; 5139 Tmp = LHS_i; 5140 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 5141 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven); 5142 5143 Tmp = LHS_r; 5144 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 5145 Result.getComplexFloatImag() = Tmp; 5146 Tmp = LHS_i; 5147 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven); 5148 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven); 5149 } else { 5150 ComplexValue LHS = Result; 5151 Result.getComplexIntReal() = 5152 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 5153 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 5154 Result.getComplexIntImag() = 5155 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 5156 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 5157 } 5158 break; 5159 case BO_Div: 5160 if (Result.isComplexFloat()) { 5161 ComplexValue LHS = Result; 5162 APFloat &LHS_r = LHS.getComplexFloatReal(); 5163 APFloat &LHS_i = LHS.getComplexFloatImag(); 5164 APFloat &RHS_r = RHS.getComplexFloatReal(); 5165 APFloat &RHS_i = RHS.getComplexFloatImag(); 5166 APFloat &Res_r = Result.getComplexFloatReal(); 5167 APFloat &Res_i = Result.getComplexFloatImag(); 5168 5169 APFloat Den = RHS_r; 5170 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven); 5171 APFloat Tmp = RHS_i; 5172 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 5173 Den.add(Tmp, APFloat::rmNearestTiesToEven); 5174 5175 Res_r = LHS_r; 5176 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven); 5177 Tmp = LHS_i; 5178 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 5179 Res_r.add(Tmp, APFloat::rmNearestTiesToEven); 5180 Res_r.divide(Den, APFloat::rmNearestTiesToEven); 5181 5182 Res_i = LHS_i; 5183 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven); 5184 Tmp = LHS_r; 5185 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven); 5186 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven); 5187 Res_i.divide(Den, APFloat::rmNearestTiesToEven); 5188 } else { 5189 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 5190 return Error(E, diag::note_expr_divide_by_zero); 5191 5192 ComplexValue LHS = Result; 5193 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 5194 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 5195 Result.getComplexIntReal() = 5196 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 5197 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 5198 Result.getComplexIntImag() = 5199 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 5200 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 5201 } 5202 break; 5203 } 5204 5205 return true; 5206 } 5207 5208 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 5209 // Get the operand value into 'Result'. 5210 if (!Visit(E->getSubExpr())) 5211 return false; 5212 5213 switch (E->getOpcode()) { 5214 default: 5215 return Error(E); 5216 case UO_Extension: 5217 return true; 5218 case UO_Plus: 5219 // The result is always just the subexpr. 5220 return true; 5221 case UO_Minus: 5222 if (Result.isComplexFloat()) { 5223 Result.getComplexFloatReal().changeSign(); 5224 Result.getComplexFloatImag().changeSign(); 5225 } 5226 else { 5227 Result.getComplexIntReal() = -Result.getComplexIntReal(); 5228 Result.getComplexIntImag() = -Result.getComplexIntImag(); 5229 } 5230 return true; 5231 case UO_Not: 5232 if (Result.isComplexFloat()) 5233 Result.getComplexFloatImag().changeSign(); 5234 else 5235 Result.getComplexIntImag() = -Result.getComplexIntImag(); 5236 return true; 5237 } 5238 } 5239 5240 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 5241 if (E->getNumInits() == 2) { 5242 if (E->getType()->isComplexType()) { 5243 Result.makeComplexFloat(); 5244 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 5245 return false; 5246 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 5247 return false; 5248 } else { 5249 Result.makeComplexInt(); 5250 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 5251 return false; 5252 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 5253 return false; 5254 } 5255 return true; 5256 } 5257 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 5258 } 5259 5260 //===----------------------------------------------------------------------===// 5261 // Void expression evaluation, primarily for a cast to void on the LHS of a 5262 // comma operator 5263 //===----------------------------------------------------------------------===// 5264 5265 namespace { 5266 class VoidExprEvaluator 5267 : public ExprEvaluatorBase<VoidExprEvaluator, bool> { 5268 public: 5269 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 5270 5271 bool Success(const CCValue &V, const Expr *e) { return true; } 5272 5273 bool VisitCastExpr(const CastExpr *E) { 5274 switch (E->getCastKind()) { 5275 default: 5276 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5277 case CK_ToVoid: 5278 VisitIgnoredValue(E->getSubExpr()); 5279 return true; 5280 } 5281 } 5282 }; 5283 } // end anonymous namespace 5284 5285 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 5286 assert(E->isRValue() && E->getType()->isVoidType()); 5287 return VoidExprEvaluator(Info).Visit(E); 5288 } 5289 5290 //===----------------------------------------------------------------------===// 5291 // Top level Expr::EvaluateAsRValue method. 5292 //===----------------------------------------------------------------------===// 5293 5294 static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) { 5295 // In C, function designators are not lvalues, but we evaluate them as if they 5296 // are. 5297 if (E->isGLValue() || E->getType()->isFunctionType()) { 5298 LValue LV; 5299 if (!EvaluateLValue(E, LV, Info)) 5300 return false; 5301 LV.moveInto(Result); 5302 } else if (E->getType()->isVectorType()) { 5303 if (!EvaluateVector(E, Result, Info)) 5304 return false; 5305 } else if (E->getType()->isIntegralOrEnumerationType()) { 5306 if (!IntExprEvaluator(Info, Result).Visit(E)) 5307 return false; 5308 } else if (E->getType()->hasPointerRepresentation()) { 5309 LValue LV; 5310 if (!EvaluatePointer(E, LV, Info)) 5311 return false; 5312 LV.moveInto(Result); 5313 } else if (E->getType()->isRealFloatingType()) { 5314 llvm::APFloat F(0.0); 5315 if (!EvaluateFloat(E, F, Info)) 5316 return false; 5317 Result = CCValue(F); 5318 } else if (E->getType()->isAnyComplexType()) { 5319 ComplexValue C; 5320 if (!EvaluateComplex(E, C, Info)) 5321 return false; 5322 C.moveInto(Result); 5323 } else if (E->getType()->isMemberPointerType()) { 5324 MemberPtr P; 5325 if (!EvaluateMemberPointer(E, P, Info)) 5326 return false; 5327 P.moveInto(Result); 5328 return true; 5329 } else if (E->getType()->isArrayType()) { 5330 LValue LV; 5331 LV.set(E, Info.CurrentCall); 5332 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info)) 5333 return false; 5334 Result = Info.CurrentCall->Temporaries[E]; 5335 } else if (E->getType()->isRecordType()) { 5336 LValue LV; 5337 LV.set(E, Info.CurrentCall); 5338 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info)) 5339 return false; 5340 Result = Info.CurrentCall->Temporaries[E]; 5341 } else if (E->getType()->isVoidType()) { 5342 if (Info.getLangOpts().CPlusPlus0x) 5343 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral) 5344 << E->getType(); 5345 else 5346 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 5347 if (!EvaluateVoid(E, Info)) 5348 return false; 5349 } else if (Info.getLangOpts().CPlusPlus0x) { 5350 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType(); 5351 return false; 5352 } else { 5353 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr); 5354 return false; 5355 } 5356 5357 return true; 5358 } 5359 5360 /// EvaluateConstantExpression - Evaluate an expression as a constant expression 5361 /// in-place in an APValue. In some cases, the in-place evaluation is essential, 5362 /// since later initializers for an object can indirectly refer to subobjects 5363 /// which were initialized earlier. 5364 static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info, 5365 const LValue &This, const Expr *E, 5366 CheckConstantExpressionKind CCEK) { 5367 if (!CheckLiteralType(Info, E)) 5368 return false; 5369 5370 if (E->isRValue()) { 5371 // Evaluate arrays and record types in-place, so that later initializers can 5372 // refer to earlier-initialized members of the object. 5373 if (E->getType()->isArrayType()) 5374 return EvaluateArray(E, This, Result, Info); 5375 else if (E->getType()->isRecordType()) 5376 return EvaluateRecord(E, This, Result, Info); 5377 } 5378 5379 // For any other type, in-place evaluation is unimportant. 5380 CCValue CoreConstResult; 5381 return Evaluate(CoreConstResult, Info, E) && 5382 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK); 5383 } 5384 5385 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 5386 /// lvalue-to-rvalue cast if it is an lvalue. 5387 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 5388 if (!CheckLiteralType(Info, E)) 5389 return false; 5390 5391 CCValue Value; 5392 if (!::Evaluate(Value, Info, E)) 5393 return false; 5394 5395 if (E->isGLValue()) { 5396 LValue LV; 5397 LV.setFrom(Value); 5398 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value)) 5399 return false; 5400 } 5401 5402 // Check this core constant expression is a constant expression, and if so, 5403 // convert it to one. 5404 return CheckConstantExpression(Info, E, Value, Result); 5405 } 5406 5407 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 5408 /// any crazy technique (that has nothing to do with language standards) that 5409 /// we want to. If this function returns true, it returns the folded constant 5410 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 5411 /// will be applied to the result. 5412 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { 5413 // Fast-path evaluations of integer literals, since we sometimes see files 5414 // containing vast quantities of these. 5415 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) { 5416 Result.Val = APValue(APSInt(L->getValue(), 5417 L->getType()->isUnsignedIntegerType())); 5418 return true; 5419 } 5420 5421 // FIXME: Evaluating values of large array and record types can cause 5422 // performance problems. Only do so in C++11 for now. 5423 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 5424 !Ctx.getLangOptions().CPlusPlus0x) 5425 return false; 5426 5427 EvalInfo Info(Ctx, Result); 5428 return ::EvaluateAsRValue(Info, this, Result.Val); 5429 } 5430 5431 bool Expr::EvaluateAsBooleanCondition(bool &Result, 5432 const ASTContext &Ctx) const { 5433 EvalResult Scratch; 5434 return EvaluateAsRValue(Scratch, Ctx) && 5435 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx), 5436 Scratch.Val, CCValue::GlobalValue()), 5437 Result); 5438 } 5439 5440 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx, 5441 SideEffectsKind AllowSideEffects) const { 5442 if (!getType()->isIntegralOrEnumerationType()) 5443 return false; 5444 5445 EvalResult ExprResult; 5446 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() || 5447 (!AllowSideEffects && ExprResult.HasSideEffects)) 5448 return false; 5449 5450 Result = ExprResult.Val.getInt(); 5451 return true; 5452 } 5453 5454 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 5455 EvalInfo Info(Ctx, Result); 5456 5457 LValue LV; 5458 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects && 5459 CheckLValueConstantExpression(Info, this, LV, Result.Val, 5460 CCEK_Constant); 5461 } 5462 5463 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 5464 const VarDecl *VD, 5465 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 5466 // FIXME: Evaluating initializers for large array and record types can cause 5467 // performance problems. Only do so in C++11 for now. 5468 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 5469 !Ctx.getLangOptions().CPlusPlus0x) 5470 return false; 5471 5472 Expr::EvalStatus EStatus; 5473 EStatus.Diag = &Notes; 5474 5475 EvalInfo InitInfo(Ctx, EStatus); 5476 InitInfo.setEvaluatingDecl(VD, Value); 5477 5478 if (!CheckLiteralType(InitInfo, this)) 5479 return false; 5480 5481 LValue LVal; 5482 LVal.set(VD); 5483 5484 // C++11 [basic.start.init]p2: 5485 // Variables with static storage duration or thread storage duration shall be 5486 // zero-initialized before any other initialization takes place. 5487 // This behavior is not present in C. 5488 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() && 5489 !VD->getType()->isReferenceType()) { 5490 ImplicitValueInitExpr VIE(VD->getType()); 5491 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE)) 5492 return false; 5493 } 5494 5495 return EvaluateConstantExpression(Value, InitInfo, LVal, this) && 5496 !EStatus.HasSideEffects; 5497 } 5498 5499 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 5500 /// constant folded, but discard the result. 5501 bool Expr::isEvaluatable(const ASTContext &Ctx) const { 5502 EvalResult Result; 5503 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects; 5504 } 5505 5506 bool Expr::HasSideEffects(const ASTContext &Ctx) const { 5507 return HasSideEffect(Ctx).Visit(this); 5508 } 5509 5510 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const { 5511 EvalResult EvalResult; 5512 bool Result = EvaluateAsRValue(EvalResult, Ctx); 5513 (void)Result; 5514 assert(Result && "Could not evaluate expression"); 5515 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 5516 5517 return EvalResult.Val.getInt(); 5518 } 5519 5520 bool Expr::EvalResult::isGlobalLValue() const { 5521 assert(Val.isLValue()); 5522 return IsGlobalLValue(Val.getLValueBase()); 5523 } 5524 5525 5526 /// isIntegerConstantExpr - this recursive routine will test if an expression is 5527 /// an integer constant expression. 5528 5529 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 5530 /// comma, etc 5531 /// 5532 /// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof 5533 /// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer 5534 /// cast+dereference. 5535 5536 // CheckICE - This function does the fundamental ICE checking: the returned 5537 // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation. 5538 // Note that to reduce code duplication, this helper does no evaluation 5539 // itself; the caller checks whether the expression is evaluatable, and 5540 // in the rare cases where CheckICE actually cares about the evaluated 5541 // value, it calls into Evalute. 5542 // 5543 // Meanings of Val: 5544 // 0: This expression is an ICE. 5545 // 1: This expression is not an ICE, but if it isn't evaluated, it's 5546 // a legal subexpression for an ICE. This return value is used to handle 5547 // the comma operator in C99 mode. 5548 // 2: This expression is not an ICE, and is not a legal subexpression for one. 5549 5550 namespace { 5551 5552 struct ICEDiag { 5553 unsigned Val; 5554 SourceLocation Loc; 5555 5556 public: 5557 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {} 5558 ICEDiag() : Val(0) {} 5559 }; 5560 5561 } 5562 5563 static ICEDiag NoDiag() { return ICEDiag(); } 5564 5565 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) { 5566 Expr::EvalResult EVResult; 5567 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects || 5568 !EVResult.Val.isInt()) { 5569 return ICEDiag(2, E->getLocStart()); 5570 } 5571 return NoDiag(); 5572 } 5573 5574 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) { 5575 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 5576 if (!E->getType()->isIntegralOrEnumerationType()) { 5577 return ICEDiag(2, E->getLocStart()); 5578 } 5579 5580 switch (E->getStmtClass()) { 5581 #define ABSTRACT_STMT(Node) 5582 #define STMT(Node, Base) case Expr::Node##Class: 5583 #define EXPR(Node, Base) 5584 #include "clang/AST/StmtNodes.inc" 5585 case Expr::PredefinedExprClass: 5586 case Expr::FloatingLiteralClass: 5587 case Expr::ImaginaryLiteralClass: 5588 case Expr::StringLiteralClass: 5589 case Expr::ArraySubscriptExprClass: 5590 case Expr::MemberExprClass: 5591 case Expr::CompoundAssignOperatorClass: 5592 case Expr::CompoundLiteralExprClass: 5593 case Expr::ExtVectorElementExprClass: 5594 case Expr::DesignatedInitExprClass: 5595 case Expr::ImplicitValueInitExprClass: 5596 case Expr::ParenListExprClass: 5597 case Expr::VAArgExprClass: 5598 case Expr::AddrLabelExprClass: 5599 case Expr::StmtExprClass: 5600 case Expr::CXXMemberCallExprClass: 5601 case Expr::CUDAKernelCallExprClass: 5602 case Expr::CXXDynamicCastExprClass: 5603 case Expr::CXXTypeidExprClass: 5604 case Expr::CXXUuidofExprClass: 5605 case Expr::CXXNullPtrLiteralExprClass: 5606 case Expr::CXXThisExprClass: 5607 case Expr::CXXThrowExprClass: 5608 case Expr::CXXNewExprClass: 5609 case Expr::CXXDeleteExprClass: 5610 case Expr::CXXPseudoDestructorExprClass: 5611 case Expr::UnresolvedLookupExprClass: 5612 case Expr::DependentScopeDeclRefExprClass: 5613 case Expr::CXXConstructExprClass: 5614 case Expr::CXXBindTemporaryExprClass: 5615 case Expr::ExprWithCleanupsClass: 5616 case Expr::CXXTemporaryObjectExprClass: 5617 case Expr::CXXUnresolvedConstructExprClass: 5618 case Expr::CXXDependentScopeMemberExprClass: 5619 case Expr::UnresolvedMemberExprClass: 5620 case Expr::ObjCStringLiteralClass: 5621 case Expr::ObjCEncodeExprClass: 5622 case Expr::ObjCMessageExprClass: 5623 case Expr::ObjCSelectorExprClass: 5624 case Expr::ObjCProtocolExprClass: 5625 case Expr::ObjCIvarRefExprClass: 5626 case Expr::ObjCPropertyRefExprClass: 5627 case Expr::ObjCIsaExprClass: 5628 case Expr::ShuffleVectorExprClass: 5629 case Expr::BlockExprClass: 5630 case Expr::BlockDeclRefExprClass: 5631 case Expr::NoStmtClass: 5632 case Expr::OpaqueValueExprClass: 5633 case Expr::PackExpansionExprClass: 5634 case Expr::SubstNonTypeTemplateParmPackExprClass: 5635 case Expr::AsTypeExprClass: 5636 case Expr::ObjCIndirectCopyRestoreExprClass: 5637 case Expr::MaterializeTemporaryExprClass: 5638 case Expr::PseudoObjectExprClass: 5639 case Expr::AtomicExprClass: 5640 case Expr::InitListExprClass: 5641 return ICEDiag(2, E->getLocStart()); 5642 5643 case Expr::SizeOfPackExprClass: 5644 case Expr::GNUNullExprClass: 5645 // GCC considers the GNU __null value to be an integral constant expression. 5646 return NoDiag(); 5647 5648 case Expr::SubstNonTypeTemplateParmExprClass: 5649 return 5650 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 5651 5652 case Expr::ParenExprClass: 5653 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 5654 case Expr::GenericSelectionExprClass: 5655 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 5656 case Expr::IntegerLiteralClass: 5657 case Expr::CharacterLiteralClass: 5658 case Expr::CXXBoolLiteralExprClass: 5659 case Expr::CXXScalarValueInitExprClass: 5660 case Expr::UnaryTypeTraitExprClass: 5661 case Expr::BinaryTypeTraitExprClass: 5662 case Expr::ArrayTypeTraitExprClass: 5663 case Expr::ExpressionTraitExprClass: 5664 case Expr::CXXNoexceptExprClass: 5665 return NoDiag(); 5666 case Expr::CallExprClass: 5667 case Expr::CXXOperatorCallExprClass: { 5668 // C99 6.6/3 allows function calls within unevaluated subexpressions of 5669 // constant expressions, but they can never be ICEs because an ICE cannot 5670 // contain an operand of (pointer to) function type. 5671 const CallExpr *CE = cast<CallExpr>(E); 5672 if (CE->isBuiltinCall()) 5673 return CheckEvalInICE(E, Ctx); 5674 return ICEDiag(2, E->getLocStart()); 5675 } 5676 case Expr::DeclRefExprClass: 5677 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 5678 return NoDiag(); 5679 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) { 5680 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 5681 5682 // Parameter variables are never constants. Without this check, 5683 // getAnyInitializer() can find a default argument, which leads 5684 // to chaos. 5685 if (isa<ParmVarDecl>(D)) 5686 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 5687 5688 // C++ 7.1.5.1p2 5689 // A variable of non-volatile const-qualified integral or enumeration 5690 // type initialized by an ICE can be used in ICEs. 5691 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 5692 if (!Dcl->getType()->isIntegralOrEnumerationType()) 5693 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 5694 5695 const VarDecl *VD; 5696 // Look for a declaration of this variable that has an initializer, and 5697 // check whether it is an ICE. 5698 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 5699 return NoDiag(); 5700 else 5701 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation()); 5702 } 5703 } 5704 return ICEDiag(2, E->getLocStart()); 5705 case Expr::UnaryOperatorClass: { 5706 const UnaryOperator *Exp = cast<UnaryOperator>(E); 5707 switch (Exp->getOpcode()) { 5708 case UO_PostInc: 5709 case UO_PostDec: 5710 case UO_PreInc: 5711 case UO_PreDec: 5712 case UO_AddrOf: 5713 case UO_Deref: 5714 // C99 6.6/3 allows increment and decrement within unevaluated 5715 // subexpressions of constant expressions, but they can never be ICEs 5716 // because an ICE cannot contain an lvalue operand. 5717 return ICEDiag(2, E->getLocStart()); 5718 case UO_Extension: 5719 case UO_LNot: 5720 case UO_Plus: 5721 case UO_Minus: 5722 case UO_Not: 5723 case UO_Real: 5724 case UO_Imag: 5725 return CheckICE(Exp->getSubExpr(), Ctx); 5726 } 5727 5728 // OffsetOf falls through here. 5729 } 5730 case Expr::OffsetOfExprClass: { 5731 // Note that per C99, offsetof must be an ICE. And AFAIK, using 5732 // EvaluateAsRValue matches the proposed gcc behavior for cases like 5733 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 5734 // compliance: we should warn earlier for offsetof expressions with 5735 // array subscripts that aren't ICEs, and if the array subscripts 5736 // are ICEs, the value of the offsetof must be an integer constant. 5737 return CheckEvalInICE(E, Ctx); 5738 } 5739 case Expr::UnaryExprOrTypeTraitExprClass: { 5740 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 5741 if ((Exp->getKind() == UETT_SizeOf) && 5742 Exp->getTypeOfArgument()->isVariableArrayType()) 5743 return ICEDiag(2, E->getLocStart()); 5744 return NoDiag(); 5745 } 5746 case Expr::BinaryOperatorClass: { 5747 const BinaryOperator *Exp = cast<BinaryOperator>(E); 5748 switch (Exp->getOpcode()) { 5749 case BO_PtrMemD: 5750 case BO_PtrMemI: 5751 case BO_Assign: 5752 case BO_MulAssign: 5753 case BO_DivAssign: 5754 case BO_RemAssign: 5755 case BO_AddAssign: 5756 case BO_SubAssign: 5757 case BO_ShlAssign: 5758 case BO_ShrAssign: 5759 case BO_AndAssign: 5760 case BO_XorAssign: 5761 case BO_OrAssign: 5762 // C99 6.6/3 allows assignments within unevaluated subexpressions of 5763 // constant expressions, but they can never be ICEs because an ICE cannot 5764 // contain an lvalue operand. 5765 return ICEDiag(2, E->getLocStart()); 5766 5767 case BO_Mul: 5768 case BO_Div: 5769 case BO_Rem: 5770 case BO_Add: 5771 case BO_Sub: 5772 case BO_Shl: 5773 case BO_Shr: 5774 case BO_LT: 5775 case BO_GT: 5776 case BO_LE: 5777 case BO_GE: 5778 case BO_EQ: 5779 case BO_NE: 5780 case BO_And: 5781 case BO_Xor: 5782 case BO_Or: 5783 case BO_Comma: { 5784 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 5785 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 5786 if (Exp->getOpcode() == BO_Div || 5787 Exp->getOpcode() == BO_Rem) { 5788 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 5789 // we don't evaluate one. 5790 if (LHSResult.Val == 0 && RHSResult.Val == 0) { 5791 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 5792 if (REval == 0) 5793 return ICEDiag(1, E->getLocStart()); 5794 if (REval.isSigned() && REval.isAllOnesValue()) { 5795 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 5796 if (LEval.isMinSignedValue()) 5797 return ICEDiag(1, E->getLocStart()); 5798 } 5799 } 5800 } 5801 if (Exp->getOpcode() == BO_Comma) { 5802 if (Ctx.getLangOptions().C99) { 5803 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 5804 // if it isn't evaluated. 5805 if (LHSResult.Val == 0 && RHSResult.Val == 0) 5806 return ICEDiag(1, E->getLocStart()); 5807 } else { 5808 // In both C89 and C++, commas in ICEs are illegal. 5809 return ICEDiag(2, E->getLocStart()); 5810 } 5811 } 5812 if (LHSResult.Val >= RHSResult.Val) 5813 return LHSResult; 5814 return RHSResult; 5815 } 5816 case BO_LAnd: 5817 case BO_LOr: { 5818 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 5819 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 5820 if (LHSResult.Val == 0 && RHSResult.Val == 1) { 5821 // Rare case where the RHS has a comma "side-effect"; we need 5822 // to actually check the condition to see whether the side 5823 // with the comma is evaluated. 5824 if ((Exp->getOpcode() == BO_LAnd) != 5825 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 5826 return RHSResult; 5827 return NoDiag(); 5828 } 5829 5830 if (LHSResult.Val >= RHSResult.Val) 5831 return LHSResult; 5832 return RHSResult; 5833 } 5834 } 5835 } 5836 case Expr::ImplicitCastExprClass: 5837 case Expr::CStyleCastExprClass: 5838 case Expr::CXXFunctionalCastExprClass: 5839 case Expr::CXXStaticCastExprClass: 5840 case Expr::CXXReinterpretCastExprClass: 5841 case Expr::CXXConstCastExprClass: 5842 case Expr::ObjCBridgedCastExprClass: { 5843 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 5844 if (isa<ExplicitCastExpr>(E)) { 5845 if (const FloatingLiteral *FL 5846 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 5847 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 5848 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 5849 APSInt IgnoredVal(DestWidth, !DestSigned); 5850 bool Ignored; 5851 // If the value does not fit in the destination type, the behavior is 5852 // undefined, so we are not required to treat it as a constant 5853 // expression. 5854 if (FL->getValue().convertToInteger(IgnoredVal, 5855 llvm::APFloat::rmTowardZero, 5856 &Ignored) & APFloat::opInvalidOp) 5857 return ICEDiag(2, E->getLocStart()); 5858 return NoDiag(); 5859 } 5860 } 5861 switch (cast<CastExpr>(E)->getCastKind()) { 5862 case CK_LValueToRValue: 5863 case CK_AtomicToNonAtomic: 5864 case CK_NonAtomicToAtomic: 5865 case CK_NoOp: 5866 case CK_IntegralToBoolean: 5867 case CK_IntegralCast: 5868 return CheckICE(SubExpr, Ctx); 5869 default: 5870 return ICEDiag(2, E->getLocStart()); 5871 } 5872 } 5873 case Expr::BinaryConditionalOperatorClass: { 5874 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 5875 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 5876 if (CommonResult.Val == 2) return CommonResult; 5877 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 5878 if (FalseResult.Val == 2) return FalseResult; 5879 if (CommonResult.Val == 1) return CommonResult; 5880 if (FalseResult.Val == 1 && 5881 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag(); 5882 return FalseResult; 5883 } 5884 case Expr::ConditionalOperatorClass: { 5885 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 5886 // If the condition (ignoring parens) is a __builtin_constant_p call, 5887 // then only the true side is actually considered in an integer constant 5888 // expression, and it is fully evaluated. This is an important GNU 5889 // extension. See GCC PR38377 for discussion. 5890 if (const CallExpr *CallCE 5891 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 5892 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) 5893 return CheckEvalInICE(E, Ctx); 5894 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 5895 if (CondResult.Val == 2) 5896 return CondResult; 5897 5898 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 5899 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 5900 5901 if (TrueResult.Val == 2) 5902 return TrueResult; 5903 if (FalseResult.Val == 2) 5904 return FalseResult; 5905 if (CondResult.Val == 1) 5906 return CondResult; 5907 if (TrueResult.Val == 0 && FalseResult.Val == 0) 5908 return NoDiag(); 5909 // Rare case where the diagnostics depend on which side is evaluated 5910 // Note that if we get here, CondResult is 0, and at least one of 5911 // TrueResult and FalseResult is non-zero. 5912 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) { 5913 return FalseResult; 5914 } 5915 return TrueResult; 5916 } 5917 case Expr::CXXDefaultArgExprClass: 5918 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 5919 case Expr::ChooseExprClass: { 5920 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx); 5921 } 5922 } 5923 5924 llvm_unreachable("Invalid StmtClass!"); 5925 } 5926 5927 /// Evaluate an expression as a C++11 integral constant expression. 5928 static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx, 5929 const Expr *E, 5930 llvm::APSInt *Value, 5931 SourceLocation *Loc) { 5932 if (!E->getType()->isIntegralOrEnumerationType()) { 5933 if (Loc) *Loc = E->getExprLoc(); 5934 return false; 5935 } 5936 5937 APValue Result; 5938 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 5939 return false; 5940 5941 assert(Result.isInt() && "pointer cast to int is not an ICE"); 5942 if (Value) *Value = Result.getInt(); 5943 return true; 5944 } 5945 5946 bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const { 5947 if (Ctx.getLangOptions().CPlusPlus0x) 5948 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc); 5949 5950 ICEDiag d = CheckICE(this, Ctx); 5951 if (d.Val != 0) { 5952 if (Loc) *Loc = d.Loc; 5953 return false; 5954 } 5955 return true; 5956 } 5957 5958 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx, 5959 SourceLocation *Loc, bool isEvaluated) const { 5960 if (Ctx.getLangOptions().CPlusPlus0x) 5961 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 5962 5963 if (!isIntegerConstantExpr(Ctx, Loc)) 5964 return false; 5965 if (!EvaluateAsInt(Value, Ctx)) 5966 llvm_unreachable("ICE cannot be evaluated!"); 5967 return true; 5968 } 5969 5970 bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result, 5971 SourceLocation *Loc) const { 5972 // We support this checking in C++98 mode in order to diagnose compatibility 5973 // issues. 5974 assert(Ctx.getLangOptions().CPlusPlus); 5975 5976 Expr::EvalStatus Status; 5977 llvm::SmallVector<PartialDiagnosticAt, 8> Diags; 5978 Status.Diag = &Diags; 5979 EvalInfo Info(Ctx, Status); 5980 5981 APValue Scratch; 5982 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 5983 5984 if (!Diags.empty()) { 5985 IsConstExpr = false; 5986 if (Loc) *Loc = Diags[0].first; 5987 } else if (!IsConstExpr) { 5988 // FIXME: This shouldn't happen. 5989 if (Loc) *Loc = getExprLoc(); 5990 } 5991 5992 return IsConstExpr; 5993 } 5994