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 // Constant expression evaluation produces four main results: 13 // 14 // * A success/failure flag indicating whether constant folding was successful. 15 // This is the 'bool' return value used by most of the code in this file. A 16 // 'false' return value indicates that constant folding has failed, and any 17 // appropriate diagnostic has already been produced. 18 // 19 // * An evaluated result, valid only if constant folding has not failed. 20 // 21 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 23 // where it is possible to determine the evaluated result regardless. 24 // 25 // * A set of notes indicating why the evaluation was not a constant expression 26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 27 // too, why the expression could not be folded. 28 // 29 // If we are checking for a potential constant expression, failure to constant 30 // fold a potential constant sub-expression will be indicated by a 'false' 31 // return value (the expression could not be folded) and no diagnostic (the 32 // expression is not necessarily non-constant). 33 // 34 //===----------------------------------------------------------------------===// 35 36 #include "clang/AST/APValue.h" 37 #include "clang/AST/ASTContext.h" 38 #include "clang/AST/ASTDiagnostic.h" 39 #include "clang/AST/CharUnits.h" 40 #include "clang/AST/Expr.h" 41 #include "clang/AST/RecordLayout.h" 42 #include "clang/AST/StmtVisitor.h" 43 #include "clang/AST/TypeLoc.h" 44 #include "clang/Basic/Builtins.h" 45 #include "clang/Basic/TargetInfo.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using llvm::APSInt; 53 using llvm::APFloat; 54 55 static bool IsGlobalLValue(APValue::LValueBase B); 56 57 namespace { 58 struct LValue; 59 struct CallStackFrame; 60 struct EvalInfo; 61 62 static QualType getType(APValue::LValueBase B) { 63 if (!B) return QualType(); 64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) 65 return D->getType(); 66 67 const Expr *Base = B.get<const Expr*>(); 68 69 // For a materialized temporary, the type of the temporary we materialized 70 // may not be the type of the expression. 71 if (const MaterializeTemporaryExpr *MTE = 72 dyn_cast<MaterializeTemporaryExpr>(Base)) { 73 SmallVector<const Expr *, 2> CommaLHSs; 74 SmallVector<SubobjectAdjustment, 2> Adjustments; 75 const Expr *Temp = MTE->GetTemporaryExpr(); 76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 77 Adjustments); 78 // Keep any cv-qualifiers from the reference if we generated a temporary 79 // for it. 80 if (Inner != Temp) 81 return Inner->getType(); 82 } 83 84 return Base->getType(); 85 } 86 87 /// Get an LValue path entry, which is known to not be an array index, as a 88 /// field or base class. 89 static 90 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) { 91 APValue::BaseOrMemberType Value; 92 Value.setFromOpaqueValue(E.BaseOrMember); 93 return Value; 94 } 95 96 /// Get an LValue path entry, which is known to not be an array index, as a 97 /// field declaration. 98 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 99 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer()); 100 } 101 /// Get an LValue path entry, which is known to not be an array index, as a 102 /// base class declaration. 103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer()); 105 } 106 /// Determine whether this LValue path entry for a base class names a virtual 107 /// base class. 108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 109 return getAsBaseOrMember(E).getInt(); 110 } 111 112 /// Find the path length and type of the most-derived subobject in the given 113 /// path, and find the size of the containing array, if any. 114 static 115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base, 116 ArrayRef<APValue::LValuePathEntry> Path, 117 uint64_t &ArraySize, QualType &Type, 118 bool &IsArray) { 119 unsigned MostDerivedLength = 0; 120 Type = Base; 121 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 122 if (Type->isArrayType()) { 123 const ConstantArrayType *CAT = 124 cast<ConstantArrayType>(Ctx.getAsArrayType(Type)); 125 Type = CAT->getElementType(); 126 ArraySize = CAT->getSize().getZExtValue(); 127 MostDerivedLength = I + 1; 128 IsArray = true; 129 } else if (Type->isAnyComplexType()) { 130 const ComplexType *CT = Type->castAs<ComplexType>(); 131 Type = CT->getElementType(); 132 ArraySize = 2; 133 MostDerivedLength = I + 1; 134 IsArray = true; 135 } else if (const FieldDecl *FD = getAsField(Path[I])) { 136 Type = FD->getType(); 137 ArraySize = 0; 138 MostDerivedLength = I + 1; 139 IsArray = false; 140 } else { 141 // Path[I] describes a base class. 142 ArraySize = 0; 143 IsArray = false; 144 } 145 } 146 return MostDerivedLength; 147 } 148 149 // The order of this enum is important for diagnostics. 150 enum CheckSubobjectKind { 151 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 152 CSK_This, CSK_Real, CSK_Imag 153 }; 154 155 /// A path from a glvalue to a subobject of that glvalue. 156 struct SubobjectDesignator { 157 /// True if the subobject was named in a manner not supported by C++11. Such 158 /// lvalues can still be folded, but they are not core constant expressions 159 /// and we cannot perform lvalue-to-rvalue conversions on them. 160 unsigned Invalid : 1; 161 162 /// Is this a pointer one past the end of an object? 163 unsigned IsOnePastTheEnd : 1; 164 165 /// Indicator of whether the most-derived object is an array element. 166 unsigned MostDerivedIsArrayElement : 1; 167 168 /// The length of the path to the most-derived object of which this is a 169 /// subobject. 170 unsigned MostDerivedPathLength : 29; 171 172 /// The size of the array of which the most-derived object is an element. 173 /// This will always be 0 if the most-derived object is not an array 174 /// element. 0 is not an indicator of whether or not the most-derived object 175 /// is an array, however, because 0-length arrays are allowed. 176 uint64_t MostDerivedArraySize; 177 178 /// The type of the most derived object referred to by this address. 179 QualType MostDerivedType; 180 181 typedef APValue::LValuePathEntry PathEntry; 182 183 /// The entries on the path from the glvalue to the designated subobject. 184 SmallVector<PathEntry, 8> Entries; 185 186 SubobjectDesignator() : Invalid(true) {} 187 188 explicit SubobjectDesignator(QualType T) 189 : Invalid(false), IsOnePastTheEnd(false), 190 MostDerivedIsArrayElement(false), MostDerivedPathLength(0), 191 MostDerivedArraySize(0), MostDerivedType(T) {} 192 193 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 194 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 195 MostDerivedIsArrayElement(false), MostDerivedPathLength(0), 196 MostDerivedArraySize(0) { 197 if (!Invalid) { 198 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 199 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 200 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 201 if (V.getLValueBase()) { 202 bool IsArray = false; 203 MostDerivedPathLength = 204 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()), 205 V.getLValuePath(), MostDerivedArraySize, 206 MostDerivedType, IsArray); 207 MostDerivedIsArrayElement = IsArray; 208 } 209 } 210 } 211 212 void setInvalid() { 213 Invalid = true; 214 Entries.clear(); 215 } 216 217 /// Determine whether this is a one-past-the-end pointer. 218 bool isOnePastTheEnd() const { 219 assert(!Invalid); 220 if (IsOnePastTheEnd) 221 return true; 222 if (MostDerivedIsArrayElement && 223 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize) 224 return true; 225 return false; 226 } 227 228 /// Check that this refers to a valid subobject. 229 bool isValidSubobject() const { 230 if (Invalid) 231 return false; 232 return !isOnePastTheEnd(); 233 } 234 /// Check that this refers to a valid subobject, and if not, produce a 235 /// relevant diagnostic and set the designator as invalid. 236 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 237 238 /// Update this designator to refer to the first element within this array. 239 void addArrayUnchecked(const ConstantArrayType *CAT) { 240 PathEntry Entry; 241 Entry.ArrayIndex = 0; 242 Entries.push_back(Entry); 243 244 // This is a most-derived object. 245 MostDerivedType = CAT->getElementType(); 246 MostDerivedIsArrayElement = true; 247 MostDerivedArraySize = CAT->getSize().getZExtValue(); 248 MostDerivedPathLength = Entries.size(); 249 } 250 /// Update this designator to refer to the given base or member of this 251 /// object. 252 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 253 PathEntry Entry; 254 APValue::BaseOrMemberType Value(D, Virtual); 255 Entry.BaseOrMember = Value.getOpaqueValue(); 256 Entries.push_back(Entry); 257 258 // If this isn't a base class, it's a new most-derived object. 259 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 260 MostDerivedType = FD->getType(); 261 MostDerivedIsArrayElement = false; 262 MostDerivedArraySize = 0; 263 MostDerivedPathLength = Entries.size(); 264 } 265 } 266 /// Update this designator to refer to the given complex component. 267 void addComplexUnchecked(QualType EltTy, bool Imag) { 268 PathEntry Entry; 269 Entry.ArrayIndex = Imag; 270 Entries.push_back(Entry); 271 272 // This is technically a most-derived object, though in practice this 273 // is unlikely to matter. 274 MostDerivedType = EltTy; 275 MostDerivedIsArrayElement = true; 276 MostDerivedArraySize = 2; 277 MostDerivedPathLength = Entries.size(); 278 } 279 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N); 280 /// Add N to the address of this subobject. 281 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) { 282 if (Invalid) return; 283 if (MostDerivedPathLength == Entries.size() && 284 MostDerivedIsArrayElement) { 285 Entries.back().ArrayIndex += N; 286 if (Entries.back().ArrayIndex > MostDerivedArraySize) { 287 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex); 288 setInvalid(); 289 } 290 return; 291 } 292 // [expr.add]p4: For the purposes of these operators, a pointer to a 293 // nonarray object behaves the same as a pointer to the first element of 294 // an array of length one with the type of the object as its element type. 295 if (IsOnePastTheEnd && N == (uint64_t)-1) 296 IsOnePastTheEnd = false; 297 else if (!IsOnePastTheEnd && N == 1) 298 IsOnePastTheEnd = true; 299 else if (N != 0) { 300 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N); 301 setInvalid(); 302 } 303 } 304 }; 305 306 /// A stack frame in the constexpr call stack. 307 struct CallStackFrame { 308 EvalInfo &Info; 309 310 /// Parent - The caller of this stack frame. 311 CallStackFrame *Caller; 312 313 /// CallLoc - The location of the call expression for this call. 314 SourceLocation CallLoc; 315 316 /// Callee - The function which was called. 317 const FunctionDecl *Callee; 318 319 /// Index - The call index of this call. 320 unsigned Index; 321 322 /// This - The binding for the this pointer in this call, if any. 323 const LValue *This; 324 325 /// Arguments - Parameter bindings for this function call, indexed by 326 /// parameters' function scope indices. 327 APValue *Arguments; 328 329 // Note that we intentionally use std::map here so that references to 330 // values are stable. 331 typedef std::map<const void*, APValue> MapTy; 332 typedef MapTy::const_iterator temp_iterator; 333 /// Temporaries - Temporary lvalues materialized within this stack frame. 334 MapTy Temporaries; 335 336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 337 const FunctionDecl *Callee, const LValue *This, 338 APValue *Arguments); 339 ~CallStackFrame(); 340 341 APValue *getTemporary(const void *Key) { 342 MapTy::iterator I = Temporaries.find(Key); 343 return I == Temporaries.end() ? nullptr : &I->second; 344 } 345 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 346 }; 347 348 /// Temporarily override 'this'. 349 class ThisOverrideRAII { 350 public: 351 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 352 : Frame(Frame), OldThis(Frame.This) { 353 if (Enable) 354 Frame.This = NewThis; 355 } 356 ~ThisOverrideRAII() { 357 Frame.This = OldThis; 358 } 359 private: 360 CallStackFrame &Frame; 361 const LValue *OldThis; 362 }; 363 364 /// A partial diagnostic which we might know in advance that we are not going 365 /// to emit. 366 class OptionalDiagnostic { 367 PartialDiagnostic *Diag; 368 369 public: 370 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr) 371 : Diag(Diag) {} 372 373 template<typename T> 374 OptionalDiagnostic &operator<<(const T &v) { 375 if (Diag) 376 *Diag << v; 377 return *this; 378 } 379 380 OptionalDiagnostic &operator<<(const APSInt &I) { 381 if (Diag) { 382 SmallVector<char, 32> Buffer; 383 I.toString(Buffer); 384 *Diag << StringRef(Buffer.data(), Buffer.size()); 385 } 386 return *this; 387 } 388 389 OptionalDiagnostic &operator<<(const APFloat &F) { 390 if (Diag) { 391 // FIXME: Force the precision of the source value down so we don't 392 // print digits which are usually useless (we don't really care here if 393 // we truncate a digit by accident in edge cases). Ideally, 394 // APFloat::toString would automatically print the shortest 395 // representation which rounds to the correct value, but it's a bit 396 // tricky to implement. 397 unsigned precision = 398 llvm::APFloat::semanticsPrecision(F.getSemantics()); 399 precision = (precision * 59 + 195) / 196; 400 SmallVector<char, 32> Buffer; 401 F.toString(Buffer, precision); 402 *Diag << StringRef(Buffer.data(), Buffer.size()); 403 } 404 return *this; 405 } 406 }; 407 408 /// A cleanup, and a flag indicating whether it is lifetime-extended. 409 class Cleanup { 410 llvm::PointerIntPair<APValue*, 1, bool> Value; 411 412 public: 413 Cleanup(APValue *Val, bool IsLifetimeExtended) 414 : Value(Val, IsLifetimeExtended) {} 415 416 bool isLifetimeExtended() const { return Value.getInt(); } 417 void endLifetime() { 418 *Value.getPointer() = APValue(); 419 } 420 }; 421 422 /// EvalInfo - This is a private struct used by the evaluator to capture 423 /// information about a subexpression as it is folded. It retains information 424 /// about the AST context, but also maintains information about the folded 425 /// expression. 426 /// 427 /// If an expression could be evaluated, it is still possible it is not a C 428 /// "integer constant expression" or constant expression. If not, this struct 429 /// captures information about how and why not. 430 /// 431 /// One bit of information passed *into* the request for constant folding 432 /// indicates whether the subexpression is "evaluated" or not according to C 433 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 434 /// evaluate the expression regardless of what the RHS is, but C only allows 435 /// certain things in certain situations. 436 struct EvalInfo { 437 ASTContext &Ctx; 438 439 /// EvalStatus - Contains information about the evaluation. 440 Expr::EvalStatus &EvalStatus; 441 442 /// CurrentCall - The top of the constexpr call stack. 443 CallStackFrame *CurrentCall; 444 445 /// CallStackDepth - The number of calls in the call stack right now. 446 unsigned CallStackDepth; 447 448 /// NextCallIndex - The next call index to assign. 449 unsigned NextCallIndex; 450 451 /// StepsLeft - The remaining number of evaluation steps we're permitted 452 /// to perform. This is essentially a limit for the number of statements 453 /// we will evaluate. 454 unsigned StepsLeft; 455 456 /// BottomFrame - The frame in which evaluation started. This must be 457 /// initialized after CurrentCall and CallStackDepth. 458 CallStackFrame BottomFrame; 459 460 /// A stack of values whose lifetimes end at the end of some surrounding 461 /// evaluation frame. 462 llvm::SmallVector<Cleanup, 16> CleanupStack; 463 464 /// EvaluatingDecl - This is the declaration whose initializer is being 465 /// evaluated, if any. 466 APValue::LValueBase EvaluatingDecl; 467 468 /// EvaluatingDeclValue - This is the value being constructed for the 469 /// declaration whose initializer is being evaluated, if any. 470 APValue *EvaluatingDeclValue; 471 472 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 473 /// notes attached to it will also be stored, otherwise they will not be. 474 bool HasActiveDiagnostic; 475 476 /// \brief Have we emitted a diagnostic explaining why we couldn't constant 477 /// fold (not just why it's not strictly a constant expression)? 478 bool HasFoldFailureDiagnostic; 479 480 /// \brief Whether or not we're currently speculatively evaluating. 481 bool IsSpeculativelyEvaluating; 482 483 enum EvaluationMode { 484 /// Evaluate as a constant expression. Stop if we find that the expression 485 /// is not a constant expression. 486 EM_ConstantExpression, 487 488 /// Evaluate as a potential constant expression. Keep going if we hit a 489 /// construct that we can't evaluate yet (because we don't yet know the 490 /// value of something) but stop if we hit something that could never be 491 /// a constant expression. 492 EM_PotentialConstantExpression, 493 494 /// Fold the expression to a constant. Stop if we hit a side-effect that 495 /// we can't model. 496 EM_ConstantFold, 497 498 /// Evaluate the expression looking for integer overflow and similar 499 /// issues. Don't worry about side-effects, and try to visit all 500 /// subexpressions. 501 EM_EvaluateForOverflow, 502 503 /// Evaluate in any way we know how. Don't worry about side-effects that 504 /// can't be modeled. 505 EM_IgnoreSideEffects, 506 507 /// Evaluate as a constant expression. Stop if we find that the expression 508 /// is not a constant expression. Some expressions can be retried in the 509 /// optimizer if we don't constant fold them here, but in an unevaluated 510 /// context we try to fold them immediately since the optimizer never 511 /// gets a chance to look at it. 512 EM_ConstantExpressionUnevaluated, 513 514 /// Evaluate as a potential constant expression. Keep going if we hit a 515 /// construct that we can't evaluate yet (because we don't yet know the 516 /// value of something) but stop if we hit something that could never be 517 /// a constant expression. Some expressions can be retried in the 518 /// optimizer if we don't constant fold them here, but in an unevaluated 519 /// context we try to fold them immediately since the optimizer never 520 /// gets a chance to look at it. 521 EM_PotentialConstantExpressionUnevaluated, 522 523 /// Evaluate as a constant expression. Continue evaluating if we find a 524 /// MemberExpr with a base that can't be evaluated. 525 EM_DesignatorFold, 526 } EvalMode; 527 528 /// Are we checking whether the expression is a potential constant 529 /// expression? 530 bool checkingPotentialConstantExpression() const { 531 return EvalMode == EM_PotentialConstantExpression || 532 EvalMode == EM_PotentialConstantExpressionUnevaluated; 533 } 534 535 /// Are we checking an expression for overflow? 536 // FIXME: We should check for any kind of undefined or suspicious behavior 537 // in such constructs, not just overflow. 538 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; } 539 540 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 541 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 542 CallStackDepth(0), NextCallIndex(1), 543 StepsLeft(getLangOpts().ConstexprStepLimit), 544 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 545 EvaluatingDecl((const ValueDecl *)nullptr), 546 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 547 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false), 548 EvalMode(Mode) {} 549 550 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 551 EvaluatingDecl = Base; 552 EvaluatingDeclValue = &Value; 553 } 554 555 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 556 557 bool CheckCallLimit(SourceLocation Loc) { 558 // Don't perform any constexpr calls (other than the call we're checking) 559 // when checking a potential constant expression. 560 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 561 return false; 562 if (NextCallIndex == 0) { 563 // NextCallIndex has wrapped around. 564 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 565 return false; 566 } 567 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 568 return true; 569 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 570 << getLangOpts().ConstexprCallDepth; 571 return false; 572 } 573 574 CallStackFrame *getCallFrame(unsigned CallIndex) { 575 assert(CallIndex && "no call index in getCallFrame"); 576 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 577 // be null in this loop. 578 CallStackFrame *Frame = CurrentCall; 579 while (Frame->Index > CallIndex) 580 Frame = Frame->Caller; 581 return (Frame->Index == CallIndex) ? Frame : nullptr; 582 } 583 584 bool nextStep(const Stmt *S) { 585 if (!StepsLeft) { 586 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded); 587 return false; 588 } 589 --StepsLeft; 590 return true; 591 } 592 593 private: 594 /// Add a diagnostic to the diagnostics list. 595 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 596 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 597 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 598 return EvalStatus.Diag->back().second; 599 } 600 601 /// Add notes containing a call stack to the current point of evaluation. 602 void addCallStack(unsigned Limit); 603 604 private: 605 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, 606 unsigned ExtraNotes, bool IsCCEDiag) { 607 608 if (EvalStatus.Diag) { 609 // If we have a prior diagnostic, it will be noting that the expression 610 // isn't a constant expression. This diagnostic is more important, 611 // unless we require this evaluation to produce a constant expression. 612 // 613 // FIXME: We might want to show both diagnostics to the user in 614 // EM_ConstantFold mode. 615 if (!EvalStatus.Diag->empty()) { 616 switch (EvalMode) { 617 case EM_ConstantFold: 618 case EM_IgnoreSideEffects: 619 case EM_EvaluateForOverflow: 620 if (!HasFoldFailureDiagnostic) 621 break; 622 // We've already failed to fold something. Keep that diagnostic. 623 case EM_ConstantExpression: 624 case EM_PotentialConstantExpression: 625 case EM_ConstantExpressionUnevaluated: 626 case EM_PotentialConstantExpressionUnevaluated: 627 case EM_DesignatorFold: 628 HasActiveDiagnostic = false; 629 return OptionalDiagnostic(); 630 } 631 } 632 633 unsigned CallStackNotes = CallStackDepth - 1; 634 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 635 if (Limit) 636 CallStackNotes = std::min(CallStackNotes, Limit + 1); 637 if (checkingPotentialConstantExpression()) 638 CallStackNotes = 0; 639 640 HasActiveDiagnostic = true; 641 HasFoldFailureDiagnostic = !IsCCEDiag; 642 EvalStatus.Diag->clear(); 643 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 644 addDiag(Loc, DiagId); 645 if (!checkingPotentialConstantExpression()) 646 addCallStack(Limit); 647 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 648 } 649 HasActiveDiagnostic = false; 650 return OptionalDiagnostic(); 651 } 652 public: 653 // Diagnose that the evaluation could not be folded (FF => FoldFailure) 654 OptionalDiagnostic 655 FFDiag(SourceLocation Loc, 656 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, 657 unsigned ExtraNotes = 0) { 658 return Diag(Loc, DiagId, ExtraNotes, false); 659 } 660 661 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId 662 = diag::note_invalid_subexpr_in_const_expr, 663 unsigned ExtraNotes = 0) { 664 if (EvalStatus.Diag) 665 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false); 666 HasActiveDiagnostic = false; 667 return OptionalDiagnostic(); 668 } 669 670 /// Diagnose that the evaluation does not produce a C++11 core constant 671 /// expression. 672 /// 673 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or 674 /// EM_PotentialConstantExpression mode and we produce one of these. 675 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 676 = diag::note_invalid_subexpr_in_const_expr, 677 unsigned ExtraNotes = 0) { 678 // Don't override a previous diagnostic. Don't bother collecting 679 // diagnostics if we're evaluating for overflow. 680 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 681 HasActiveDiagnostic = false; 682 return OptionalDiagnostic(); 683 } 684 return Diag(Loc, DiagId, ExtraNotes, true); 685 } 686 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId 687 = diag::note_invalid_subexpr_in_const_expr, 688 unsigned ExtraNotes = 0) { 689 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes); 690 } 691 /// Add a note to a prior diagnostic. 692 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 693 if (!HasActiveDiagnostic) 694 return OptionalDiagnostic(); 695 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 696 } 697 698 /// Add a stack of notes to a prior diagnostic. 699 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 700 if (HasActiveDiagnostic) { 701 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 702 Diags.begin(), Diags.end()); 703 } 704 } 705 706 /// Should we continue evaluation after encountering a side-effect that we 707 /// couldn't model? 708 bool keepEvaluatingAfterSideEffect() { 709 switch (EvalMode) { 710 case EM_PotentialConstantExpression: 711 case EM_PotentialConstantExpressionUnevaluated: 712 case EM_EvaluateForOverflow: 713 case EM_IgnoreSideEffects: 714 return true; 715 716 case EM_ConstantExpression: 717 case EM_ConstantExpressionUnevaluated: 718 case EM_ConstantFold: 719 case EM_DesignatorFold: 720 return false; 721 } 722 llvm_unreachable("Missed EvalMode case"); 723 } 724 725 /// Note that we have had a side-effect, and determine whether we should 726 /// keep evaluating. 727 bool noteSideEffect() { 728 EvalStatus.HasSideEffects = true; 729 return keepEvaluatingAfterSideEffect(); 730 } 731 732 /// Should we continue evaluation after encountering undefined behavior? 733 bool keepEvaluatingAfterUndefinedBehavior() { 734 switch (EvalMode) { 735 case EM_EvaluateForOverflow: 736 case EM_IgnoreSideEffects: 737 case EM_ConstantFold: 738 case EM_DesignatorFold: 739 return true; 740 741 case EM_PotentialConstantExpression: 742 case EM_PotentialConstantExpressionUnevaluated: 743 case EM_ConstantExpression: 744 case EM_ConstantExpressionUnevaluated: 745 return false; 746 } 747 llvm_unreachable("Missed EvalMode case"); 748 } 749 750 /// Note that we hit something that was technically undefined behavior, but 751 /// that we can evaluate past it (such as signed overflow or floating-point 752 /// division by zero.) 753 bool noteUndefinedBehavior() { 754 EvalStatus.HasUndefinedBehavior = true; 755 return keepEvaluatingAfterUndefinedBehavior(); 756 } 757 758 /// Should we continue evaluation as much as possible after encountering a 759 /// construct which can't be reduced to a value? 760 bool keepEvaluatingAfterFailure() { 761 if (!StepsLeft) 762 return false; 763 764 switch (EvalMode) { 765 case EM_PotentialConstantExpression: 766 case EM_PotentialConstantExpressionUnevaluated: 767 case EM_EvaluateForOverflow: 768 return true; 769 770 case EM_ConstantExpression: 771 case EM_ConstantExpressionUnevaluated: 772 case EM_ConstantFold: 773 case EM_IgnoreSideEffects: 774 case EM_DesignatorFold: 775 return false; 776 } 777 llvm_unreachable("Missed EvalMode case"); 778 } 779 780 /// Notes that we failed to evaluate an expression that other expressions 781 /// directly depend on, and determine if we should keep evaluating. This 782 /// should only be called if we actually intend to keep evaluating. 783 /// 784 /// Call noteSideEffect() instead if we may be able to ignore the value that 785 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 786 /// 787 /// (Foo(), 1) // use noteSideEffect 788 /// (Foo() || true) // use noteSideEffect 789 /// Foo() + 1 // use noteFailure 790 LLVM_ATTRIBUTE_UNUSED_RESULT bool noteFailure() { 791 // Failure when evaluating some expression often means there is some 792 // subexpression whose evaluation was skipped. Therefore, (because we 793 // don't track whether we skipped an expression when unwinding after an 794 // evaluation failure) every evaluation failure that bubbles up from a 795 // subexpression implies that a side-effect has potentially happened. We 796 // skip setting the HasSideEffects flag to true until we decide to 797 // continue evaluating after that point, which happens here. 798 bool KeepGoing = keepEvaluatingAfterFailure(); 799 EvalStatus.HasSideEffects |= KeepGoing; 800 return KeepGoing; 801 } 802 803 bool allowInvalidBaseExpr() const { 804 return EvalMode == EM_DesignatorFold; 805 } 806 }; 807 808 /// Object used to treat all foldable expressions as constant expressions. 809 struct FoldConstant { 810 EvalInfo &Info; 811 bool Enabled; 812 bool HadNoPriorDiags; 813 EvalInfo::EvaluationMode OldMode; 814 815 explicit FoldConstant(EvalInfo &Info, bool Enabled) 816 : Info(Info), 817 Enabled(Enabled), 818 HadNoPriorDiags(Info.EvalStatus.Diag && 819 Info.EvalStatus.Diag->empty() && 820 !Info.EvalStatus.HasSideEffects), 821 OldMode(Info.EvalMode) { 822 if (Enabled && 823 (Info.EvalMode == EvalInfo::EM_ConstantExpression || 824 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated)) 825 Info.EvalMode = EvalInfo::EM_ConstantFold; 826 } 827 void keepDiagnostics() { Enabled = false; } 828 ~FoldConstant() { 829 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 830 !Info.EvalStatus.HasSideEffects) 831 Info.EvalStatus.Diag->clear(); 832 Info.EvalMode = OldMode; 833 } 834 }; 835 836 /// RAII object used to treat the current evaluation as the correct pointer 837 /// offset fold for the current EvalMode 838 struct FoldOffsetRAII { 839 EvalInfo &Info; 840 EvalInfo::EvaluationMode OldMode; 841 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject) 842 : Info(Info), OldMode(Info.EvalMode) { 843 if (!Info.checkingPotentialConstantExpression()) 844 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold 845 : EvalInfo::EM_ConstantFold; 846 } 847 848 ~FoldOffsetRAII() { Info.EvalMode = OldMode; } 849 }; 850 851 /// RAII object used to optionally suppress diagnostics and side-effects from 852 /// a speculative evaluation. 853 class SpeculativeEvaluationRAII { 854 /// Pair of EvalInfo, and a bit that stores whether or not we were 855 /// speculatively evaluating when we created this RAII. 856 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval; 857 Expr::EvalStatus Old; 858 859 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 860 InfoAndOldSpecEval = Other.InfoAndOldSpecEval; 861 Old = Other.Old; 862 Other.InfoAndOldSpecEval.setPointer(nullptr); 863 } 864 865 void maybeRestoreState() { 866 EvalInfo *Info = InfoAndOldSpecEval.getPointer(); 867 if (!Info) 868 return; 869 870 Info->EvalStatus = Old; 871 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt(); 872 } 873 874 public: 875 SpeculativeEvaluationRAII() = default; 876 877 SpeculativeEvaluationRAII( 878 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 879 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating), 880 Old(Info.EvalStatus) { 881 Info.EvalStatus.Diag = NewDiag; 882 Info.IsSpeculativelyEvaluating = true; 883 } 884 885 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 886 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 887 moveFromAndCancel(std::move(Other)); 888 } 889 890 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 891 maybeRestoreState(); 892 moveFromAndCancel(std::move(Other)); 893 return *this; 894 } 895 896 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 897 }; 898 899 /// RAII object wrapping a full-expression or block scope, and handling 900 /// the ending of the lifetime of temporaries created within it. 901 template<bool IsFullExpression> 902 class ScopeRAII { 903 EvalInfo &Info; 904 unsigned OldStackSize; 905 public: 906 ScopeRAII(EvalInfo &Info) 907 : Info(Info), OldStackSize(Info.CleanupStack.size()) {} 908 ~ScopeRAII() { 909 // Body moved to a static method to encourage the compiler to inline away 910 // instances of this class. 911 cleanup(Info, OldStackSize); 912 } 913 private: 914 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 915 unsigned NewEnd = OldStackSize; 916 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 917 I != N; ++I) { 918 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 919 // Full-expression cleanup of a lifetime-extended temporary: nothing 920 // to do, just move this cleanup to the right place in the stack. 921 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 922 ++NewEnd; 923 } else { 924 // End the lifetime of the object. 925 Info.CleanupStack[I].endLifetime(); 926 } 927 } 928 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 929 Info.CleanupStack.end()); 930 } 931 }; 932 typedef ScopeRAII<false> BlockScopeRAII; 933 typedef ScopeRAII<true> FullExpressionRAII; 934 } 935 936 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 937 CheckSubobjectKind CSK) { 938 if (Invalid) 939 return false; 940 if (isOnePastTheEnd()) { 941 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 942 << CSK; 943 setInvalid(); 944 return false; 945 } 946 return true; 947 } 948 949 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 950 const Expr *E, uint64_t N) { 951 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 952 Info.CCEDiag(E, diag::note_constexpr_array_index) 953 << static_cast<int>(N) << /*array*/ 0 954 << static_cast<unsigned>(MostDerivedArraySize); 955 else 956 Info.CCEDiag(E, diag::note_constexpr_array_index) 957 << static_cast<int>(N) << /*non-array*/ 1; 958 setInvalid(); 959 } 960 961 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 962 const FunctionDecl *Callee, const LValue *This, 963 APValue *Arguments) 964 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee), 965 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) { 966 Info.CurrentCall = this; 967 ++Info.CallStackDepth; 968 } 969 970 CallStackFrame::~CallStackFrame() { 971 assert(Info.CurrentCall == this && "calls retired out of order"); 972 --Info.CallStackDepth; 973 Info.CurrentCall = Caller; 974 } 975 976 APValue &CallStackFrame::createTemporary(const void *Key, 977 bool IsLifetimeExtended) { 978 APValue &Result = Temporaries[Key]; 979 assert(Result.isUninit() && "temporary created multiple times"); 980 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 981 return Result; 982 } 983 984 static void describeCall(CallStackFrame *Frame, raw_ostream &Out); 985 986 void EvalInfo::addCallStack(unsigned Limit) { 987 // Determine which calls to skip, if any. 988 unsigned ActiveCalls = CallStackDepth - 1; 989 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 990 if (Limit && Limit < ActiveCalls) { 991 SkipStart = Limit / 2 + Limit % 2; 992 SkipEnd = ActiveCalls - Limit / 2; 993 } 994 995 // Walk the call stack and add the diagnostics. 996 unsigned CallIdx = 0; 997 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 998 Frame = Frame->Caller, ++CallIdx) { 999 // Skip this call? 1000 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 1001 if (CallIdx == SkipStart) { 1002 // Note that we're skipping calls. 1003 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 1004 << unsigned(ActiveCalls - Limit); 1005 } 1006 continue; 1007 } 1008 1009 // Use a different note for an inheriting constructor, because from the 1010 // user's perspective it's not really a function at all. 1011 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) { 1012 if (CD->isInheritingConstructor()) { 1013 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here) 1014 << CD->getParent(); 1015 continue; 1016 } 1017 } 1018 1019 SmallVector<char, 128> Buffer; 1020 llvm::raw_svector_ostream Out(Buffer); 1021 describeCall(Frame, Out); 1022 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 1023 } 1024 } 1025 1026 namespace { 1027 struct ComplexValue { 1028 private: 1029 bool IsInt; 1030 1031 public: 1032 APSInt IntReal, IntImag; 1033 APFloat FloatReal, FloatImag; 1034 1035 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {} 1036 1037 void makeComplexFloat() { IsInt = false; } 1038 bool isComplexFloat() const { return !IsInt; } 1039 APFloat &getComplexFloatReal() { return FloatReal; } 1040 APFloat &getComplexFloatImag() { return FloatImag; } 1041 1042 void makeComplexInt() { IsInt = true; } 1043 bool isComplexInt() const { return IsInt; } 1044 APSInt &getComplexIntReal() { return IntReal; } 1045 APSInt &getComplexIntImag() { return IntImag; } 1046 1047 void moveInto(APValue &v) const { 1048 if (isComplexFloat()) 1049 v = APValue(FloatReal, FloatImag); 1050 else 1051 v = APValue(IntReal, IntImag); 1052 } 1053 void setFrom(const APValue &v) { 1054 assert(v.isComplexFloat() || v.isComplexInt()); 1055 if (v.isComplexFloat()) { 1056 makeComplexFloat(); 1057 FloatReal = v.getComplexFloatReal(); 1058 FloatImag = v.getComplexFloatImag(); 1059 } else { 1060 makeComplexInt(); 1061 IntReal = v.getComplexIntReal(); 1062 IntImag = v.getComplexIntImag(); 1063 } 1064 } 1065 }; 1066 1067 struct LValue { 1068 APValue::LValueBase Base; 1069 CharUnits Offset; 1070 unsigned InvalidBase : 1; 1071 unsigned CallIndex : 31; 1072 SubobjectDesignator Designator; 1073 1074 const APValue::LValueBase getLValueBase() const { return Base; } 1075 CharUnits &getLValueOffset() { return Offset; } 1076 const CharUnits &getLValueOffset() const { return Offset; } 1077 unsigned getLValueCallIndex() const { return CallIndex; } 1078 SubobjectDesignator &getLValueDesignator() { return Designator; } 1079 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1080 1081 void moveInto(APValue &V) const { 1082 if (Designator.Invalid) 1083 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex); 1084 else 1085 V = APValue(Base, Offset, Designator.Entries, 1086 Designator.IsOnePastTheEnd, CallIndex); 1087 } 1088 void setFrom(ASTContext &Ctx, const APValue &V) { 1089 assert(V.isLValue()); 1090 Base = V.getLValueBase(); 1091 Offset = V.getLValueOffset(); 1092 InvalidBase = false; 1093 CallIndex = V.getLValueCallIndex(); 1094 Designator = SubobjectDesignator(Ctx, V); 1095 } 1096 1097 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) { 1098 Base = B; 1099 Offset = CharUnits::Zero(); 1100 InvalidBase = BInvalid; 1101 CallIndex = I; 1102 Designator = SubobjectDesignator(getType(B)); 1103 } 1104 1105 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1106 set(B, I, true); 1107 } 1108 1109 // Check that this LValue is not based on a null pointer. If it is, produce 1110 // a diagnostic and mark the designator as invalid. 1111 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1112 CheckSubobjectKind CSK) { 1113 if (Designator.Invalid) 1114 return false; 1115 if (!Base) { 1116 Info.CCEDiag(E, diag::note_constexpr_null_subobject) 1117 << CSK; 1118 Designator.setInvalid(); 1119 return false; 1120 } 1121 return true; 1122 } 1123 1124 // Check this LValue refers to an object. If not, set the designator to be 1125 // invalid and emit a diagnostic. 1126 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1127 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1128 Designator.checkSubobject(Info, E, CSK); 1129 } 1130 1131 void addDecl(EvalInfo &Info, const Expr *E, 1132 const Decl *D, bool Virtual = false) { 1133 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1134 Designator.addDeclUnchecked(D, Virtual); 1135 } 1136 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1137 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1138 Designator.addArrayUnchecked(CAT); 1139 } 1140 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1141 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1142 Designator.addComplexUnchecked(EltTy, Imag); 1143 } 1144 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) { 1145 if (N && checkNullPointer(Info, E, CSK_ArrayIndex)) 1146 Designator.adjustIndex(Info, E, N); 1147 } 1148 }; 1149 1150 struct MemberPtr { 1151 MemberPtr() {} 1152 explicit MemberPtr(const ValueDecl *Decl) : 1153 DeclAndIsDerivedMember(Decl, false), Path() {} 1154 1155 /// The member or (direct or indirect) field referred to by this member 1156 /// pointer, or 0 if this is a null member pointer. 1157 const ValueDecl *getDecl() const { 1158 return DeclAndIsDerivedMember.getPointer(); 1159 } 1160 /// Is this actually a member of some type derived from the relevant class? 1161 bool isDerivedMember() const { 1162 return DeclAndIsDerivedMember.getInt(); 1163 } 1164 /// Get the class which the declaration actually lives in. 1165 const CXXRecordDecl *getContainingRecord() const { 1166 return cast<CXXRecordDecl>( 1167 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1168 } 1169 1170 void moveInto(APValue &V) const { 1171 V = APValue(getDecl(), isDerivedMember(), Path); 1172 } 1173 void setFrom(const APValue &V) { 1174 assert(V.isMemberPointer()); 1175 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1176 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1177 Path.clear(); 1178 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1179 Path.insert(Path.end(), P.begin(), P.end()); 1180 } 1181 1182 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1183 /// whether the member is a member of some class derived from the class type 1184 /// of the member pointer. 1185 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1186 /// Path - The path of base/derived classes from the member declaration's 1187 /// class (exclusive) to the class type of the member pointer (inclusive). 1188 SmallVector<const CXXRecordDecl*, 4> Path; 1189 1190 /// Perform a cast towards the class of the Decl (either up or down the 1191 /// hierarchy). 1192 bool castBack(const CXXRecordDecl *Class) { 1193 assert(!Path.empty()); 1194 const CXXRecordDecl *Expected; 1195 if (Path.size() >= 2) 1196 Expected = Path[Path.size() - 2]; 1197 else 1198 Expected = getContainingRecord(); 1199 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1200 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1201 // if B does not contain the original member and is not a base or 1202 // derived class of the class containing the original member, the result 1203 // of the cast is undefined. 1204 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1205 // (D::*). We consider that to be a language defect. 1206 return false; 1207 } 1208 Path.pop_back(); 1209 return true; 1210 } 1211 /// Perform a base-to-derived member pointer cast. 1212 bool castToDerived(const CXXRecordDecl *Derived) { 1213 if (!getDecl()) 1214 return true; 1215 if (!isDerivedMember()) { 1216 Path.push_back(Derived); 1217 return true; 1218 } 1219 if (!castBack(Derived)) 1220 return false; 1221 if (Path.empty()) 1222 DeclAndIsDerivedMember.setInt(false); 1223 return true; 1224 } 1225 /// Perform a derived-to-base member pointer cast. 1226 bool castToBase(const CXXRecordDecl *Base) { 1227 if (!getDecl()) 1228 return true; 1229 if (Path.empty()) 1230 DeclAndIsDerivedMember.setInt(true); 1231 if (isDerivedMember()) { 1232 Path.push_back(Base); 1233 return true; 1234 } 1235 return castBack(Base); 1236 } 1237 }; 1238 1239 /// Compare two member pointers, which are assumed to be of the same type. 1240 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1241 if (!LHS.getDecl() || !RHS.getDecl()) 1242 return !LHS.getDecl() && !RHS.getDecl(); 1243 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1244 return false; 1245 return LHS.Path == RHS.Path; 1246 } 1247 } 1248 1249 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1250 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1251 const LValue &This, const Expr *E, 1252 bool AllowNonLiteralTypes = false); 1253 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info); 1254 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info); 1255 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1256 EvalInfo &Info); 1257 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1258 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1259 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1260 EvalInfo &Info); 1261 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1262 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1263 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info); 1264 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1265 1266 //===----------------------------------------------------------------------===// 1267 // Misc utilities 1268 //===----------------------------------------------------------------------===// 1269 1270 /// Produce a string describing the given constexpr call. 1271 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) { 1272 unsigned ArgIndex = 0; 1273 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 1274 !isa<CXXConstructorDecl>(Frame->Callee) && 1275 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 1276 1277 if (!IsMemberCall) 1278 Out << *Frame->Callee << '('; 1279 1280 if (Frame->This && IsMemberCall) { 1281 APValue Val; 1282 Frame->This->moveInto(Val); 1283 Val.printPretty(Out, Frame->Info.Ctx, 1284 Frame->This->Designator.MostDerivedType); 1285 // FIXME: Add parens around Val if needed. 1286 Out << "->" << *Frame->Callee << '('; 1287 IsMemberCall = false; 1288 } 1289 1290 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 1291 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 1292 if (ArgIndex > (unsigned)IsMemberCall) 1293 Out << ", "; 1294 1295 const ParmVarDecl *Param = *I; 1296 const APValue &Arg = Frame->Arguments[ArgIndex]; 1297 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 1298 1299 if (ArgIndex == 0 && IsMemberCall) 1300 Out << "->" << *Frame->Callee << '('; 1301 } 1302 1303 Out << ')'; 1304 } 1305 1306 /// Evaluate an expression to see if it had side-effects, and discard its 1307 /// result. 1308 /// \return \c true if the caller should keep evaluating. 1309 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1310 APValue Scratch; 1311 if (!Evaluate(Scratch, Info, E)) 1312 // We don't need the value, but we might have skipped a side effect here. 1313 return Info.noteSideEffect(); 1314 return true; 1315 } 1316 1317 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just 1318 /// return its existing value. 1319 static int64_t getExtValue(const APSInt &Value) { 1320 return Value.isSigned() ? Value.getSExtValue() 1321 : static_cast<int64_t>(Value.getZExtValue()); 1322 } 1323 1324 /// Should this call expression be treated as a string literal? 1325 static bool IsStringLiteralCall(const CallExpr *E) { 1326 unsigned Builtin = E->getBuiltinCallee(); 1327 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1328 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1329 } 1330 1331 static bool IsGlobalLValue(APValue::LValueBase B) { 1332 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1333 // constant expression of pointer type that evaluates to... 1334 1335 // ... a null pointer value, or a prvalue core constant expression of type 1336 // std::nullptr_t. 1337 if (!B) return true; 1338 1339 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1340 // ... the address of an object with static storage duration, 1341 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1342 return VD->hasGlobalStorage(); 1343 // ... the address of a function, 1344 return isa<FunctionDecl>(D); 1345 } 1346 1347 const Expr *E = B.get<const Expr*>(); 1348 switch (E->getStmtClass()) { 1349 default: 1350 return false; 1351 case Expr::CompoundLiteralExprClass: { 1352 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1353 return CLE->isFileScope() && CLE->isLValue(); 1354 } 1355 case Expr::MaterializeTemporaryExprClass: 1356 // A materialized temporary might have been lifetime-extended to static 1357 // storage duration. 1358 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1359 // A string literal has static storage duration. 1360 case Expr::StringLiteralClass: 1361 case Expr::PredefinedExprClass: 1362 case Expr::ObjCStringLiteralClass: 1363 case Expr::ObjCEncodeExprClass: 1364 case Expr::CXXTypeidExprClass: 1365 case Expr::CXXUuidofExprClass: 1366 return true; 1367 case Expr::CallExprClass: 1368 return IsStringLiteralCall(cast<CallExpr>(E)); 1369 // For GCC compatibility, &&label has static storage duration. 1370 case Expr::AddrLabelExprClass: 1371 return true; 1372 // A Block literal expression may be used as the initialization value for 1373 // Block variables at global or local static scope. 1374 case Expr::BlockExprClass: 1375 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1376 case Expr::ImplicitValueInitExprClass: 1377 // FIXME: 1378 // We can never form an lvalue with an implicit value initialization as its 1379 // base through expression evaluation, so these only appear in one case: the 1380 // implicit variable declaration we invent when checking whether a constexpr 1381 // constructor can produce a constant expression. We must assume that such 1382 // an expression might be a global lvalue. 1383 return true; 1384 } 1385 } 1386 1387 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1388 assert(Base && "no location for a null lvalue"); 1389 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1390 if (VD) 1391 Info.Note(VD->getLocation(), diag::note_declared_at); 1392 else 1393 Info.Note(Base.get<const Expr*>()->getExprLoc(), 1394 diag::note_constexpr_temporary_here); 1395 } 1396 1397 /// Check that this reference or pointer core constant expression is a valid 1398 /// value for an address or reference constant expression. Return true if we 1399 /// can fold this expression, whether or not it's a constant expression. 1400 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1401 QualType Type, const LValue &LVal) { 1402 bool IsReferenceType = Type->isReferenceType(); 1403 1404 APValue::LValueBase Base = LVal.getLValueBase(); 1405 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1406 1407 // Check that the object is a global. Note that the fake 'this' object we 1408 // manufacture when checking potential constant expressions is conservatively 1409 // assumed to be global here. 1410 if (!IsGlobalLValue(Base)) { 1411 if (Info.getLangOpts().CPlusPlus11) { 1412 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1413 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1414 << IsReferenceType << !Designator.Entries.empty() 1415 << !!VD << VD; 1416 NoteLValueLocation(Info, Base); 1417 } else { 1418 Info.FFDiag(Loc); 1419 } 1420 // Don't allow references to temporaries to escape. 1421 return false; 1422 } 1423 assert((Info.checkingPotentialConstantExpression() || 1424 LVal.getLValueCallIndex() == 0) && 1425 "have call index for global lvalue"); 1426 1427 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1428 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1429 // Check if this is a thread-local variable. 1430 if (Var->getTLSKind()) 1431 return false; 1432 1433 // A dllimport variable never acts like a constant. 1434 if (Var->hasAttr<DLLImportAttr>()) 1435 return false; 1436 } 1437 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1438 // __declspec(dllimport) must be handled very carefully: 1439 // We must never initialize an expression with the thunk in C++. 1440 // Doing otherwise would allow the same id-expression to yield 1441 // different addresses for the same function in different translation 1442 // units. However, this means that we must dynamically initialize the 1443 // expression with the contents of the import address table at runtime. 1444 // 1445 // The C language has no notion of ODR; furthermore, it has no notion of 1446 // dynamic initialization. This means that we are permitted to 1447 // perform initialization with the address of the thunk. 1448 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>()) 1449 return false; 1450 } 1451 } 1452 1453 // Allow address constant expressions to be past-the-end pointers. This is 1454 // an extension: the standard requires them to point to an object. 1455 if (!IsReferenceType) 1456 return true; 1457 1458 // A reference constant expression must refer to an object. 1459 if (!Base) { 1460 // FIXME: diagnostic 1461 Info.CCEDiag(Loc); 1462 return true; 1463 } 1464 1465 // Does this refer one past the end of some object? 1466 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1467 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1468 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1469 << !Designator.Entries.empty() << !!VD << VD; 1470 NoteLValueLocation(Info, Base); 1471 } 1472 1473 return true; 1474 } 1475 1476 /// Check that this core constant expression is of literal type, and if not, 1477 /// produce an appropriate diagnostic. 1478 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 1479 const LValue *This = nullptr) { 1480 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 1481 return true; 1482 1483 // C++1y: A constant initializer for an object o [...] may also invoke 1484 // constexpr constructors for o and its subobjects even if those objects 1485 // are of non-literal class types. 1486 if (Info.getLangOpts().CPlusPlus14 && This && 1487 Info.EvaluatingDecl == This->getLValueBase()) 1488 return true; 1489 1490 // Prvalue constant expressions must be of literal types. 1491 if (Info.getLangOpts().CPlusPlus11) 1492 Info.FFDiag(E, diag::note_constexpr_nonliteral) 1493 << E->getType(); 1494 else 1495 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1496 return false; 1497 } 1498 1499 /// Check that this core constant expression value is a valid value for a 1500 /// constant expression. If not, report an appropriate diagnostic. Does not 1501 /// check that the expression is of literal type. 1502 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 1503 QualType Type, const APValue &Value) { 1504 if (Value.isUninit()) { 1505 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 1506 << true << Type; 1507 return false; 1508 } 1509 1510 // We allow _Atomic(T) to be initialized from anything that T can be 1511 // initialized from. 1512 if (const AtomicType *AT = Type->getAs<AtomicType>()) 1513 Type = AT->getValueType(); 1514 1515 // Core issue 1454: For a literal constant expression of array or class type, 1516 // each subobject of its value shall have been initialized by a constant 1517 // expression. 1518 if (Value.isArray()) { 1519 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 1520 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 1521 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 1522 Value.getArrayInitializedElt(I))) 1523 return false; 1524 } 1525 if (!Value.hasArrayFiller()) 1526 return true; 1527 return CheckConstantExpression(Info, DiagLoc, EltTy, 1528 Value.getArrayFiller()); 1529 } 1530 if (Value.isUnion() && Value.getUnionField()) { 1531 return CheckConstantExpression(Info, DiagLoc, 1532 Value.getUnionField()->getType(), 1533 Value.getUnionValue()); 1534 } 1535 if (Value.isStruct()) { 1536 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 1537 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 1538 unsigned BaseIndex = 0; 1539 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 1540 End = CD->bases_end(); I != End; ++I, ++BaseIndex) { 1541 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1542 Value.getStructBase(BaseIndex))) 1543 return false; 1544 } 1545 } 1546 for (const auto *I : RD->fields()) { 1547 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1548 Value.getStructField(I->getFieldIndex()))) 1549 return false; 1550 } 1551 } 1552 1553 if (Value.isLValue()) { 1554 LValue LVal; 1555 LVal.setFrom(Info.Ctx, Value); 1556 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal); 1557 } 1558 1559 // Everything else is fine. 1560 return true; 1561 } 1562 1563 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1564 return LVal.Base.dyn_cast<const ValueDecl*>(); 1565 } 1566 1567 static bool IsLiteralLValue(const LValue &Value) { 1568 if (Value.CallIndex) 1569 return false; 1570 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1571 return E && !isa<MaterializeTemporaryExpr>(E); 1572 } 1573 1574 static bool IsWeakLValue(const LValue &Value) { 1575 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1576 return Decl && Decl->isWeak(); 1577 } 1578 1579 static bool isZeroSized(const LValue &Value) { 1580 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1581 if (Decl && isa<VarDecl>(Decl)) { 1582 QualType Ty = Decl->getType(); 1583 if (Ty->isArrayType()) 1584 return Ty->isIncompleteType() || 1585 Decl->getASTContext().getTypeSize(Ty) == 0; 1586 } 1587 return false; 1588 } 1589 1590 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 1591 // A null base expression indicates a null pointer. These are always 1592 // evaluatable, and they are false unless the offset is zero. 1593 if (!Value.getLValueBase()) { 1594 Result = !Value.getLValueOffset().isZero(); 1595 return true; 1596 } 1597 1598 // We have a non-null base. These are generally known to be true, but if it's 1599 // a weak declaration it can be null at runtime. 1600 Result = true; 1601 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 1602 return !Decl || !Decl->isWeak(); 1603 } 1604 1605 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 1606 switch (Val.getKind()) { 1607 case APValue::Uninitialized: 1608 return false; 1609 case APValue::Int: 1610 Result = Val.getInt().getBoolValue(); 1611 return true; 1612 case APValue::Float: 1613 Result = !Val.getFloat().isZero(); 1614 return true; 1615 case APValue::ComplexInt: 1616 Result = Val.getComplexIntReal().getBoolValue() || 1617 Val.getComplexIntImag().getBoolValue(); 1618 return true; 1619 case APValue::ComplexFloat: 1620 Result = !Val.getComplexFloatReal().isZero() || 1621 !Val.getComplexFloatImag().isZero(); 1622 return true; 1623 case APValue::LValue: 1624 return EvalPointerValueAsBool(Val, Result); 1625 case APValue::MemberPointer: 1626 Result = Val.getMemberPointerDecl(); 1627 return true; 1628 case APValue::Vector: 1629 case APValue::Array: 1630 case APValue::Struct: 1631 case APValue::Union: 1632 case APValue::AddrLabelDiff: 1633 return false; 1634 } 1635 1636 llvm_unreachable("unknown APValue kind"); 1637 } 1638 1639 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 1640 EvalInfo &Info) { 1641 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 1642 APValue Val; 1643 if (!Evaluate(Val, Info, E)) 1644 return false; 1645 return HandleConversionToBool(Val, Result); 1646 } 1647 1648 template<typename T> 1649 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 1650 const T &SrcValue, QualType DestType) { 1651 Info.CCEDiag(E, diag::note_constexpr_overflow) 1652 << SrcValue << DestType; 1653 return Info.noteUndefinedBehavior(); 1654 } 1655 1656 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 1657 QualType SrcType, const APFloat &Value, 1658 QualType DestType, APSInt &Result) { 1659 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 1660 // Determine whether we are converting to unsigned or signed. 1661 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 1662 1663 Result = APSInt(DestWidth, !DestSigned); 1664 bool ignored; 1665 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 1666 & APFloat::opInvalidOp) 1667 return HandleOverflow(Info, E, Value, DestType); 1668 return true; 1669 } 1670 1671 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 1672 QualType SrcType, QualType DestType, 1673 APFloat &Result) { 1674 APFloat Value = Result; 1675 bool ignored; 1676 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 1677 APFloat::rmNearestTiesToEven, &ignored) 1678 & APFloat::opOverflow) 1679 return HandleOverflow(Info, E, Value, DestType); 1680 return true; 1681 } 1682 1683 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 1684 QualType DestType, QualType SrcType, 1685 const APSInt &Value) { 1686 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 1687 APSInt Result = Value; 1688 // Figure out if this is a truncate, extend or noop cast. 1689 // If the input is signed, do a sign extend, noop, or truncate. 1690 Result = Result.extOrTrunc(DestWidth); 1691 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 1692 return Result; 1693 } 1694 1695 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 1696 QualType SrcType, const APSInt &Value, 1697 QualType DestType, APFloat &Result) { 1698 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 1699 if (Result.convertFromAPInt(Value, Value.isSigned(), 1700 APFloat::rmNearestTiesToEven) 1701 & APFloat::opOverflow) 1702 return HandleOverflow(Info, E, Value, DestType); 1703 return true; 1704 } 1705 1706 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 1707 APValue &Value, const FieldDecl *FD) { 1708 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 1709 1710 if (!Value.isInt()) { 1711 // Trying to store a pointer-cast-to-integer into a bitfield. 1712 // FIXME: In this case, we should provide the diagnostic for casting 1713 // a pointer to an integer. 1714 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 1715 Info.FFDiag(E); 1716 return false; 1717 } 1718 1719 APSInt &Int = Value.getInt(); 1720 unsigned OldBitWidth = Int.getBitWidth(); 1721 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 1722 if (NewBitWidth < OldBitWidth) 1723 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 1724 return true; 1725 } 1726 1727 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 1728 llvm::APInt &Res) { 1729 APValue SVal; 1730 if (!Evaluate(SVal, Info, E)) 1731 return false; 1732 if (SVal.isInt()) { 1733 Res = SVal.getInt(); 1734 return true; 1735 } 1736 if (SVal.isFloat()) { 1737 Res = SVal.getFloat().bitcastToAPInt(); 1738 return true; 1739 } 1740 if (SVal.isVector()) { 1741 QualType VecTy = E->getType(); 1742 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 1743 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 1744 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 1745 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 1746 Res = llvm::APInt::getNullValue(VecSize); 1747 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 1748 APValue &Elt = SVal.getVectorElt(i); 1749 llvm::APInt EltAsInt; 1750 if (Elt.isInt()) { 1751 EltAsInt = Elt.getInt(); 1752 } else if (Elt.isFloat()) { 1753 EltAsInt = Elt.getFloat().bitcastToAPInt(); 1754 } else { 1755 // Don't try to handle vectors of anything other than int or float 1756 // (not sure if it's possible to hit this case). 1757 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1758 return false; 1759 } 1760 unsigned BaseEltSize = EltAsInt.getBitWidth(); 1761 if (BigEndian) 1762 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 1763 else 1764 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 1765 } 1766 return true; 1767 } 1768 // Give up if the input isn't an int, float, or vector. For example, we 1769 // reject "(v4i16)(intptr_t)&a". 1770 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1771 return false; 1772 } 1773 1774 /// Perform the given integer operation, which is known to need at most BitWidth 1775 /// bits, and check for overflow in the original type (if that type was not an 1776 /// unsigned type). 1777 template<typename Operation> 1778 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 1779 const APSInt &LHS, const APSInt &RHS, 1780 unsigned BitWidth, Operation Op, 1781 APSInt &Result) { 1782 if (LHS.isUnsigned()) { 1783 Result = Op(LHS, RHS); 1784 return true; 1785 } 1786 1787 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 1788 Result = Value.trunc(LHS.getBitWidth()); 1789 if (Result.extend(BitWidth) != Value) { 1790 if (Info.checkingForOverflow()) 1791 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 1792 diag::warn_integer_constant_overflow) 1793 << Result.toString(10) << E->getType(); 1794 else 1795 return HandleOverflow(Info, E, Value, E->getType()); 1796 } 1797 return true; 1798 } 1799 1800 /// Perform the given binary integer operation. 1801 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 1802 BinaryOperatorKind Opcode, APSInt RHS, 1803 APSInt &Result) { 1804 switch (Opcode) { 1805 default: 1806 Info.FFDiag(E); 1807 return false; 1808 case BO_Mul: 1809 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 1810 std::multiplies<APSInt>(), Result); 1811 case BO_Add: 1812 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 1813 std::plus<APSInt>(), Result); 1814 case BO_Sub: 1815 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 1816 std::minus<APSInt>(), Result); 1817 case BO_And: Result = LHS & RHS; return true; 1818 case BO_Xor: Result = LHS ^ RHS; return true; 1819 case BO_Or: Result = LHS | RHS; return true; 1820 case BO_Div: 1821 case BO_Rem: 1822 if (RHS == 0) { 1823 Info.FFDiag(E, diag::note_expr_divide_by_zero); 1824 return false; 1825 } 1826 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 1827 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 1828 // this operation and gives the two's complement result. 1829 if (RHS.isNegative() && RHS.isAllOnesValue() && 1830 LHS.isSigned() && LHS.isMinSignedValue()) 1831 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 1832 E->getType()); 1833 return true; 1834 case BO_Shl: { 1835 if (Info.getLangOpts().OpenCL) 1836 // OpenCL 6.3j: shift values are effectively % word size of LHS. 1837 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 1838 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 1839 RHS.isUnsigned()); 1840 else if (RHS.isSigned() && RHS.isNegative()) { 1841 // During constant-folding, a negative shift is an opposite shift. Such 1842 // a shift is not a constant expression. 1843 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 1844 RHS = -RHS; 1845 goto shift_right; 1846 } 1847 shift_left: 1848 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 1849 // the shifted type. 1850 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 1851 if (SA != RHS) { 1852 Info.CCEDiag(E, diag::note_constexpr_large_shift) 1853 << RHS << E->getType() << LHS.getBitWidth(); 1854 } else if (LHS.isSigned()) { 1855 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 1856 // operand, and must not overflow the corresponding unsigned type. 1857 if (LHS.isNegative()) 1858 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 1859 else if (LHS.countLeadingZeros() < SA) 1860 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 1861 } 1862 Result = LHS << SA; 1863 return true; 1864 } 1865 case BO_Shr: { 1866 if (Info.getLangOpts().OpenCL) 1867 // OpenCL 6.3j: shift values are effectively % word size of LHS. 1868 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 1869 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 1870 RHS.isUnsigned()); 1871 else if (RHS.isSigned() && RHS.isNegative()) { 1872 // During constant-folding, a negative shift is an opposite shift. Such a 1873 // shift is not a constant expression. 1874 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 1875 RHS = -RHS; 1876 goto shift_left; 1877 } 1878 shift_right: 1879 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 1880 // shifted type. 1881 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 1882 if (SA != RHS) 1883 Info.CCEDiag(E, diag::note_constexpr_large_shift) 1884 << RHS << E->getType() << LHS.getBitWidth(); 1885 Result = LHS >> SA; 1886 return true; 1887 } 1888 1889 case BO_LT: Result = LHS < RHS; return true; 1890 case BO_GT: Result = LHS > RHS; return true; 1891 case BO_LE: Result = LHS <= RHS; return true; 1892 case BO_GE: Result = LHS >= RHS; return true; 1893 case BO_EQ: Result = LHS == RHS; return true; 1894 case BO_NE: Result = LHS != RHS; return true; 1895 } 1896 } 1897 1898 /// Perform the given binary floating-point operation, in-place, on LHS. 1899 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 1900 APFloat &LHS, BinaryOperatorKind Opcode, 1901 const APFloat &RHS) { 1902 switch (Opcode) { 1903 default: 1904 Info.FFDiag(E); 1905 return false; 1906 case BO_Mul: 1907 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 1908 break; 1909 case BO_Add: 1910 LHS.add(RHS, APFloat::rmNearestTiesToEven); 1911 break; 1912 case BO_Sub: 1913 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 1914 break; 1915 case BO_Div: 1916 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 1917 break; 1918 } 1919 1920 if (LHS.isInfinity() || LHS.isNaN()) { 1921 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 1922 return Info.noteUndefinedBehavior(); 1923 } 1924 return true; 1925 } 1926 1927 /// Cast an lvalue referring to a base subobject to a derived class, by 1928 /// truncating the lvalue's path to the given length. 1929 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 1930 const RecordDecl *TruncatedType, 1931 unsigned TruncatedElements) { 1932 SubobjectDesignator &D = Result.Designator; 1933 1934 // Check we actually point to a derived class object. 1935 if (TruncatedElements == D.Entries.size()) 1936 return true; 1937 assert(TruncatedElements >= D.MostDerivedPathLength && 1938 "not casting to a derived class"); 1939 if (!Result.checkSubobject(Info, E, CSK_Derived)) 1940 return false; 1941 1942 // Truncate the path to the subobject, and remove any derived-to-base offsets. 1943 const RecordDecl *RD = TruncatedType; 1944 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 1945 if (RD->isInvalidDecl()) return false; 1946 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 1947 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 1948 if (isVirtualBaseClass(D.Entries[I])) 1949 Result.Offset -= Layout.getVBaseClassOffset(Base); 1950 else 1951 Result.Offset -= Layout.getBaseClassOffset(Base); 1952 RD = Base; 1953 } 1954 D.Entries.resize(TruncatedElements); 1955 return true; 1956 } 1957 1958 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 1959 const CXXRecordDecl *Derived, 1960 const CXXRecordDecl *Base, 1961 const ASTRecordLayout *RL = nullptr) { 1962 if (!RL) { 1963 if (Derived->isInvalidDecl()) return false; 1964 RL = &Info.Ctx.getASTRecordLayout(Derived); 1965 } 1966 1967 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 1968 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 1969 return true; 1970 } 1971 1972 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 1973 const CXXRecordDecl *DerivedDecl, 1974 const CXXBaseSpecifier *Base) { 1975 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 1976 1977 if (!Base->isVirtual()) 1978 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 1979 1980 SubobjectDesignator &D = Obj.Designator; 1981 if (D.Invalid) 1982 return false; 1983 1984 // Extract most-derived object and corresponding type. 1985 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 1986 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 1987 return false; 1988 1989 // Find the virtual base class. 1990 if (DerivedDecl->isInvalidDecl()) return false; 1991 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 1992 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 1993 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 1994 return true; 1995 } 1996 1997 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 1998 QualType Type, LValue &Result) { 1999 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2000 PathE = E->path_end(); 2001 PathI != PathE; ++PathI) { 2002 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2003 *PathI)) 2004 return false; 2005 Type = (*PathI)->getType(); 2006 } 2007 return true; 2008 } 2009 2010 /// Update LVal to refer to the given field, which must be a member of the type 2011 /// currently described by LVal. 2012 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2013 const FieldDecl *FD, 2014 const ASTRecordLayout *RL = nullptr) { 2015 if (!RL) { 2016 if (FD->getParent()->isInvalidDecl()) return false; 2017 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2018 } 2019 2020 unsigned I = FD->getFieldIndex(); 2021 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)); 2022 LVal.addDecl(Info, E, FD); 2023 return true; 2024 } 2025 2026 /// Update LVal to refer to the given indirect field. 2027 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2028 LValue &LVal, 2029 const IndirectFieldDecl *IFD) { 2030 for (const auto *C : IFD->chain()) 2031 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2032 return false; 2033 return true; 2034 } 2035 2036 /// Get the size of the given type in char units. 2037 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2038 QualType Type, CharUnits &Size) { 2039 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2040 // extension. 2041 if (Type->isVoidType() || Type->isFunctionType()) { 2042 Size = CharUnits::One(); 2043 return true; 2044 } 2045 2046 if (Type->isDependentType()) { 2047 Info.FFDiag(Loc); 2048 return false; 2049 } 2050 2051 if (!Type->isConstantSizeType()) { 2052 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2053 // FIXME: Better diagnostic. 2054 Info.FFDiag(Loc); 2055 return false; 2056 } 2057 2058 Size = Info.Ctx.getTypeSizeInChars(Type); 2059 return true; 2060 } 2061 2062 /// Update a pointer value to model pointer arithmetic. 2063 /// \param Info - Information about the ongoing evaluation. 2064 /// \param E - The expression being evaluated, for diagnostic purposes. 2065 /// \param LVal - The pointer value to be updated. 2066 /// \param EltTy - The pointee type represented by LVal. 2067 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2068 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2069 LValue &LVal, QualType EltTy, 2070 int64_t Adjustment) { 2071 CharUnits SizeOfPointee; 2072 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2073 return false; 2074 2075 // Compute the new offset in the appropriate width. 2076 LVal.Offset += Adjustment * SizeOfPointee; 2077 LVal.adjustIndex(Info, E, Adjustment); 2078 return true; 2079 } 2080 2081 /// Update an lvalue to refer to a component of a complex number. 2082 /// \param Info - Information about the ongoing evaluation. 2083 /// \param LVal - The lvalue to be updated. 2084 /// \param EltTy - The complex number's component type. 2085 /// \param Imag - False for the real component, true for the imaginary. 2086 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2087 LValue &LVal, QualType EltTy, 2088 bool Imag) { 2089 if (Imag) { 2090 CharUnits SizeOfComponent; 2091 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2092 return false; 2093 LVal.Offset += SizeOfComponent; 2094 } 2095 LVal.addComplex(Info, E, EltTy, Imag); 2096 return true; 2097 } 2098 2099 /// Try to evaluate the initializer for a variable declaration. 2100 /// 2101 /// \param Info Information about the ongoing evaluation. 2102 /// \param E An expression to be used when printing diagnostics. 2103 /// \param VD The variable whose initializer should be obtained. 2104 /// \param Frame The frame in which the variable was created. Must be null 2105 /// if this variable is not local to the evaluation. 2106 /// \param Result Filled in with a pointer to the value of the variable. 2107 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2108 const VarDecl *VD, CallStackFrame *Frame, 2109 APValue *&Result) { 2110 // If this is a parameter to an active constexpr function call, perform 2111 // argument substitution. 2112 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2113 // Assume arguments of a potential constant expression are unknown 2114 // constant expressions. 2115 if (Info.checkingPotentialConstantExpression()) 2116 return false; 2117 if (!Frame || !Frame->Arguments) { 2118 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2119 return false; 2120 } 2121 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2122 return true; 2123 } 2124 2125 // If this is a local variable, dig out its value. 2126 if (Frame) { 2127 Result = Frame->getTemporary(VD); 2128 assert(Result && "missing value for local variable"); 2129 return true; 2130 } 2131 2132 // Dig out the initializer, and use the declaration which it's attached to. 2133 const Expr *Init = VD->getAnyInitializer(VD); 2134 if (!Init || Init->isValueDependent()) { 2135 // If we're checking a potential constant expression, the variable could be 2136 // initialized later. 2137 if (!Info.checkingPotentialConstantExpression()) 2138 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2139 return false; 2140 } 2141 2142 // If we're currently evaluating the initializer of this declaration, use that 2143 // in-flight value. 2144 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2145 Result = Info.EvaluatingDeclValue; 2146 return true; 2147 } 2148 2149 // Never evaluate the initializer of a weak variable. We can't be sure that 2150 // this is the definition which will be used. 2151 if (VD->isWeak()) { 2152 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2153 return false; 2154 } 2155 2156 // Check that we can fold the initializer. In C++, we will have already done 2157 // this in the cases where it matters for conformance. 2158 SmallVector<PartialDiagnosticAt, 8> Notes; 2159 if (!VD->evaluateValue(Notes)) { 2160 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2161 Notes.size() + 1) << VD; 2162 Info.Note(VD->getLocation(), diag::note_declared_at); 2163 Info.addNotes(Notes); 2164 return false; 2165 } else if (!VD->checkInitIsICE()) { 2166 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2167 Notes.size() + 1) << VD; 2168 Info.Note(VD->getLocation(), diag::note_declared_at); 2169 Info.addNotes(Notes); 2170 } 2171 2172 Result = VD->getEvaluatedValue(); 2173 return true; 2174 } 2175 2176 static bool IsConstNonVolatile(QualType T) { 2177 Qualifiers Quals = T.getQualifiers(); 2178 return Quals.hasConst() && !Quals.hasVolatile(); 2179 } 2180 2181 /// Get the base index of the given base class within an APValue representing 2182 /// the given derived class. 2183 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2184 const CXXRecordDecl *Base) { 2185 Base = Base->getCanonicalDecl(); 2186 unsigned Index = 0; 2187 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2188 E = Derived->bases_end(); I != E; ++I, ++Index) { 2189 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2190 return Index; 2191 } 2192 2193 llvm_unreachable("base class missing from derived class's bases list"); 2194 } 2195 2196 /// Extract the value of a character from a string literal. 2197 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2198 uint64_t Index) { 2199 // FIXME: Support ObjCEncodeExpr, MakeStringConstant 2200 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2201 Lit = PE->getFunctionName(); 2202 const StringLiteral *S = cast<StringLiteral>(Lit); 2203 const ConstantArrayType *CAT = 2204 Info.Ctx.getAsConstantArrayType(S->getType()); 2205 assert(CAT && "string literal isn't an array"); 2206 QualType CharType = CAT->getElementType(); 2207 assert(CharType->isIntegerType() && "unexpected character type"); 2208 2209 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2210 CharType->isUnsignedIntegerType()); 2211 if (Index < S->getLength()) 2212 Value = S->getCodeUnit(Index); 2213 return Value; 2214 } 2215 2216 // Expand a string literal into an array of characters. 2217 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit, 2218 APValue &Result) { 2219 const StringLiteral *S = cast<StringLiteral>(Lit); 2220 const ConstantArrayType *CAT = 2221 Info.Ctx.getAsConstantArrayType(S->getType()); 2222 assert(CAT && "string literal isn't an array"); 2223 QualType CharType = CAT->getElementType(); 2224 assert(CharType->isIntegerType() && "unexpected character type"); 2225 2226 unsigned Elts = CAT->getSize().getZExtValue(); 2227 Result = APValue(APValue::UninitArray(), 2228 std::min(S->getLength(), Elts), Elts); 2229 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2230 CharType->isUnsignedIntegerType()); 2231 if (Result.hasArrayFiller()) 2232 Result.getArrayFiller() = APValue(Value); 2233 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2234 Value = S->getCodeUnit(I); 2235 Result.getArrayInitializedElt(I) = APValue(Value); 2236 } 2237 } 2238 2239 // Expand an array so that it has more than Index filled elements. 2240 static void expandArray(APValue &Array, unsigned Index) { 2241 unsigned Size = Array.getArraySize(); 2242 assert(Index < Size); 2243 2244 // Always at least double the number of elements for which we store a value. 2245 unsigned OldElts = Array.getArrayInitializedElts(); 2246 unsigned NewElts = std::max(Index+1, OldElts * 2); 2247 NewElts = std::min(Size, std::max(NewElts, 8u)); 2248 2249 // Copy the data across. 2250 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2251 for (unsigned I = 0; I != OldElts; ++I) 2252 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2253 for (unsigned I = OldElts; I != NewElts; ++I) 2254 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2255 if (NewValue.hasArrayFiller()) 2256 NewValue.getArrayFiller() = Array.getArrayFiller(); 2257 Array.swap(NewValue); 2258 } 2259 2260 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2261 /// conversion. If it's of class type, we may assume that the copy operation 2262 /// is trivial. Note that this is never true for a union type with fields 2263 /// (because the copy always "reads" the active member) and always true for 2264 /// a non-class type. 2265 static bool isReadByLvalueToRvalueConversion(QualType T) { 2266 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2267 if (!RD || (RD->isUnion() && !RD->field_empty())) 2268 return true; 2269 if (RD->isEmpty()) 2270 return false; 2271 2272 for (auto *Field : RD->fields()) 2273 if (isReadByLvalueToRvalueConversion(Field->getType())) 2274 return true; 2275 2276 for (auto &BaseSpec : RD->bases()) 2277 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2278 return true; 2279 2280 return false; 2281 } 2282 2283 /// Diagnose an attempt to read from any unreadable field within the specified 2284 /// type, which might be a class type. 2285 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2286 QualType T) { 2287 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2288 if (!RD) 2289 return false; 2290 2291 if (!RD->hasMutableFields()) 2292 return false; 2293 2294 for (auto *Field : RD->fields()) { 2295 // If we're actually going to read this field in some way, then it can't 2296 // be mutable. If we're in a union, then assigning to a mutable field 2297 // (even an empty one) can change the active member, so that's not OK. 2298 // FIXME: Add core issue number for the union case. 2299 if (Field->isMutable() && 2300 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2301 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2302 Info.Note(Field->getLocation(), diag::note_declared_at); 2303 return true; 2304 } 2305 2306 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2307 return true; 2308 } 2309 2310 for (auto &BaseSpec : RD->bases()) 2311 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2312 return true; 2313 2314 // All mutable fields were empty, and thus not actually read. 2315 return false; 2316 } 2317 2318 /// Kinds of access we can perform on an object, for diagnostics. 2319 enum AccessKinds { 2320 AK_Read, 2321 AK_Assign, 2322 AK_Increment, 2323 AK_Decrement 2324 }; 2325 2326 namespace { 2327 /// A handle to a complete object (an object that is not a subobject of 2328 /// another object). 2329 struct CompleteObject { 2330 /// The value of the complete object. 2331 APValue *Value; 2332 /// The type of the complete object. 2333 QualType Type; 2334 2335 CompleteObject() : Value(nullptr) {} 2336 CompleteObject(APValue *Value, QualType Type) 2337 : Value(Value), Type(Type) { 2338 assert(Value && "missing value for complete object"); 2339 } 2340 2341 explicit operator bool() const { return Value; } 2342 }; 2343 } // end anonymous namespace 2344 2345 /// Find the designated sub-object of an rvalue. 2346 template<typename SubobjectHandler> 2347 typename SubobjectHandler::result_type 2348 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2349 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2350 if (Sub.Invalid) 2351 // A diagnostic will have already been produced. 2352 return handler.failed(); 2353 if (Sub.isOnePastTheEnd()) { 2354 if (Info.getLangOpts().CPlusPlus11) 2355 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2356 << handler.AccessKind; 2357 else 2358 Info.FFDiag(E); 2359 return handler.failed(); 2360 } 2361 2362 APValue *O = Obj.Value; 2363 QualType ObjType = Obj.Type; 2364 const FieldDecl *LastField = nullptr; 2365 2366 // Walk the designator's path to find the subobject. 2367 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 2368 if (O->isUninit()) { 2369 if (!Info.checkingPotentialConstantExpression()) 2370 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind; 2371 return handler.failed(); 2372 } 2373 2374 if (I == N) { 2375 // If we are reading an object of class type, there may still be more 2376 // things we need to check: if there are any mutable subobjects, we 2377 // cannot perform this read. (This only happens when performing a trivial 2378 // copy or assignment.) 2379 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 2380 diagnoseUnreadableFields(Info, E, ObjType)) 2381 return handler.failed(); 2382 2383 if (!handler.found(*O, ObjType)) 2384 return false; 2385 2386 // If we modified a bit-field, truncate it to the right width. 2387 if (handler.AccessKind != AK_Read && 2388 LastField && LastField->isBitField() && 2389 !truncateBitfieldValue(Info, E, *O, LastField)) 2390 return false; 2391 2392 return true; 2393 } 2394 2395 LastField = nullptr; 2396 if (ObjType->isArrayType()) { 2397 // Next subobject is an array element. 2398 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 2399 assert(CAT && "vla in literal type?"); 2400 uint64_t Index = Sub.Entries[I].ArrayIndex; 2401 if (CAT->getSize().ule(Index)) { 2402 // Note, it should not be possible to form a pointer with a valid 2403 // designator which points more than one past the end of the array. 2404 if (Info.getLangOpts().CPlusPlus11) 2405 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2406 << handler.AccessKind; 2407 else 2408 Info.FFDiag(E); 2409 return handler.failed(); 2410 } 2411 2412 ObjType = CAT->getElementType(); 2413 2414 // An array object is represented as either an Array APValue or as an 2415 // LValue which refers to a string literal. 2416 if (O->isLValue()) { 2417 assert(I == N - 1 && "extracting subobject of character?"); 2418 assert(!O->hasLValuePath() || O->getLValuePath().empty()); 2419 if (handler.AccessKind != AK_Read) 2420 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(), 2421 *O); 2422 else 2423 return handler.foundString(*O, ObjType, Index); 2424 } 2425 2426 if (O->getArrayInitializedElts() > Index) 2427 O = &O->getArrayInitializedElt(Index); 2428 else if (handler.AccessKind != AK_Read) { 2429 expandArray(*O, Index); 2430 O = &O->getArrayInitializedElt(Index); 2431 } else 2432 O = &O->getArrayFiller(); 2433 } else if (ObjType->isAnyComplexType()) { 2434 // Next subobject is a complex number. 2435 uint64_t Index = Sub.Entries[I].ArrayIndex; 2436 if (Index > 1) { 2437 if (Info.getLangOpts().CPlusPlus11) 2438 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2439 << handler.AccessKind; 2440 else 2441 Info.FFDiag(E); 2442 return handler.failed(); 2443 } 2444 2445 bool WasConstQualified = ObjType.isConstQualified(); 2446 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2447 if (WasConstQualified) 2448 ObjType.addConst(); 2449 2450 assert(I == N - 1 && "extracting subobject of scalar?"); 2451 if (O->isComplexInt()) { 2452 return handler.found(Index ? O->getComplexIntImag() 2453 : O->getComplexIntReal(), ObjType); 2454 } else { 2455 assert(O->isComplexFloat()); 2456 return handler.found(Index ? O->getComplexFloatImag() 2457 : O->getComplexFloatReal(), ObjType); 2458 } 2459 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 2460 if (Field->isMutable() && handler.AccessKind == AK_Read) { 2461 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 2462 << Field; 2463 Info.Note(Field->getLocation(), diag::note_declared_at); 2464 return handler.failed(); 2465 } 2466 2467 // Next subobject is a class, struct or union field. 2468 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 2469 if (RD->isUnion()) { 2470 const FieldDecl *UnionField = O->getUnionField(); 2471 if (!UnionField || 2472 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 2473 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 2474 << handler.AccessKind << Field << !UnionField << UnionField; 2475 return handler.failed(); 2476 } 2477 O = &O->getUnionValue(); 2478 } else 2479 O = &O->getStructField(Field->getFieldIndex()); 2480 2481 bool WasConstQualified = ObjType.isConstQualified(); 2482 ObjType = Field->getType(); 2483 if (WasConstQualified && !Field->isMutable()) 2484 ObjType.addConst(); 2485 2486 if (ObjType.isVolatileQualified()) { 2487 if (Info.getLangOpts().CPlusPlus) { 2488 // FIXME: Include a description of the path to the volatile subobject. 2489 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2490 << handler.AccessKind << 2 << Field; 2491 Info.Note(Field->getLocation(), diag::note_declared_at); 2492 } else { 2493 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2494 } 2495 return handler.failed(); 2496 } 2497 2498 LastField = Field; 2499 } else { 2500 // Next subobject is a base class. 2501 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 2502 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 2503 O = &O->getStructBase(getBaseIndex(Derived, Base)); 2504 2505 bool WasConstQualified = ObjType.isConstQualified(); 2506 ObjType = Info.Ctx.getRecordType(Base); 2507 if (WasConstQualified) 2508 ObjType.addConst(); 2509 } 2510 } 2511 } 2512 2513 namespace { 2514 struct ExtractSubobjectHandler { 2515 EvalInfo &Info; 2516 APValue &Result; 2517 2518 static const AccessKinds AccessKind = AK_Read; 2519 2520 typedef bool result_type; 2521 bool failed() { return false; } 2522 bool found(APValue &Subobj, QualType SubobjType) { 2523 Result = Subobj; 2524 return true; 2525 } 2526 bool found(APSInt &Value, QualType SubobjType) { 2527 Result = APValue(Value); 2528 return true; 2529 } 2530 bool found(APFloat &Value, QualType SubobjType) { 2531 Result = APValue(Value); 2532 return true; 2533 } 2534 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2535 Result = APValue(extractStringLiteralCharacter( 2536 Info, Subobj.getLValueBase().get<const Expr *>(), Character)); 2537 return true; 2538 } 2539 }; 2540 } // end anonymous namespace 2541 2542 const AccessKinds ExtractSubobjectHandler::AccessKind; 2543 2544 /// Extract the designated sub-object of an rvalue. 2545 static bool extractSubobject(EvalInfo &Info, const Expr *E, 2546 const CompleteObject &Obj, 2547 const SubobjectDesignator &Sub, 2548 APValue &Result) { 2549 ExtractSubobjectHandler Handler = { Info, Result }; 2550 return findSubobject(Info, E, Obj, Sub, Handler); 2551 } 2552 2553 namespace { 2554 struct ModifySubobjectHandler { 2555 EvalInfo &Info; 2556 APValue &NewVal; 2557 const Expr *E; 2558 2559 typedef bool result_type; 2560 static const AccessKinds AccessKind = AK_Assign; 2561 2562 bool checkConst(QualType QT) { 2563 // Assigning to a const object has undefined behavior. 2564 if (QT.isConstQualified()) { 2565 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 2566 return false; 2567 } 2568 return true; 2569 } 2570 2571 bool failed() { return false; } 2572 bool found(APValue &Subobj, QualType SubobjType) { 2573 if (!checkConst(SubobjType)) 2574 return false; 2575 // We've been given ownership of NewVal, so just swap it in. 2576 Subobj.swap(NewVal); 2577 return true; 2578 } 2579 bool found(APSInt &Value, QualType SubobjType) { 2580 if (!checkConst(SubobjType)) 2581 return false; 2582 if (!NewVal.isInt()) { 2583 // Maybe trying to write a cast pointer value into a complex? 2584 Info.FFDiag(E); 2585 return false; 2586 } 2587 Value = NewVal.getInt(); 2588 return true; 2589 } 2590 bool found(APFloat &Value, QualType SubobjType) { 2591 if (!checkConst(SubobjType)) 2592 return false; 2593 Value = NewVal.getFloat(); 2594 return true; 2595 } 2596 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2597 llvm_unreachable("shouldn't encounter string elements with ExpandArrays"); 2598 } 2599 }; 2600 } // end anonymous namespace 2601 2602 const AccessKinds ModifySubobjectHandler::AccessKind; 2603 2604 /// Update the designated sub-object of an rvalue to the given value. 2605 static bool modifySubobject(EvalInfo &Info, const Expr *E, 2606 const CompleteObject &Obj, 2607 const SubobjectDesignator &Sub, 2608 APValue &NewVal) { 2609 ModifySubobjectHandler Handler = { Info, NewVal, E }; 2610 return findSubobject(Info, E, Obj, Sub, Handler); 2611 } 2612 2613 /// Find the position where two subobject designators diverge, or equivalently 2614 /// the length of the common initial subsequence. 2615 static unsigned FindDesignatorMismatch(QualType ObjType, 2616 const SubobjectDesignator &A, 2617 const SubobjectDesignator &B, 2618 bool &WasArrayIndex) { 2619 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 2620 for (/**/; I != N; ++I) { 2621 if (!ObjType.isNull() && 2622 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 2623 // Next subobject is an array element. 2624 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) { 2625 WasArrayIndex = true; 2626 return I; 2627 } 2628 if (ObjType->isAnyComplexType()) 2629 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2630 else 2631 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 2632 } else { 2633 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) { 2634 WasArrayIndex = false; 2635 return I; 2636 } 2637 if (const FieldDecl *FD = getAsField(A.Entries[I])) 2638 // Next subobject is a field. 2639 ObjType = FD->getType(); 2640 else 2641 // Next subobject is a base class. 2642 ObjType = QualType(); 2643 } 2644 } 2645 WasArrayIndex = false; 2646 return I; 2647 } 2648 2649 /// Determine whether the given subobject designators refer to elements of the 2650 /// same array object. 2651 static bool AreElementsOfSameArray(QualType ObjType, 2652 const SubobjectDesignator &A, 2653 const SubobjectDesignator &B) { 2654 if (A.Entries.size() != B.Entries.size()) 2655 return false; 2656 2657 bool IsArray = A.MostDerivedIsArrayElement; 2658 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 2659 // A is a subobject of the array element. 2660 return false; 2661 2662 // If A (and B) designates an array element, the last entry will be the array 2663 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 2664 // of length 1' case, and the entire path must match. 2665 bool WasArrayIndex; 2666 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 2667 return CommonLength >= A.Entries.size() - IsArray; 2668 } 2669 2670 /// Find the complete object to which an LValue refers. 2671 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 2672 AccessKinds AK, const LValue &LVal, 2673 QualType LValType) { 2674 if (!LVal.Base) { 2675 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 2676 return CompleteObject(); 2677 } 2678 2679 CallStackFrame *Frame = nullptr; 2680 if (LVal.CallIndex) { 2681 Frame = Info.getCallFrame(LVal.CallIndex); 2682 if (!Frame) { 2683 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 2684 << AK << LVal.Base.is<const ValueDecl*>(); 2685 NoteLValueLocation(Info, LVal.Base); 2686 return CompleteObject(); 2687 } 2688 } 2689 2690 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 2691 // is not a constant expression (even if the object is non-volatile). We also 2692 // apply this rule to C++98, in order to conform to the expected 'volatile' 2693 // semantics. 2694 if (LValType.isVolatileQualified()) { 2695 if (Info.getLangOpts().CPlusPlus) 2696 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 2697 << AK << LValType; 2698 else 2699 Info.FFDiag(E); 2700 return CompleteObject(); 2701 } 2702 2703 // Compute value storage location and type of base object. 2704 APValue *BaseVal = nullptr; 2705 QualType BaseType = getType(LVal.Base); 2706 2707 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 2708 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 2709 // In C++11, constexpr, non-volatile variables initialized with constant 2710 // expressions are constant expressions too. Inside constexpr functions, 2711 // parameters are constant expressions even if they're non-const. 2712 // In C++1y, objects local to a constant expression (those with a Frame) are 2713 // both readable and writable inside constant expressions. 2714 // In C, such things can also be folded, although they are not ICEs. 2715 const VarDecl *VD = dyn_cast<VarDecl>(D); 2716 if (VD) { 2717 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 2718 VD = VDef; 2719 } 2720 if (!VD || VD->isInvalidDecl()) { 2721 Info.FFDiag(E); 2722 return CompleteObject(); 2723 } 2724 2725 // Accesses of volatile-qualified objects are not allowed. 2726 if (BaseType.isVolatileQualified()) { 2727 if (Info.getLangOpts().CPlusPlus) { 2728 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2729 << AK << 1 << VD; 2730 Info.Note(VD->getLocation(), diag::note_declared_at); 2731 } else { 2732 Info.FFDiag(E); 2733 } 2734 return CompleteObject(); 2735 } 2736 2737 // Unless we're looking at a local variable or argument in a constexpr call, 2738 // the variable we're reading must be const. 2739 if (!Frame) { 2740 if (Info.getLangOpts().CPlusPlus14 && 2741 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) { 2742 // OK, we can read and modify an object if we're in the process of 2743 // evaluating its initializer, because its lifetime began in this 2744 // evaluation. 2745 } else if (AK != AK_Read) { 2746 // All the remaining cases only permit reading. 2747 Info.FFDiag(E, diag::note_constexpr_modify_global); 2748 return CompleteObject(); 2749 } else if (VD->isConstexpr()) { 2750 // OK, we can read this variable. 2751 } else if (BaseType->isIntegralOrEnumerationType()) { 2752 // In OpenCL if a variable is in constant address space it is a const value. 2753 if (!(BaseType.isConstQualified() || 2754 (Info.getLangOpts().OpenCL && 2755 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 2756 if (Info.getLangOpts().CPlusPlus) { 2757 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 2758 Info.Note(VD->getLocation(), diag::note_declared_at); 2759 } else { 2760 Info.FFDiag(E); 2761 } 2762 return CompleteObject(); 2763 } 2764 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 2765 // We support folding of const floating-point types, in order to make 2766 // static const data members of such types (supported as an extension) 2767 // more useful. 2768 if (Info.getLangOpts().CPlusPlus11) { 2769 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 2770 Info.Note(VD->getLocation(), diag::note_declared_at); 2771 } else { 2772 Info.CCEDiag(E); 2773 } 2774 } else { 2775 // FIXME: Allow folding of values of any literal type in all languages. 2776 if (Info.checkingPotentialConstantExpression() && 2777 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 2778 // The definition of this variable could be constexpr. We can't 2779 // access it right now, but may be able to in future. 2780 } else if (Info.getLangOpts().CPlusPlus11) { 2781 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 2782 Info.Note(VD->getLocation(), diag::note_declared_at); 2783 } else { 2784 Info.FFDiag(E); 2785 } 2786 return CompleteObject(); 2787 } 2788 } 2789 2790 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal)) 2791 return CompleteObject(); 2792 } else { 2793 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 2794 2795 if (!Frame) { 2796 if (const MaterializeTemporaryExpr *MTE = 2797 dyn_cast<MaterializeTemporaryExpr>(Base)) { 2798 assert(MTE->getStorageDuration() == SD_Static && 2799 "should have a frame for a non-global materialized temporary"); 2800 2801 // Per C++1y [expr.const]p2: 2802 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 2803 // - a [...] glvalue of integral or enumeration type that refers to 2804 // a non-volatile const object [...] 2805 // [...] 2806 // - a [...] glvalue of literal type that refers to a non-volatile 2807 // object whose lifetime began within the evaluation of e. 2808 // 2809 // C++11 misses the 'began within the evaluation of e' check and 2810 // instead allows all temporaries, including things like: 2811 // int &&r = 1; 2812 // int x = ++r; 2813 // constexpr int k = r; 2814 // Therefore we use the C++1y rules in C++11 too. 2815 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 2816 const ValueDecl *ED = MTE->getExtendingDecl(); 2817 if (!(BaseType.isConstQualified() && 2818 BaseType->isIntegralOrEnumerationType()) && 2819 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 2820 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 2821 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 2822 return CompleteObject(); 2823 } 2824 2825 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 2826 assert(BaseVal && "got reference to unevaluated temporary"); 2827 } else { 2828 Info.FFDiag(E); 2829 return CompleteObject(); 2830 } 2831 } else { 2832 BaseVal = Frame->getTemporary(Base); 2833 assert(BaseVal && "missing value for temporary"); 2834 } 2835 2836 // Volatile temporary objects cannot be accessed in constant expressions. 2837 if (BaseType.isVolatileQualified()) { 2838 if (Info.getLangOpts().CPlusPlus) { 2839 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2840 << AK << 0; 2841 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here); 2842 } else { 2843 Info.FFDiag(E); 2844 } 2845 return CompleteObject(); 2846 } 2847 } 2848 2849 // During the construction of an object, it is not yet 'const'. 2850 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries, 2851 // and this doesn't do quite the right thing for const subobjects of the 2852 // object under construction. 2853 if (LVal.getLValueBase() == Info.EvaluatingDecl) { 2854 BaseType = Info.Ctx.getCanonicalType(BaseType); 2855 BaseType.removeLocalConst(); 2856 } 2857 2858 // In C++1y, we can't safely access any mutable state when we might be 2859 // evaluating after an unmodeled side effect. 2860 // 2861 // FIXME: Not all local state is mutable. Allow local constant subobjects 2862 // to be read here (but take care with 'mutable' fields). 2863 if ((Frame && Info.getLangOpts().CPlusPlus14 && 2864 Info.EvalStatus.HasSideEffects) || 2865 (AK != AK_Read && Info.IsSpeculativelyEvaluating)) 2866 return CompleteObject(); 2867 2868 return CompleteObject(BaseVal, BaseType); 2869 } 2870 2871 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This 2872 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 2873 /// glvalue referred to by an entity of reference type. 2874 /// 2875 /// \param Info - Information about the ongoing evaluation. 2876 /// \param Conv - The expression for which we are performing the conversion. 2877 /// Used for diagnostics. 2878 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 2879 /// case of a non-class type). 2880 /// \param LVal - The glvalue on which we are attempting to perform this action. 2881 /// \param RVal - The produced value will be placed here. 2882 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 2883 QualType Type, 2884 const LValue &LVal, APValue &RVal) { 2885 if (LVal.Designator.Invalid) 2886 return false; 2887 2888 // Check for special cases where there is no existing APValue to look at. 2889 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 2890 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) { 2891 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 2892 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 2893 // initializer until now for such expressions. Such an expression can't be 2894 // an ICE in C, so this only matters for fold. 2895 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?"); 2896 if (Type.isVolatileQualified()) { 2897 Info.FFDiag(Conv); 2898 return false; 2899 } 2900 APValue Lit; 2901 if (!Evaluate(Lit, Info, CLE->getInitializer())) 2902 return false; 2903 CompleteObject LitObj(&Lit, Base->getType()); 2904 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 2905 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 2906 // We represent a string literal array as an lvalue pointing at the 2907 // corresponding expression, rather than building an array of chars. 2908 // FIXME: Support ObjCEncodeExpr, MakeStringConstant 2909 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0); 2910 CompleteObject StrObj(&Str, Base->getType()); 2911 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal); 2912 } 2913 } 2914 2915 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 2916 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 2917 } 2918 2919 /// Perform an assignment of Val to LVal. Takes ownership of Val. 2920 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 2921 QualType LValType, APValue &Val) { 2922 if (LVal.Designator.Invalid) 2923 return false; 2924 2925 if (!Info.getLangOpts().CPlusPlus14) { 2926 Info.FFDiag(E); 2927 return false; 2928 } 2929 2930 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 2931 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 2932 } 2933 2934 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 2935 return T->isSignedIntegerType() && 2936 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 2937 } 2938 2939 namespace { 2940 struct CompoundAssignSubobjectHandler { 2941 EvalInfo &Info; 2942 const Expr *E; 2943 QualType PromotedLHSType; 2944 BinaryOperatorKind Opcode; 2945 const APValue &RHS; 2946 2947 static const AccessKinds AccessKind = AK_Assign; 2948 2949 typedef bool result_type; 2950 2951 bool checkConst(QualType QT) { 2952 // Assigning to a const object has undefined behavior. 2953 if (QT.isConstQualified()) { 2954 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 2955 return false; 2956 } 2957 return true; 2958 } 2959 2960 bool failed() { return false; } 2961 bool found(APValue &Subobj, QualType SubobjType) { 2962 switch (Subobj.getKind()) { 2963 case APValue::Int: 2964 return found(Subobj.getInt(), SubobjType); 2965 case APValue::Float: 2966 return found(Subobj.getFloat(), SubobjType); 2967 case APValue::ComplexInt: 2968 case APValue::ComplexFloat: 2969 // FIXME: Implement complex compound assignment. 2970 Info.FFDiag(E); 2971 return false; 2972 case APValue::LValue: 2973 return foundPointer(Subobj, SubobjType); 2974 default: 2975 // FIXME: can this happen? 2976 Info.FFDiag(E); 2977 return false; 2978 } 2979 } 2980 bool found(APSInt &Value, QualType SubobjType) { 2981 if (!checkConst(SubobjType)) 2982 return false; 2983 2984 if (!SubobjType->isIntegerType() || !RHS.isInt()) { 2985 // We don't support compound assignment on integer-cast-to-pointer 2986 // values. 2987 Info.FFDiag(E); 2988 return false; 2989 } 2990 2991 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType, 2992 SubobjType, Value); 2993 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 2994 return false; 2995 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 2996 return true; 2997 } 2998 bool found(APFloat &Value, QualType SubobjType) { 2999 return checkConst(SubobjType) && 3000 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3001 Value) && 3002 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3003 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3004 } 3005 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3006 if (!checkConst(SubobjType)) 3007 return false; 3008 3009 QualType PointeeType; 3010 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3011 PointeeType = PT->getPointeeType(); 3012 3013 if (PointeeType.isNull() || !RHS.isInt() || 3014 (Opcode != BO_Add && Opcode != BO_Sub)) { 3015 Info.FFDiag(E); 3016 return false; 3017 } 3018 3019 int64_t Offset = getExtValue(RHS.getInt()); 3020 if (Opcode == BO_Sub) 3021 Offset = -Offset; 3022 3023 LValue LVal; 3024 LVal.setFrom(Info.Ctx, Subobj); 3025 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3026 return false; 3027 LVal.moveInto(Subobj); 3028 return true; 3029 } 3030 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3031 llvm_unreachable("shouldn't encounter string elements here"); 3032 } 3033 }; 3034 } // end anonymous namespace 3035 3036 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3037 3038 /// Perform a compound assignment of LVal <op>= RVal. 3039 static bool handleCompoundAssignment( 3040 EvalInfo &Info, const Expr *E, 3041 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3042 BinaryOperatorKind Opcode, const APValue &RVal) { 3043 if (LVal.Designator.Invalid) 3044 return false; 3045 3046 if (!Info.getLangOpts().CPlusPlus14) { 3047 Info.FFDiag(E); 3048 return false; 3049 } 3050 3051 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3052 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3053 RVal }; 3054 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3055 } 3056 3057 namespace { 3058 struct IncDecSubobjectHandler { 3059 EvalInfo &Info; 3060 const Expr *E; 3061 AccessKinds AccessKind; 3062 APValue *Old; 3063 3064 typedef bool result_type; 3065 3066 bool checkConst(QualType QT) { 3067 // Assigning to a const object has undefined behavior. 3068 if (QT.isConstQualified()) { 3069 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3070 return false; 3071 } 3072 return true; 3073 } 3074 3075 bool failed() { return false; } 3076 bool found(APValue &Subobj, QualType SubobjType) { 3077 // Stash the old value. Also clear Old, so we don't clobber it later 3078 // if we're post-incrementing a complex. 3079 if (Old) { 3080 *Old = Subobj; 3081 Old = nullptr; 3082 } 3083 3084 switch (Subobj.getKind()) { 3085 case APValue::Int: 3086 return found(Subobj.getInt(), SubobjType); 3087 case APValue::Float: 3088 return found(Subobj.getFloat(), SubobjType); 3089 case APValue::ComplexInt: 3090 return found(Subobj.getComplexIntReal(), 3091 SubobjType->castAs<ComplexType>()->getElementType() 3092 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3093 case APValue::ComplexFloat: 3094 return found(Subobj.getComplexFloatReal(), 3095 SubobjType->castAs<ComplexType>()->getElementType() 3096 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3097 case APValue::LValue: 3098 return foundPointer(Subobj, SubobjType); 3099 default: 3100 // FIXME: can this happen? 3101 Info.FFDiag(E); 3102 return false; 3103 } 3104 } 3105 bool found(APSInt &Value, QualType SubobjType) { 3106 if (!checkConst(SubobjType)) 3107 return false; 3108 3109 if (!SubobjType->isIntegerType()) { 3110 // We don't support increment / decrement on integer-cast-to-pointer 3111 // values. 3112 Info.FFDiag(E); 3113 return false; 3114 } 3115 3116 if (Old) *Old = APValue(Value); 3117 3118 // bool arithmetic promotes to int, and the conversion back to bool 3119 // doesn't reduce mod 2^n, so special-case it. 3120 if (SubobjType->isBooleanType()) { 3121 if (AccessKind == AK_Increment) 3122 Value = 1; 3123 else 3124 Value = !Value; 3125 return true; 3126 } 3127 3128 bool WasNegative = Value.isNegative(); 3129 if (AccessKind == AK_Increment) { 3130 ++Value; 3131 3132 if (!WasNegative && Value.isNegative() && 3133 isOverflowingIntegerType(Info.Ctx, SubobjType)) { 3134 APSInt ActualValue(Value, /*IsUnsigned*/true); 3135 return HandleOverflow(Info, E, ActualValue, SubobjType); 3136 } 3137 } else { 3138 --Value; 3139 3140 if (WasNegative && !Value.isNegative() && 3141 isOverflowingIntegerType(Info.Ctx, SubobjType)) { 3142 unsigned BitWidth = Value.getBitWidth(); 3143 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3144 ActualValue.setBit(BitWidth); 3145 return HandleOverflow(Info, E, ActualValue, SubobjType); 3146 } 3147 } 3148 return true; 3149 } 3150 bool found(APFloat &Value, QualType SubobjType) { 3151 if (!checkConst(SubobjType)) 3152 return false; 3153 3154 if (Old) *Old = APValue(Value); 3155 3156 APFloat One(Value.getSemantics(), 1); 3157 if (AccessKind == AK_Increment) 3158 Value.add(One, APFloat::rmNearestTiesToEven); 3159 else 3160 Value.subtract(One, APFloat::rmNearestTiesToEven); 3161 return true; 3162 } 3163 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3164 if (!checkConst(SubobjType)) 3165 return false; 3166 3167 QualType PointeeType; 3168 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3169 PointeeType = PT->getPointeeType(); 3170 else { 3171 Info.FFDiag(E); 3172 return false; 3173 } 3174 3175 LValue LVal; 3176 LVal.setFrom(Info.Ctx, Subobj); 3177 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3178 AccessKind == AK_Increment ? 1 : -1)) 3179 return false; 3180 LVal.moveInto(Subobj); 3181 return true; 3182 } 3183 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3184 llvm_unreachable("shouldn't encounter string elements here"); 3185 } 3186 }; 3187 } // end anonymous namespace 3188 3189 /// Perform an increment or decrement on LVal. 3190 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3191 QualType LValType, bool IsIncrement, APValue *Old) { 3192 if (LVal.Designator.Invalid) 3193 return false; 3194 3195 if (!Info.getLangOpts().CPlusPlus14) { 3196 Info.FFDiag(E); 3197 return false; 3198 } 3199 3200 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3201 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3202 IncDecSubobjectHandler Handler = { Info, E, AK, Old }; 3203 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3204 } 3205 3206 /// Build an lvalue for the object argument of a member function call. 3207 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3208 LValue &This) { 3209 if (Object->getType()->isPointerType()) 3210 return EvaluatePointer(Object, This, Info); 3211 3212 if (Object->isGLValue()) 3213 return EvaluateLValue(Object, This, Info); 3214 3215 if (Object->getType()->isLiteralType(Info.Ctx)) 3216 return EvaluateTemporary(Object, This, Info); 3217 3218 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3219 return false; 3220 } 3221 3222 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3223 /// lvalue referring to the result. 3224 /// 3225 /// \param Info - Information about the ongoing evaluation. 3226 /// \param LV - An lvalue referring to the base of the member pointer. 3227 /// \param RHS - The member pointer expression. 3228 /// \param IncludeMember - Specifies whether the member itself is included in 3229 /// the resulting LValue subobject designator. This is not possible when 3230 /// creating a bound member function. 3231 /// \return The field or method declaration to which the member pointer refers, 3232 /// or 0 if evaluation fails. 3233 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3234 QualType LVType, 3235 LValue &LV, 3236 const Expr *RHS, 3237 bool IncludeMember = true) { 3238 MemberPtr MemPtr; 3239 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3240 return nullptr; 3241 3242 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3243 // member value, the behavior is undefined. 3244 if (!MemPtr.getDecl()) { 3245 // FIXME: Specific diagnostic. 3246 Info.FFDiag(RHS); 3247 return nullptr; 3248 } 3249 3250 if (MemPtr.isDerivedMember()) { 3251 // This is a member of some derived class. Truncate LV appropriately. 3252 // The end of the derived-to-base path for the base object must match the 3253 // derived-to-base path for the member pointer. 3254 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3255 LV.Designator.Entries.size()) { 3256 Info.FFDiag(RHS); 3257 return nullptr; 3258 } 3259 unsigned PathLengthToMember = 3260 LV.Designator.Entries.size() - MemPtr.Path.size(); 3261 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3262 const CXXRecordDecl *LVDecl = getAsBaseClass( 3263 LV.Designator.Entries[PathLengthToMember + I]); 3264 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3265 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3266 Info.FFDiag(RHS); 3267 return nullptr; 3268 } 3269 } 3270 3271 // Truncate the lvalue to the appropriate derived class. 3272 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3273 PathLengthToMember)) 3274 return nullptr; 3275 } else if (!MemPtr.Path.empty()) { 3276 // Extend the LValue path with the member pointer's path. 3277 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3278 MemPtr.Path.size() + IncludeMember); 3279 3280 // Walk down to the appropriate base class. 3281 if (const PointerType *PT = LVType->getAs<PointerType>()) 3282 LVType = PT->getPointeeType(); 3283 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3284 assert(RD && "member pointer access on non-class-type expression"); 3285 // The first class in the path is that of the lvalue. 3286 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3287 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3288 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3289 return nullptr; 3290 RD = Base; 3291 } 3292 // Finally cast to the class containing the member. 3293 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3294 MemPtr.getContainingRecord())) 3295 return nullptr; 3296 } 3297 3298 // Add the member. Note that we cannot build bound member functions here. 3299 if (IncludeMember) { 3300 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3301 if (!HandleLValueMember(Info, RHS, LV, FD)) 3302 return nullptr; 3303 } else if (const IndirectFieldDecl *IFD = 3304 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3305 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3306 return nullptr; 3307 } else { 3308 llvm_unreachable("can't construct reference to bound member function"); 3309 } 3310 } 3311 3312 return MemPtr.getDecl(); 3313 } 3314 3315 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3316 const BinaryOperator *BO, 3317 LValue &LV, 3318 bool IncludeMember = true) { 3319 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3320 3321 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3322 if (Info.noteFailure()) { 3323 MemberPtr MemPtr; 3324 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3325 } 3326 return nullptr; 3327 } 3328 3329 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3330 BO->getRHS(), IncludeMember); 3331 } 3332 3333 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3334 /// the provided lvalue, which currently refers to the base object. 3335 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3336 LValue &Result) { 3337 SubobjectDesignator &D = Result.Designator; 3338 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3339 return false; 3340 3341 QualType TargetQT = E->getType(); 3342 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 3343 TargetQT = PT->getPointeeType(); 3344 3345 // Check this cast lands within the final derived-to-base subobject path. 3346 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 3347 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3348 << D.MostDerivedType << TargetQT; 3349 return false; 3350 } 3351 3352 // Check the type of the final cast. We don't need to check the path, 3353 // since a cast can only be formed if the path is unique. 3354 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 3355 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 3356 const CXXRecordDecl *FinalType; 3357 if (NewEntriesSize == D.MostDerivedPathLength) 3358 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 3359 else 3360 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 3361 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 3362 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3363 << D.MostDerivedType << TargetQT; 3364 return false; 3365 } 3366 3367 // Truncate the lvalue to the appropriate derived class. 3368 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 3369 } 3370 3371 namespace { 3372 enum EvalStmtResult { 3373 /// Evaluation failed. 3374 ESR_Failed, 3375 /// Hit a 'return' statement. 3376 ESR_Returned, 3377 /// Evaluation succeeded. 3378 ESR_Succeeded, 3379 /// Hit a 'continue' statement. 3380 ESR_Continue, 3381 /// Hit a 'break' statement. 3382 ESR_Break, 3383 /// Still scanning for 'case' or 'default' statement. 3384 ESR_CaseNotFound 3385 }; 3386 } 3387 3388 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 3389 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 3390 // We don't need to evaluate the initializer for a static local. 3391 if (!VD->hasLocalStorage()) 3392 return true; 3393 3394 LValue Result; 3395 Result.set(VD, Info.CurrentCall->Index); 3396 APValue &Val = Info.CurrentCall->createTemporary(VD, true); 3397 3398 const Expr *InitE = VD->getInit(); 3399 if (!InitE) { 3400 Info.FFDiag(D->getLocStart(), diag::note_constexpr_uninitialized) 3401 << false << VD->getType(); 3402 Val = APValue(); 3403 return false; 3404 } 3405 3406 if (InitE->isValueDependent()) 3407 return false; 3408 3409 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 3410 // Wipe out any partially-computed value, to allow tracking that this 3411 // evaluation failed. 3412 Val = APValue(); 3413 return false; 3414 } 3415 } 3416 3417 return true; 3418 } 3419 3420 /// Evaluate a condition (either a variable declaration or an expression). 3421 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 3422 const Expr *Cond, bool &Result) { 3423 FullExpressionRAII Scope(Info); 3424 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 3425 return false; 3426 return EvaluateAsBooleanCondition(Cond, Result, Info); 3427 } 3428 3429 namespace { 3430 /// \brief A location where the result (returned value) of evaluating a 3431 /// statement should be stored. 3432 struct StmtResult { 3433 /// The APValue that should be filled in with the returned value. 3434 APValue &Value; 3435 /// The location containing the result, if any (used to support RVO). 3436 const LValue *Slot; 3437 }; 3438 } 3439 3440 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3441 const Stmt *S, 3442 const SwitchCase *SC = nullptr); 3443 3444 /// Evaluate the body of a loop, and translate the result as appropriate. 3445 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 3446 const Stmt *Body, 3447 const SwitchCase *Case = nullptr) { 3448 BlockScopeRAII Scope(Info); 3449 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 3450 case ESR_Break: 3451 return ESR_Succeeded; 3452 case ESR_Succeeded: 3453 case ESR_Continue: 3454 return ESR_Continue; 3455 case ESR_Failed: 3456 case ESR_Returned: 3457 case ESR_CaseNotFound: 3458 return ESR; 3459 } 3460 llvm_unreachable("Invalid EvalStmtResult!"); 3461 } 3462 3463 /// Evaluate a switch statement. 3464 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 3465 const SwitchStmt *SS) { 3466 BlockScopeRAII Scope(Info); 3467 3468 // Evaluate the switch condition. 3469 APSInt Value; 3470 { 3471 FullExpressionRAII Scope(Info); 3472 if (const Stmt *Init = SS->getInit()) { 3473 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3474 if (ESR != ESR_Succeeded) 3475 return ESR; 3476 } 3477 if (SS->getConditionVariable() && 3478 !EvaluateDecl(Info, SS->getConditionVariable())) 3479 return ESR_Failed; 3480 if (!EvaluateInteger(SS->getCond(), Value, Info)) 3481 return ESR_Failed; 3482 } 3483 3484 // Find the switch case corresponding to the value of the condition. 3485 // FIXME: Cache this lookup. 3486 const SwitchCase *Found = nullptr; 3487 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 3488 SC = SC->getNextSwitchCase()) { 3489 if (isa<DefaultStmt>(SC)) { 3490 Found = SC; 3491 continue; 3492 } 3493 3494 const CaseStmt *CS = cast<CaseStmt>(SC); 3495 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 3496 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 3497 : LHS; 3498 if (LHS <= Value && Value <= RHS) { 3499 Found = SC; 3500 break; 3501 } 3502 } 3503 3504 if (!Found) 3505 return ESR_Succeeded; 3506 3507 // Search the switch body for the switch case and evaluate it from there. 3508 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 3509 case ESR_Break: 3510 return ESR_Succeeded; 3511 case ESR_Succeeded: 3512 case ESR_Continue: 3513 case ESR_Failed: 3514 case ESR_Returned: 3515 return ESR; 3516 case ESR_CaseNotFound: 3517 // This can only happen if the switch case is nested within a statement 3518 // expression. We have no intention of supporting that. 3519 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported); 3520 return ESR_Failed; 3521 } 3522 llvm_unreachable("Invalid EvalStmtResult!"); 3523 } 3524 3525 // Evaluate a statement. 3526 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3527 const Stmt *S, const SwitchCase *Case) { 3528 if (!Info.nextStep(S)) 3529 return ESR_Failed; 3530 3531 // If we're hunting down a 'case' or 'default' label, recurse through 3532 // substatements until we hit the label. 3533 if (Case) { 3534 // FIXME: We don't start the lifetime of objects whose initialization we 3535 // jump over. However, such objects must be of class type with a trivial 3536 // default constructor that initialize all subobjects, so must be empty, 3537 // so this almost never matters. 3538 switch (S->getStmtClass()) { 3539 case Stmt::CompoundStmtClass: 3540 // FIXME: Precompute which substatement of a compound statement we 3541 // would jump to, and go straight there rather than performing a 3542 // linear scan each time. 3543 case Stmt::LabelStmtClass: 3544 case Stmt::AttributedStmtClass: 3545 case Stmt::DoStmtClass: 3546 break; 3547 3548 case Stmt::CaseStmtClass: 3549 case Stmt::DefaultStmtClass: 3550 if (Case == S) 3551 Case = nullptr; 3552 break; 3553 3554 case Stmt::IfStmtClass: { 3555 // FIXME: Precompute which side of an 'if' we would jump to, and go 3556 // straight there rather than scanning both sides. 3557 const IfStmt *IS = cast<IfStmt>(S); 3558 3559 // Wrap the evaluation in a block scope, in case it's a DeclStmt 3560 // preceded by our switch label. 3561 BlockScopeRAII Scope(Info); 3562 3563 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 3564 if (ESR != ESR_CaseNotFound || !IS->getElse()) 3565 return ESR; 3566 return EvaluateStmt(Result, Info, IS->getElse(), Case); 3567 } 3568 3569 case Stmt::WhileStmtClass: { 3570 EvalStmtResult ESR = 3571 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 3572 if (ESR != ESR_Continue) 3573 return ESR; 3574 break; 3575 } 3576 3577 case Stmt::ForStmtClass: { 3578 const ForStmt *FS = cast<ForStmt>(S); 3579 EvalStmtResult ESR = 3580 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 3581 if (ESR != ESR_Continue) 3582 return ESR; 3583 if (FS->getInc()) { 3584 FullExpressionRAII IncScope(Info); 3585 if (!EvaluateIgnoredValue(Info, FS->getInc())) 3586 return ESR_Failed; 3587 } 3588 break; 3589 } 3590 3591 case Stmt::DeclStmtClass: 3592 // FIXME: If the variable has initialization that can't be jumped over, 3593 // bail out of any immediately-surrounding compound-statement too. 3594 default: 3595 return ESR_CaseNotFound; 3596 } 3597 } 3598 3599 switch (S->getStmtClass()) { 3600 default: 3601 if (const Expr *E = dyn_cast<Expr>(S)) { 3602 // Don't bother evaluating beyond an expression-statement which couldn't 3603 // be evaluated. 3604 FullExpressionRAII Scope(Info); 3605 if (!EvaluateIgnoredValue(Info, E)) 3606 return ESR_Failed; 3607 return ESR_Succeeded; 3608 } 3609 3610 Info.FFDiag(S->getLocStart()); 3611 return ESR_Failed; 3612 3613 case Stmt::NullStmtClass: 3614 return ESR_Succeeded; 3615 3616 case Stmt::DeclStmtClass: { 3617 const DeclStmt *DS = cast<DeclStmt>(S); 3618 for (const auto *DclIt : DS->decls()) { 3619 // Each declaration initialization is its own full-expression. 3620 // FIXME: This isn't quite right; if we're performing aggregate 3621 // initialization, each braced subexpression is its own full-expression. 3622 FullExpressionRAII Scope(Info); 3623 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 3624 return ESR_Failed; 3625 } 3626 return ESR_Succeeded; 3627 } 3628 3629 case Stmt::ReturnStmtClass: { 3630 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 3631 FullExpressionRAII Scope(Info); 3632 if (RetExpr && 3633 !(Result.Slot 3634 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 3635 : Evaluate(Result.Value, Info, RetExpr))) 3636 return ESR_Failed; 3637 return ESR_Returned; 3638 } 3639 3640 case Stmt::CompoundStmtClass: { 3641 BlockScopeRAII Scope(Info); 3642 3643 const CompoundStmt *CS = cast<CompoundStmt>(S); 3644 for (const auto *BI : CS->body()) { 3645 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 3646 if (ESR == ESR_Succeeded) 3647 Case = nullptr; 3648 else if (ESR != ESR_CaseNotFound) 3649 return ESR; 3650 } 3651 return Case ? ESR_CaseNotFound : ESR_Succeeded; 3652 } 3653 3654 case Stmt::IfStmtClass: { 3655 const IfStmt *IS = cast<IfStmt>(S); 3656 3657 // Evaluate the condition, as either a var decl or as an expression. 3658 BlockScopeRAII Scope(Info); 3659 if (const Stmt *Init = IS->getInit()) { 3660 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3661 if (ESR != ESR_Succeeded) 3662 return ESR; 3663 } 3664 bool Cond; 3665 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 3666 return ESR_Failed; 3667 3668 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 3669 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 3670 if (ESR != ESR_Succeeded) 3671 return ESR; 3672 } 3673 return ESR_Succeeded; 3674 } 3675 3676 case Stmt::WhileStmtClass: { 3677 const WhileStmt *WS = cast<WhileStmt>(S); 3678 while (true) { 3679 BlockScopeRAII Scope(Info); 3680 bool Continue; 3681 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 3682 Continue)) 3683 return ESR_Failed; 3684 if (!Continue) 3685 break; 3686 3687 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 3688 if (ESR != ESR_Continue) 3689 return ESR; 3690 } 3691 return ESR_Succeeded; 3692 } 3693 3694 case Stmt::DoStmtClass: { 3695 const DoStmt *DS = cast<DoStmt>(S); 3696 bool Continue; 3697 do { 3698 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 3699 if (ESR != ESR_Continue) 3700 return ESR; 3701 Case = nullptr; 3702 3703 FullExpressionRAII CondScope(Info); 3704 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 3705 return ESR_Failed; 3706 } while (Continue); 3707 return ESR_Succeeded; 3708 } 3709 3710 case Stmt::ForStmtClass: { 3711 const ForStmt *FS = cast<ForStmt>(S); 3712 BlockScopeRAII Scope(Info); 3713 if (FS->getInit()) { 3714 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 3715 if (ESR != ESR_Succeeded) 3716 return ESR; 3717 } 3718 while (true) { 3719 BlockScopeRAII Scope(Info); 3720 bool Continue = true; 3721 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 3722 FS->getCond(), Continue)) 3723 return ESR_Failed; 3724 if (!Continue) 3725 break; 3726 3727 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 3728 if (ESR != ESR_Continue) 3729 return ESR; 3730 3731 if (FS->getInc()) { 3732 FullExpressionRAII IncScope(Info); 3733 if (!EvaluateIgnoredValue(Info, FS->getInc())) 3734 return ESR_Failed; 3735 } 3736 } 3737 return ESR_Succeeded; 3738 } 3739 3740 case Stmt::CXXForRangeStmtClass: { 3741 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 3742 BlockScopeRAII Scope(Info); 3743 3744 // Initialize the __range variable. 3745 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 3746 if (ESR != ESR_Succeeded) 3747 return ESR; 3748 3749 // Create the __begin and __end iterators. 3750 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 3751 if (ESR != ESR_Succeeded) 3752 return ESR; 3753 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 3754 if (ESR != ESR_Succeeded) 3755 return ESR; 3756 3757 while (true) { 3758 // Condition: __begin != __end. 3759 { 3760 bool Continue = true; 3761 FullExpressionRAII CondExpr(Info); 3762 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 3763 return ESR_Failed; 3764 if (!Continue) 3765 break; 3766 } 3767 3768 // User's variable declaration, initialized by *__begin. 3769 BlockScopeRAII InnerScope(Info); 3770 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 3771 if (ESR != ESR_Succeeded) 3772 return ESR; 3773 3774 // Loop body. 3775 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 3776 if (ESR != ESR_Continue) 3777 return ESR; 3778 3779 // Increment: ++__begin 3780 if (!EvaluateIgnoredValue(Info, FS->getInc())) 3781 return ESR_Failed; 3782 } 3783 3784 return ESR_Succeeded; 3785 } 3786 3787 case Stmt::SwitchStmtClass: 3788 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 3789 3790 case Stmt::ContinueStmtClass: 3791 return ESR_Continue; 3792 3793 case Stmt::BreakStmtClass: 3794 return ESR_Break; 3795 3796 case Stmt::LabelStmtClass: 3797 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 3798 3799 case Stmt::AttributedStmtClass: 3800 // As a general principle, C++11 attributes can be ignored without 3801 // any semantic impact. 3802 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 3803 Case); 3804 3805 case Stmt::CaseStmtClass: 3806 case Stmt::DefaultStmtClass: 3807 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 3808 } 3809 } 3810 3811 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 3812 /// default constructor. If so, we'll fold it whether or not it's marked as 3813 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 3814 /// so we need special handling. 3815 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 3816 const CXXConstructorDecl *CD, 3817 bool IsValueInitialization) { 3818 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 3819 return false; 3820 3821 // Value-initialization does not call a trivial default constructor, so such a 3822 // call is a core constant expression whether or not the constructor is 3823 // constexpr. 3824 if (!CD->isConstexpr() && !IsValueInitialization) { 3825 if (Info.getLangOpts().CPlusPlus11) { 3826 // FIXME: If DiagDecl is an implicitly-declared special member function, 3827 // we should be much more explicit about why it's not constexpr. 3828 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 3829 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 3830 Info.Note(CD->getLocation(), diag::note_declared_at); 3831 } else { 3832 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 3833 } 3834 } 3835 return true; 3836 } 3837 3838 /// CheckConstexprFunction - Check that a function can be called in a constant 3839 /// expression. 3840 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 3841 const FunctionDecl *Declaration, 3842 const FunctionDecl *Definition, 3843 const Stmt *Body) { 3844 // Potential constant expressions can contain calls to declared, but not yet 3845 // defined, constexpr functions. 3846 if (Info.checkingPotentialConstantExpression() && !Definition && 3847 Declaration->isConstexpr()) 3848 return false; 3849 3850 // Bail out with no diagnostic if the function declaration itself is invalid. 3851 // We will have produced a relevant diagnostic while parsing it. 3852 if (Declaration->isInvalidDecl()) 3853 return false; 3854 3855 // Can we evaluate this function call? 3856 if (Definition && Definition->isConstexpr() && 3857 !Definition->isInvalidDecl() && Body) 3858 return true; 3859 3860 if (Info.getLangOpts().CPlusPlus11) { 3861 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 3862 3863 // If this function is not constexpr because it is an inherited 3864 // non-constexpr constructor, diagnose that directly. 3865 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 3866 if (CD && CD->isInheritingConstructor()) { 3867 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 3868 if (!Inherited->isConstexpr()) 3869 DiagDecl = CD = Inherited; 3870 } 3871 3872 // FIXME: If DiagDecl is an implicitly-declared special member function 3873 // or an inheriting constructor, we should be much more explicit about why 3874 // it's not constexpr. 3875 if (CD && CD->isInheritingConstructor()) 3876 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 3877 << CD->getInheritedConstructor().getConstructor()->getParent(); 3878 else 3879 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 3880 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 3881 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 3882 } else { 3883 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 3884 } 3885 return false; 3886 } 3887 3888 /// Determine if a class has any fields that might need to be copied by a 3889 /// trivial copy or move operation. 3890 static bool hasFields(const CXXRecordDecl *RD) { 3891 if (!RD || RD->isEmpty()) 3892 return false; 3893 for (auto *FD : RD->fields()) { 3894 if (FD->isUnnamedBitfield()) 3895 continue; 3896 return true; 3897 } 3898 for (auto &Base : RD->bases()) 3899 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 3900 return true; 3901 return false; 3902 } 3903 3904 namespace { 3905 typedef SmallVector<APValue, 8> ArgVector; 3906 } 3907 3908 /// EvaluateArgs - Evaluate the arguments to a function call. 3909 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 3910 EvalInfo &Info) { 3911 bool Success = true; 3912 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 3913 I != E; ++I) { 3914 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 3915 // If we're checking for a potential constant expression, evaluate all 3916 // initializers even if some of them fail. 3917 if (!Info.noteFailure()) 3918 return false; 3919 Success = false; 3920 } 3921 } 3922 return Success; 3923 } 3924 3925 /// Evaluate a function call. 3926 static bool HandleFunctionCall(SourceLocation CallLoc, 3927 const FunctionDecl *Callee, const LValue *This, 3928 ArrayRef<const Expr*> Args, const Stmt *Body, 3929 EvalInfo &Info, APValue &Result, 3930 const LValue *ResultSlot) { 3931 ArgVector ArgValues(Args.size()); 3932 if (!EvaluateArgs(Args, ArgValues, Info)) 3933 return false; 3934 3935 if (!Info.CheckCallLimit(CallLoc)) 3936 return false; 3937 3938 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 3939 3940 // For a trivial copy or move assignment, perform an APValue copy. This is 3941 // essential for unions, where the operations performed by the assignment 3942 // operator cannot be represented as statements. 3943 // 3944 // Skip this for non-union classes with no fields; in that case, the defaulted 3945 // copy/move does not actually read the object. 3946 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 3947 if (MD && MD->isDefaulted() && 3948 (MD->getParent()->isUnion() || 3949 (MD->isTrivial() && hasFields(MD->getParent())))) { 3950 assert(This && 3951 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 3952 LValue RHS; 3953 RHS.setFrom(Info.Ctx, ArgValues[0]); 3954 APValue RHSValue; 3955 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 3956 RHS, RHSValue)) 3957 return false; 3958 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx), 3959 RHSValue)) 3960 return false; 3961 This->moveInto(Result); 3962 return true; 3963 } 3964 3965 StmtResult Ret = {Result, ResultSlot}; 3966 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 3967 if (ESR == ESR_Succeeded) { 3968 if (Callee->getReturnType()->isVoidType()) 3969 return true; 3970 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return); 3971 } 3972 return ESR == ESR_Returned; 3973 } 3974 3975 /// Evaluate a constructor call. 3976 static bool HandleConstructorCall(const Expr *E, const LValue &This, 3977 APValue *ArgValues, 3978 const CXXConstructorDecl *Definition, 3979 EvalInfo &Info, APValue &Result) { 3980 SourceLocation CallLoc = E->getExprLoc(); 3981 if (!Info.CheckCallLimit(CallLoc)) 3982 return false; 3983 3984 const CXXRecordDecl *RD = Definition->getParent(); 3985 if (RD->getNumVBases()) { 3986 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 3987 return false; 3988 } 3989 3990 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 3991 3992 // FIXME: Creating an APValue just to hold a nonexistent return value is 3993 // wasteful. 3994 APValue RetVal; 3995 StmtResult Ret = {RetVal, nullptr}; 3996 3997 // If it's a delegating constructor, delegate. 3998 if (Definition->isDelegatingConstructor()) { 3999 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 4000 { 4001 FullExpressionRAII InitScope(Info); 4002 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 4003 return false; 4004 } 4005 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4006 } 4007 4008 // For a trivial copy or move constructor, perform an APValue copy. This is 4009 // essential for unions (or classes with anonymous union members), where the 4010 // operations performed by the constructor cannot be represented by 4011 // ctor-initializers. 4012 // 4013 // Skip this for empty non-union classes; we should not perform an 4014 // lvalue-to-rvalue conversion on them because their copy constructor does not 4015 // actually read them. 4016 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 4017 (Definition->getParent()->isUnion() || 4018 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 4019 LValue RHS; 4020 RHS.setFrom(Info.Ctx, ArgValues[0]); 4021 return handleLValueToRValueConversion( 4022 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 4023 RHS, Result); 4024 } 4025 4026 // Reserve space for the struct members. 4027 if (!RD->isUnion() && Result.isUninit()) 4028 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4029 std::distance(RD->field_begin(), RD->field_end())); 4030 4031 if (RD->isInvalidDecl()) return false; 4032 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 4033 4034 // A scope for temporaries lifetime-extended by reference members. 4035 BlockScopeRAII LifetimeExtendedScope(Info); 4036 4037 bool Success = true; 4038 unsigned BasesSeen = 0; 4039 #ifndef NDEBUG 4040 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 4041 #endif 4042 for (const auto *I : Definition->inits()) { 4043 LValue Subobject = This; 4044 APValue *Value = &Result; 4045 4046 // Determine the subobject to initialize. 4047 FieldDecl *FD = nullptr; 4048 if (I->isBaseInitializer()) { 4049 QualType BaseType(I->getBaseClass(), 0); 4050 #ifndef NDEBUG 4051 // Non-virtual base classes are initialized in the order in the class 4052 // definition. We have already checked for virtual base classes. 4053 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 4054 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 4055 "base class initializers not in expected order"); 4056 ++BaseIt; 4057 #endif 4058 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 4059 BaseType->getAsCXXRecordDecl(), &Layout)) 4060 return false; 4061 Value = &Result.getStructBase(BasesSeen++); 4062 } else if ((FD = I->getMember())) { 4063 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 4064 return false; 4065 if (RD->isUnion()) { 4066 Result = APValue(FD); 4067 Value = &Result.getUnionValue(); 4068 } else { 4069 Value = &Result.getStructField(FD->getFieldIndex()); 4070 } 4071 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 4072 // Walk the indirect field decl's chain to find the object to initialize, 4073 // and make sure we've initialized every step along it. 4074 for (auto *C : IFD->chain()) { 4075 FD = cast<FieldDecl>(C); 4076 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 4077 // Switch the union field if it differs. This happens if we had 4078 // preceding zero-initialization, and we're now initializing a union 4079 // subobject other than the first. 4080 // FIXME: In this case, the values of the other subobjects are 4081 // specified, since zero-initialization sets all padding bits to zero. 4082 if (Value->isUninit() || 4083 (Value->isUnion() && Value->getUnionField() != FD)) { 4084 if (CD->isUnion()) 4085 *Value = APValue(FD); 4086 else 4087 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 4088 std::distance(CD->field_begin(), CD->field_end())); 4089 } 4090 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 4091 return false; 4092 if (CD->isUnion()) 4093 Value = &Value->getUnionValue(); 4094 else 4095 Value = &Value->getStructField(FD->getFieldIndex()); 4096 } 4097 } else { 4098 llvm_unreachable("unknown base initializer kind"); 4099 } 4100 4101 FullExpressionRAII InitScope(Info); 4102 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) || 4103 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(), 4104 *Value, FD))) { 4105 // If we're checking for a potential constant expression, evaluate all 4106 // initializers even if some of them fail. 4107 if (!Info.noteFailure()) 4108 return false; 4109 Success = false; 4110 } 4111 } 4112 4113 return Success && 4114 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4115 } 4116 4117 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4118 ArrayRef<const Expr*> Args, 4119 const CXXConstructorDecl *Definition, 4120 EvalInfo &Info, APValue &Result) { 4121 ArgVector ArgValues(Args.size()); 4122 if (!EvaluateArgs(Args, ArgValues, Info)) 4123 return false; 4124 4125 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 4126 Info, Result); 4127 } 4128 4129 //===----------------------------------------------------------------------===// 4130 // Generic Evaluation 4131 //===----------------------------------------------------------------------===// 4132 namespace { 4133 4134 template <class Derived> 4135 class ExprEvaluatorBase 4136 : public ConstStmtVisitor<Derived, bool> { 4137 private: 4138 Derived &getDerived() { return static_cast<Derived&>(*this); } 4139 bool DerivedSuccess(const APValue &V, const Expr *E) { 4140 return getDerived().Success(V, E); 4141 } 4142 bool DerivedZeroInitialization(const Expr *E) { 4143 return getDerived().ZeroInitialization(E); 4144 } 4145 4146 // Check whether a conditional operator with a non-constant condition is a 4147 // potential constant expression. If neither arm is a potential constant 4148 // expression, then the conditional operator is not either. 4149 template<typename ConditionalOperator> 4150 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 4151 assert(Info.checkingPotentialConstantExpression()); 4152 4153 // Speculatively evaluate both arms. 4154 SmallVector<PartialDiagnosticAt, 8> Diag; 4155 { 4156 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4157 StmtVisitorTy::Visit(E->getFalseExpr()); 4158 if (Diag.empty()) 4159 return; 4160 } 4161 4162 { 4163 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4164 Diag.clear(); 4165 StmtVisitorTy::Visit(E->getTrueExpr()); 4166 if (Diag.empty()) 4167 return; 4168 } 4169 4170 Error(E, diag::note_constexpr_conditional_never_const); 4171 } 4172 4173 4174 template<typename ConditionalOperator> 4175 bool HandleConditionalOperator(const ConditionalOperator *E) { 4176 bool BoolResult; 4177 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 4178 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) 4179 CheckPotentialConstantConditional(E); 4180 return false; 4181 } 4182 4183 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 4184 return StmtVisitorTy::Visit(EvalExpr); 4185 } 4186 4187 protected: 4188 EvalInfo &Info; 4189 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 4190 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 4191 4192 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 4193 return Info.CCEDiag(E, D); 4194 } 4195 4196 bool ZeroInitialization(const Expr *E) { return Error(E); } 4197 4198 public: 4199 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 4200 4201 EvalInfo &getEvalInfo() { return Info; } 4202 4203 /// Report an evaluation error. This should only be called when an error is 4204 /// first discovered. When propagating an error, just return false. 4205 bool Error(const Expr *E, diag::kind D) { 4206 Info.FFDiag(E, D); 4207 return false; 4208 } 4209 bool Error(const Expr *E) { 4210 return Error(E, diag::note_invalid_subexpr_in_const_expr); 4211 } 4212 4213 bool VisitStmt(const Stmt *) { 4214 llvm_unreachable("Expression evaluator should not be called on stmts"); 4215 } 4216 bool VisitExpr(const Expr *E) { 4217 return Error(E); 4218 } 4219 4220 bool VisitParenExpr(const ParenExpr *E) 4221 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4222 bool VisitUnaryExtension(const UnaryOperator *E) 4223 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4224 bool VisitUnaryPlus(const UnaryOperator *E) 4225 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4226 bool VisitChooseExpr(const ChooseExpr *E) 4227 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 4228 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 4229 { return StmtVisitorTy::Visit(E->getResultExpr()); } 4230 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 4231 { return StmtVisitorTy::Visit(E->getReplacement()); } 4232 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) 4233 { return StmtVisitorTy::Visit(E->getExpr()); } 4234 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 4235 // The initializer may not have been parsed yet, or might be erroneous. 4236 if (!E->getExpr()) 4237 return Error(E); 4238 return StmtVisitorTy::Visit(E->getExpr()); 4239 } 4240 // We cannot create any objects for which cleanups are required, so there is 4241 // nothing to do here; all cleanups must come from unevaluated subexpressions. 4242 bool VisitExprWithCleanups(const ExprWithCleanups *E) 4243 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4244 4245 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 4246 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 4247 return static_cast<Derived*>(this)->VisitCastExpr(E); 4248 } 4249 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 4250 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 4251 return static_cast<Derived*>(this)->VisitCastExpr(E); 4252 } 4253 4254 bool VisitBinaryOperator(const BinaryOperator *E) { 4255 switch (E->getOpcode()) { 4256 default: 4257 return Error(E); 4258 4259 case BO_Comma: 4260 VisitIgnoredValue(E->getLHS()); 4261 return StmtVisitorTy::Visit(E->getRHS()); 4262 4263 case BO_PtrMemD: 4264 case BO_PtrMemI: { 4265 LValue Obj; 4266 if (!HandleMemberPointerAccess(Info, E, Obj)) 4267 return false; 4268 APValue Result; 4269 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 4270 return false; 4271 return DerivedSuccess(Result, E); 4272 } 4273 } 4274 } 4275 4276 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 4277 // Evaluate and cache the common expression. We treat it as a temporary, 4278 // even though it's not quite the same thing. 4279 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 4280 Info, E->getCommon())) 4281 return false; 4282 4283 return HandleConditionalOperator(E); 4284 } 4285 4286 bool VisitConditionalOperator(const ConditionalOperator *E) { 4287 bool IsBcpCall = false; 4288 // If the condition (ignoring parens) is a __builtin_constant_p call, 4289 // the result is a constant expression if it can be folded without 4290 // side-effects. This is an important GNU extension. See GCC PR38377 4291 // for discussion. 4292 if (const CallExpr *CallCE = 4293 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 4294 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 4295 IsBcpCall = true; 4296 4297 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 4298 // constant expression; we can't check whether it's potentially foldable. 4299 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 4300 return false; 4301 4302 FoldConstant Fold(Info, IsBcpCall); 4303 if (!HandleConditionalOperator(E)) { 4304 Fold.keepDiagnostics(); 4305 return false; 4306 } 4307 4308 return true; 4309 } 4310 4311 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 4312 if (APValue *Value = Info.CurrentCall->getTemporary(E)) 4313 return DerivedSuccess(*Value, E); 4314 4315 const Expr *Source = E->getSourceExpr(); 4316 if (!Source) 4317 return Error(E); 4318 if (Source == E) { // sanity checking. 4319 assert(0 && "OpaqueValueExpr recursively refers to itself"); 4320 return Error(E); 4321 } 4322 return StmtVisitorTy::Visit(Source); 4323 } 4324 4325 bool VisitCallExpr(const CallExpr *E) { 4326 APValue Result; 4327 if (!handleCallExpr(E, Result, nullptr)) 4328 return false; 4329 return DerivedSuccess(Result, E); 4330 } 4331 4332 bool handleCallExpr(const CallExpr *E, APValue &Result, 4333 const LValue *ResultSlot) { 4334 const Expr *Callee = E->getCallee()->IgnoreParens(); 4335 QualType CalleeType = Callee->getType(); 4336 4337 const FunctionDecl *FD = nullptr; 4338 LValue *This = nullptr, ThisVal; 4339 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 4340 bool HasQualifier = false; 4341 4342 // Extract function decl and 'this' pointer from the callee. 4343 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 4344 const ValueDecl *Member = nullptr; 4345 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 4346 // Explicit bound member calls, such as x.f() or p->g(); 4347 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 4348 return false; 4349 Member = ME->getMemberDecl(); 4350 This = &ThisVal; 4351 HasQualifier = ME->hasQualifier(); 4352 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 4353 // Indirect bound member calls ('.*' or '->*'). 4354 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false); 4355 if (!Member) return false; 4356 This = &ThisVal; 4357 } else 4358 return Error(Callee); 4359 4360 FD = dyn_cast<FunctionDecl>(Member); 4361 if (!FD) 4362 return Error(Callee); 4363 } else if (CalleeType->isFunctionPointerType()) { 4364 LValue Call; 4365 if (!EvaluatePointer(Callee, Call, Info)) 4366 return false; 4367 4368 if (!Call.getLValueOffset().isZero()) 4369 return Error(Callee); 4370 FD = dyn_cast_or_null<FunctionDecl>( 4371 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 4372 if (!FD) 4373 return Error(Callee); 4374 4375 // Overloaded operator calls to member functions are represented as normal 4376 // calls with '*this' as the first argument. 4377 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 4378 if (MD && !MD->isStatic()) { 4379 // FIXME: When selecting an implicit conversion for an overloaded 4380 // operator delete, we sometimes try to evaluate calls to conversion 4381 // operators without a 'this' parameter! 4382 if (Args.empty()) 4383 return Error(E); 4384 4385 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 4386 return false; 4387 This = &ThisVal; 4388 Args = Args.slice(1); 4389 } 4390 4391 // Don't call function pointers which have been cast to some other type. 4392 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType())) 4393 return Error(E); 4394 } else 4395 return Error(E); 4396 4397 if (This && !This->checkSubobject(Info, E, CSK_This)) 4398 return false; 4399 4400 // DR1358 allows virtual constexpr functions in some cases. Don't allow 4401 // calls to such functions in constant expressions. 4402 if (This && !HasQualifier && 4403 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual()) 4404 return Error(E, diag::note_constexpr_virtual_call); 4405 4406 const FunctionDecl *Definition = nullptr; 4407 Stmt *Body = FD->getBody(Definition); 4408 4409 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 4410 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 4411 Result, ResultSlot)) 4412 return false; 4413 4414 return true; 4415 } 4416 4417 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 4418 return StmtVisitorTy::Visit(E->getInitializer()); 4419 } 4420 bool VisitInitListExpr(const InitListExpr *E) { 4421 if (E->getNumInits() == 0) 4422 return DerivedZeroInitialization(E); 4423 if (E->getNumInits() == 1) 4424 return StmtVisitorTy::Visit(E->getInit(0)); 4425 return Error(E); 4426 } 4427 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 4428 return DerivedZeroInitialization(E); 4429 } 4430 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 4431 return DerivedZeroInitialization(E); 4432 } 4433 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 4434 return DerivedZeroInitialization(E); 4435 } 4436 4437 /// A member expression where the object is a prvalue is itself a prvalue. 4438 bool VisitMemberExpr(const MemberExpr *E) { 4439 assert(!E->isArrow() && "missing call to bound member function?"); 4440 4441 APValue Val; 4442 if (!Evaluate(Val, Info, E->getBase())) 4443 return false; 4444 4445 QualType BaseTy = E->getBase()->getType(); 4446 4447 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 4448 if (!FD) return Error(E); 4449 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 4450 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 4451 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 4452 4453 CompleteObject Obj(&Val, BaseTy); 4454 SubobjectDesignator Designator(BaseTy); 4455 Designator.addDeclUnchecked(FD); 4456 4457 APValue Result; 4458 return extractSubobject(Info, E, Obj, Designator, Result) && 4459 DerivedSuccess(Result, E); 4460 } 4461 4462 bool VisitCastExpr(const CastExpr *E) { 4463 switch (E->getCastKind()) { 4464 default: 4465 break; 4466 4467 case CK_AtomicToNonAtomic: { 4468 APValue AtomicVal; 4469 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info)) 4470 return false; 4471 return DerivedSuccess(AtomicVal, E); 4472 } 4473 4474 case CK_NoOp: 4475 case CK_UserDefinedConversion: 4476 return StmtVisitorTy::Visit(E->getSubExpr()); 4477 4478 case CK_LValueToRValue: { 4479 LValue LVal; 4480 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 4481 return false; 4482 APValue RVal; 4483 // Note, we use the subexpression's type in order to retain cv-qualifiers. 4484 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 4485 LVal, RVal)) 4486 return false; 4487 return DerivedSuccess(RVal, E); 4488 } 4489 } 4490 4491 return Error(E); 4492 } 4493 4494 bool VisitUnaryPostInc(const UnaryOperator *UO) { 4495 return VisitUnaryPostIncDec(UO); 4496 } 4497 bool VisitUnaryPostDec(const UnaryOperator *UO) { 4498 return VisitUnaryPostIncDec(UO); 4499 } 4500 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 4501 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 4502 return Error(UO); 4503 4504 LValue LVal; 4505 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 4506 return false; 4507 APValue RVal; 4508 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 4509 UO->isIncrementOp(), &RVal)) 4510 return false; 4511 return DerivedSuccess(RVal, UO); 4512 } 4513 4514 bool VisitStmtExpr(const StmtExpr *E) { 4515 // We will have checked the full-expressions inside the statement expression 4516 // when they were completed, and don't need to check them again now. 4517 if (Info.checkingForOverflow()) 4518 return Error(E); 4519 4520 BlockScopeRAII Scope(Info); 4521 const CompoundStmt *CS = E->getSubStmt(); 4522 if (CS->body_empty()) 4523 return true; 4524 4525 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 4526 BE = CS->body_end(); 4527 /**/; ++BI) { 4528 if (BI + 1 == BE) { 4529 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 4530 if (!FinalExpr) { 4531 Info.FFDiag((*BI)->getLocStart(), 4532 diag::note_constexpr_stmt_expr_unsupported); 4533 return false; 4534 } 4535 return this->Visit(FinalExpr); 4536 } 4537 4538 APValue ReturnValue; 4539 StmtResult Result = { ReturnValue, nullptr }; 4540 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 4541 if (ESR != ESR_Succeeded) { 4542 // FIXME: If the statement-expression terminated due to 'return', 4543 // 'break', or 'continue', it would be nice to propagate that to 4544 // the outer statement evaluation rather than bailing out. 4545 if (ESR != ESR_Failed) 4546 Info.FFDiag((*BI)->getLocStart(), 4547 diag::note_constexpr_stmt_expr_unsupported); 4548 return false; 4549 } 4550 } 4551 4552 llvm_unreachable("Return from function from the loop above."); 4553 } 4554 4555 /// Visit a value which is evaluated, but whose value is ignored. 4556 void VisitIgnoredValue(const Expr *E) { 4557 EvaluateIgnoredValue(Info, E); 4558 } 4559 4560 /// Potentially visit a MemberExpr's base expression. 4561 void VisitIgnoredBaseExpression(const Expr *E) { 4562 // While MSVC doesn't evaluate the base expression, it does diagnose the 4563 // presence of side-effecting behavior. 4564 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 4565 return; 4566 VisitIgnoredValue(E); 4567 } 4568 }; 4569 4570 } 4571 4572 //===----------------------------------------------------------------------===// 4573 // Common base class for lvalue and temporary evaluation. 4574 //===----------------------------------------------------------------------===// 4575 namespace { 4576 template<class Derived> 4577 class LValueExprEvaluatorBase 4578 : public ExprEvaluatorBase<Derived> { 4579 protected: 4580 LValue &Result; 4581 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 4582 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 4583 4584 bool Success(APValue::LValueBase B) { 4585 Result.set(B); 4586 return true; 4587 } 4588 4589 public: 4590 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) : 4591 ExprEvaluatorBaseTy(Info), Result(Result) {} 4592 4593 bool Success(const APValue &V, const Expr *E) { 4594 Result.setFrom(this->Info.Ctx, V); 4595 return true; 4596 } 4597 4598 bool VisitMemberExpr(const MemberExpr *E) { 4599 // Handle non-static data members. 4600 QualType BaseTy; 4601 bool EvalOK; 4602 if (E->isArrow()) { 4603 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info); 4604 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 4605 } else if (E->getBase()->isRValue()) { 4606 assert(E->getBase()->getType()->isRecordType()); 4607 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 4608 BaseTy = E->getBase()->getType(); 4609 } else { 4610 EvalOK = this->Visit(E->getBase()); 4611 BaseTy = E->getBase()->getType(); 4612 } 4613 if (!EvalOK) { 4614 if (!this->Info.allowInvalidBaseExpr()) 4615 return false; 4616 Result.setInvalid(E); 4617 return true; 4618 } 4619 4620 const ValueDecl *MD = E->getMemberDecl(); 4621 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 4622 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 4623 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 4624 (void)BaseTy; 4625 if (!HandleLValueMember(this->Info, E, Result, FD)) 4626 return false; 4627 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 4628 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 4629 return false; 4630 } else 4631 return this->Error(E); 4632 4633 if (MD->getType()->isReferenceType()) { 4634 APValue RefValue; 4635 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 4636 RefValue)) 4637 return false; 4638 return Success(RefValue, E); 4639 } 4640 return true; 4641 } 4642 4643 bool VisitBinaryOperator(const BinaryOperator *E) { 4644 switch (E->getOpcode()) { 4645 default: 4646 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 4647 4648 case BO_PtrMemD: 4649 case BO_PtrMemI: 4650 return HandleMemberPointerAccess(this->Info, E, Result); 4651 } 4652 } 4653 4654 bool VisitCastExpr(const CastExpr *E) { 4655 switch (E->getCastKind()) { 4656 default: 4657 return ExprEvaluatorBaseTy::VisitCastExpr(E); 4658 4659 case CK_DerivedToBase: 4660 case CK_UncheckedDerivedToBase: 4661 if (!this->Visit(E->getSubExpr())) 4662 return false; 4663 4664 // Now figure out the necessary offset to add to the base LV to get from 4665 // the derived class to the base class. 4666 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 4667 Result); 4668 } 4669 } 4670 }; 4671 } 4672 4673 //===----------------------------------------------------------------------===// 4674 // LValue Evaluation 4675 // 4676 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 4677 // function designators (in C), decl references to void objects (in C), and 4678 // temporaries (if building with -Wno-address-of-temporary). 4679 // 4680 // LValue evaluation produces values comprising a base expression of one of the 4681 // following types: 4682 // - Declarations 4683 // * VarDecl 4684 // * FunctionDecl 4685 // - Literals 4686 // * CompoundLiteralExpr in C 4687 // * StringLiteral 4688 // * CXXTypeidExpr 4689 // * PredefinedExpr 4690 // * ObjCStringLiteralExpr 4691 // * ObjCEncodeExpr 4692 // * AddrLabelExpr 4693 // * BlockExpr 4694 // * CallExpr for a MakeStringConstant builtin 4695 // - Locals and temporaries 4696 // * MaterializeTemporaryExpr 4697 // * Any Expr, with a CallIndex indicating the function in which the temporary 4698 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 4699 // from the AST (FIXME). 4700 // * A MaterializeTemporaryExpr that has static storage duration, with no 4701 // CallIndex, for a lifetime-extended temporary. 4702 // plus an offset in bytes. 4703 //===----------------------------------------------------------------------===// 4704 namespace { 4705 class LValueExprEvaluator 4706 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 4707 public: 4708 LValueExprEvaluator(EvalInfo &Info, LValue &Result) : 4709 LValueExprEvaluatorBaseTy(Info, Result) {} 4710 4711 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 4712 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 4713 4714 bool VisitDeclRefExpr(const DeclRefExpr *E); 4715 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 4716 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 4717 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 4718 bool VisitMemberExpr(const MemberExpr *E); 4719 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 4720 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 4721 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 4722 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 4723 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 4724 bool VisitUnaryDeref(const UnaryOperator *E); 4725 bool VisitUnaryReal(const UnaryOperator *E); 4726 bool VisitUnaryImag(const UnaryOperator *E); 4727 bool VisitUnaryPreInc(const UnaryOperator *UO) { 4728 return VisitUnaryPreIncDec(UO); 4729 } 4730 bool VisitUnaryPreDec(const UnaryOperator *UO) { 4731 return VisitUnaryPreIncDec(UO); 4732 } 4733 bool VisitBinAssign(const BinaryOperator *BO); 4734 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 4735 4736 bool VisitCastExpr(const CastExpr *E) { 4737 switch (E->getCastKind()) { 4738 default: 4739 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 4740 4741 case CK_LValueBitCast: 4742 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 4743 if (!Visit(E->getSubExpr())) 4744 return false; 4745 Result.Designator.setInvalid(); 4746 return true; 4747 4748 case CK_BaseToDerived: 4749 if (!Visit(E->getSubExpr())) 4750 return false; 4751 return HandleBaseToDerivedCast(Info, E, Result); 4752 } 4753 } 4754 }; 4755 } // end anonymous namespace 4756 4757 /// Evaluate an expression as an lvalue. This can be legitimately called on 4758 /// expressions which are not glvalues, in three cases: 4759 /// * function designators in C, and 4760 /// * "extern void" objects 4761 /// * @selector() expressions in Objective-C 4762 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) { 4763 assert(E->isGLValue() || E->getType()->isFunctionType() || 4764 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 4765 return LValueExprEvaluator(Info, Result).Visit(E); 4766 } 4767 4768 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 4769 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 4770 return Success(FD); 4771 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 4772 return VisitVarDecl(E, VD); 4773 return Error(E); 4774 } 4775 4776 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 4777 CallStackFrame *Frame = nullptr; 4778 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) 4779 Frame = Info.CurrentCall; 4780 4781 if (!VD->getType()->isReferenceType()) { 4782 if (Frame) { 4783 Result.set(VD, Frame->Index); 4784 return true; 4785 } 4786 return Success(VD); 4787 } 4788 4789 APValue *V; 4790 if (!evaluateVarDeclInit(Info, E, VD, Frame, V)) 4791 return false; 4792 if (V->isUninit()) { 4793 if (!Info.checkingPotentialConstantExpression()) 4794 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 4795 return false; 4796 } 4797 return Success(*V, E); 4798 } 4799 4800 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 4801 const MaterializeTemporaryExpr *E) { 4802 // Walk through the expression to find the materialized temporary itself. 4803 SmallVector<const Expr *, 2> CommaLHSs; 4804 SmallVector<SubobjectAdjustment, 2> Adjustments; 4805 const Expr *Inner = E->GetTemporaryExpr()-> 4806 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 4807 4808 // If we passed any comma operators, evaluate their LHSs. 4809 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 4810 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 4811 return false; 4812 4813 // A materialized temporary with static storage duration can appear within the 4814 // result of a constant expression evaluation, so we need to preserve its 4815 // value for use outside this evaluation. 4816 APValue *Value; 4817 if (E->getStorageDuration() == SD_Static) { 4818 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 4819 *Value = APValue(); 4820 Result.set(E); 4821 } else { 4822 Value = &Info.CurrentCall-> 4823 createTemporary(E, E->getStorageDuration() == SD_Automatic); 4824 Result.set(E, Info.CurrentCall->Index); 4825 } 4826 4827 QualType Type = Inner->getType(); 4828 4829 // Materialize the temporary itself. 4830 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 4831 (E->getStorageDuration() == SD_Static && 4832 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 4833 *Value = APValue(); 4834 return false; 4835 } 4836 4837 // Adjust our lvalue to refer to the desired subobject. 4838 for (unsigned I = Adjustments.size(); I != 0; /**/) { 4839 --I; 4840 switch (Adjustments[I].Kind) { 4841 case SubobjectAdjustment::DerivedToBaseAdjustment: 4842 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 4843 Type, Result)) 4844 return false; 4845 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 4846 break; 4847 4848 case SubobjectAdjustment::FieldAdjustment: 4849 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 4850 return false; 4851 Type = Adjustments[I].Field->getType(); 4852 break; 4853 4854 case SubobjectAdjustment::MemberPointerAdjustment: 4855 if (!HandleMemberPointerAccess(this->Info, Type, Result, 4856 Adjustments[I].Ptr.RHS)) 4857 return false; 4858 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 4859 break; 4860 } 4861 } 4862 4863 return true; 4864 } 4865 4866 bool 4867 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 4868 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?"); 4869 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 4870 // only see this when folding in C, so there's no standard to follow here. 4871 return Success(E); 4872 } 4873 4874 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 4875 if (!E->isPotentiallyEvaluated()) 4876 return Success(E); 4877 4878 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic) 4879 << E->getExprOperand()->getType() 4880 << E->getExprOperand()->getSourceRange(); 4881 return false; 4882 } 4883 4884 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 4885 return Success(E); 4886 } 4887 4888 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 4889 // Handle static data members. 4890 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 4891 VisitIgnoredBaseExpression(E->getBase()); 4892 return VisitVarDecl(E, VD); 4893 } 4894 4895 // Handle static member functions. 4896 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 4897 if (MD->isStatic()) { 4898 VisitIgnoredBaseExpression(E->getBase()); 4899 return Success(MD); 4900 } 4901 } 4902 4903 // Handle non-static data members. 4904 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 4905 } 4906 4907 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 4908 // FIXME: Deal with vectors as array subscript bases. 4909 if (E->getBase()->getType()->isVectorType()) 4910 return Error(E); 4911 4912 if (!EvaluatePointer(E->getBase(), Result, Info)) 4913 return false; 4914 4915 APSInt Index; 4916 if (!EvaluateInteger(E->getIdx(), Index, Info)) 4917 return false; 4918 4919 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), 4920 getExtValue(Index)); 4921 } 4922 4923 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 4924 return EvaluatePointer(E->getSubExpr(), Result, Info); 4925 } 4926 4927 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 4928 if (!Visit(E->getSubExpr())) 4929 return false; 4930 // __real is a no-op on scalar lvalues. 4931 if (E->getSubExpr()->getType()->isAnyComplexType()) 4932 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 4933 return true; 4934 } 4935 4936 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 4937 assert(E->getSubExpr()->getType()->isAnyComplexType() && 4938 "lvalue __imag__ on scalar?"); 4939 if (!Visit(E->getSubExpr())) 4940 return false; 4941 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 4942 return true; 4943 } 4944 4945 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 4946 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 4947 return Error(UO); 4948 4949 if (!this->Visit(UO->getSubExpr())) 4950 return false; 4951 4952 return handleIncDec( 4953 this->Info, UO, Result, UO->getSubExpr()->getType(), 4954 UO->isIncrementOp(), nullptr); 4955 } 4956 4957 bool LValueExprEvaluator::VisitCompoundAssignOperator( 4958 const CompoundAssignOperator *CAO) { 4959 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 4960 return Error(CAO); 4961 4962 APValue RHS; 4963 4964 // The overall lvalue result is the result of evaluating the LHS. 4965 if (!this->Visit(CAO->getLHS())) { 4966 if (Info.noteFailure()) 4967 Evaluate(RHS, this->Info, CAO->getRHS()); 4968 return false; 4969 } 4970 4971 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 4972 return false; 4973 4974 return handleCompoundAssignment( 4975 this->Info, CAO, 4976 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 4977 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 4978 } 4979 4980 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 4981 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 4982 return Error(E); 4983 4984 APValue NewVal; 4985 4986 if (!this->Visit(E->getLHS())) { 4987 if (Info.noteFailure()) 4988 Evaluate(NewVal, this->Info, E->getRHS()); 4989 return false; 4990 } 4991 4992 if (!Evaluate(NewVal, this->Info, E->getRHS())) 4993 return false; 4994 4995 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 4996 NewVal); 4997 } 4998 4999 //===----------------------------------------------------------------------===// 5000 // Pointer Evaluation 5001 //===----------------------------------------------------------------------===// 5002 5003 namespace { 5004 class PointerExprEvaluator 5005 : public ExprEvaluatorBase<PointerExprEvaluator> { 5006 LValue &Result; 5007 5008 bool Success(const Expr *E) { 5009 Result.set(E); 5010 return true; 5011 } 5012 public: 5013 5014 PointerExprEvaluator(EvalInfo &info, LValue &Result) 5015 : ExprEvaluatorBaseTy(info), Result(Result) {} 5016 5017 bool Success(const APValue &V, const Expr *E) { 5018 Result.setFrom(Info.Ctx, V); 5019 return true; 5020 } 5021 bool ZeroInitialization(const Expr *E) { 5022 return Success((Expr*)nullptr); 5023 } 5024 5025 bool VisitBinaryOperator(const BinaryOperator *E); 5026 bool VisitCastExpr(const CastExpr* E); 5027 bool VisitUnaryAddrOf(const UnaryOperator *E); 5028 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 5029 { return Success(E); } 5030 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) 5031 { return Success(E); } 5032 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 5033 { return Success(E); } 5034 bool VisitCallExpr(const CallExpr *E); 5035 bool VisitBlockExpr(const BlockExpr *E) { 5036 if (!E->getBlockDecl()->hasCaptures()) 5037 return Success(E); 5038 return Error(E); 5039 } 5040 bool VisitCXXThisExpr(const CXXThisExpr *E) { 5041 // Can't look at 'this' when checking a potential constant expression. 5042 if (Info.checkingPotentialConstantExpression()) 5043 return false; 5044 if (!Info.CurrentCall->This) { 5045 if (Info.getLangOpts().CPlusPlus11) 5046 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 5047 else 5048 Info.FFDiag(E); 5049 return false; 5050 } 5051 Result = *Info.CurrentCall->This; 5052 return true; 5053 } 5054 5055 // FIXME: Missing: @protocol, @selector 5056 }; 5057 } // end anonymous namespace 5058 5059 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) { 5060 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 5061 return PointerExprEvaluator(Info, Result).Visit(E); 5062 } 5063 5064 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 5065 if (E->getOpcode() != BO_Add && 5066 E->getOpcode() != BO_Sub) 5067 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5068 5069 const Expr *PExp = E->getLHS(); 5070 const Expr *IExp = E->getRHS(); 5071 if (IExp->getType()->isPointerType()) 5072 std::swap(PExp, IExp); 5073 5074 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info); 5075 if (!EvalPtrOK && !Info.noteFailure()) 5076 return false; 5077 5078 llvm::APSInt Offset; 5079 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 5080 return false; 5081 5082 int64_t AdditionalOffset = getExtValue(Offset); 5083 if (E->getOpcode() == BO_Sub) 5084 AdditionalOffset = -AdditionalOffset; 5085 5086 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 5087 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, 5088 AdditionalOffset); 5089 } 5090 5091 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 5092 return EvaluateLValue(E->getSubExpr(), Result, Info); 5093 } 5094 5095 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { 5096 const Expr* SubExpr = E->getSubExpr(); 5097 5098 switch (E->getCastKind()) { 5099 default: 5100 break; 5101 5102 case CK_BitCast: 5103 case CK_CPointerToObjCPointerCast: 5104 case CK_BlockPointerToObjCPointerCast: 5105 case CK_AnyPointerToBlockPointerCast: 5106 case CK_AddressSpaceConversion: 5107 if (!Visit(SubExpr)) 5108 return false; 5109 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 5110 // permitted in constant expressions in C++11. Bitcasts from cv void* are 5111 // also static_casts, but we disallow them as a resolution to DR1312. 5112 if (!E->getType()->isVoidPointerType()) { 5113 Result.Designator.setInvalid(); 5114 if (SubExpr->getType()->isVoidPointerType()) 5115 CCEDiag(E, diag::note_constexpr_invalid_cast) 5116 << 3 << SubExpr->getType(); 5117 else 5118 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5119 } 5120 return true; 5121 5122 case CK_DerivedToBase: 5123 case CK_UncheckedDerivedToBase: 5124 if (!EvaluatePointer(E->getSubExpr(), Result, Info)) 5125 return false; 5126 if (!Result.Base && Result.Offset.isZero()) 5127 return true; 5128 5129 // Now figure out the necessary offset to add to the base LV to get from 5130 // the derived class to the base class. 5131 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 5132 castAs<PointerType>()->getPointeeType(), 5133 Result); 5134 5135 case CK_BaseToDerived: 5136 if (!Visit(E->getSubExpr())) 5137 return false; 5138 if (!Result.Base && Result.Offset.isZero()) 5139 return true; 5140 return HandleBaseToDerivedCast(Info, E, Result); 5141 5142 case CK_NullToPointer: 5143 VisitIgnoredValue(E->getSubExpr()); 5144 return ZeroInitialization(E); 5145 5146 case CK_IntegralToPointer: { 5147 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5148 5149 APValue Value; 5150 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 5151 break; 5152 5153 if (Value.isInt()) { 5154 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 5155 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 5156 Result.Base = (Expr*)nullptr; 5157 Result.InvalidBase = false; 5158 Result.Offset = CharUnits::fromQuantity(N); 5159 Result.CallIndex = 0; 5160 Result.Designator.setInvalid(); 5161 return true; 5162 } else { 5163 // Cast is of an lvalue, no need to change value. 5164 Result.setFrom(Info.Ctx, Value); 5165 return true; 5166 } 5167 } 5168 case CK_ArrayToPointerDecay: 5169 if (SubExpr->isGLValue()) { 5170 if (!EvaluateLValue(SubExpr, Result, Info)) 5171 return false; 5172 } else { 5173 Result.set(SubExpr, Info.CurrentCall->Index); 5174 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false), 5175 Info, Result, SubExpr)) 5176 return false; 5177 } 5178 // The result is a pointer to the first element of the array. 5179 if (const ConstantArrayType *CAT 5180 = Info.Ctx.getAsConstantArrayType(SubExpr->getType())) 5181 Result.addArray(Info, E, CAT); 5182 else 5183 Result.Designator.setInvalid(); 5184 return true; 5185 5186 case CK_FunctionToPointerDecay: 5187 return EvaluateLValue(SubExpr, Result, Info); 5188 } 5189 5190 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5191 } 5192 5193 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) { 5194 // C++ [expr.alignof]p3: 5195 // When alignof is applied to a reference type, the result is the 5196 // alignment of the referenced type. 5197 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 5198 T = Ref->getPointeeType(); 5199 5200 // __alignof is defined to return the preferred alignment. 5201 return Info.Ctx.toCharUnitsFromBits( 5202 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 5203 } 5204 5205 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) { 5206 E = E->IgnoreParens(); 5207 5208 // The kinds of expressions that we have special-case logic here for 5209 // should be kept up to date with the special checks for those 5210 // expressions in Sema. 5211 5212 // alignof decl is always accepted, even if it doesn't make sense: we default 5213 // to 1 in those cases. 5214 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5215 return Info.Ctx.getDeclAlign(DRE->getDecl(), 5216 /*RefAsPointee*/true); 5217 5218 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 5219 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 5220 /*RefAsPointee*/true); 5221 5222 return GetAlignOfType(Info, E->getType()); 5223 } 5224 5225 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 5226 if (IsStringLiteralCall(E)) 5227 return Success(E); 5228 5229 switch (E->getBuiltinCallee()) { 5230 case Builtin::BI__builtin_addressof: 5231 return EvaluateLValue(E->getArg(0), Result, Info); 5232 case Builtin::BI__builtin_assume_aligned: { 5233 // We need to be very careful here because: if the pointer does not have the 5234 // asserted alignment, then the behavior is undefined, and undefined 5235 // behavior is non-constant. 5236 if (!EvaluatePointer(E->getArg(0), Result, Info)) 5237 return false; 5238 5239 LValue OffsetResult(Result); 5240 APSInt Alignment; 5241 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 5242 return false; 5243 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment)); 5244 5245 if (E->getNumArgs() > 2) { 5246 APSInt Offset; 5247 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 5248 return false; 5249 5250 int64_t AdditionalOffset = -getExtValue(Offset); 5251 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 5252 } 5253 5254 // If there is a base object, then it must have the correct alignment. 5255 if (OffsetResult.Base) { 5256 CharUnits BaseAlignment; 5257 if (const ValueDecl *VD = 5258 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 5259 BaseAlignment = Info.Ctx.getDeclAlign(VD); 5260 } else { 5261 BaseAlignment = 5262 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>()); 5263 } 5264 5265 if (BaseAlignment < Align) { 5266 Result.Designator.setInvalid(); 5267 // FIXME: Quantities here cast to integers because the plural modifier 5268 // does not work on APSInts yet. 5269 CCEDiag(E->getArg(0), 5270 diag::note_constexpr_baa_insufficient_alignment) << 0 5271 << (int) BaseAlignment.getQuantity() 5272 << (unsigned) getExtValue(Alignment); 5273 return false; 5274 } 5275 } 5276 5277 // The offset must also have the correct alignment. 5278 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 5279 Result.Designator.setInvalid(); 5280 APSInt Offset(64, false); 5281 Offset = OffsetResult.Offset.getQuantity(); 5282 5283 if (OffsetResult.Base) 5284 CCEDiag(E->getArg(0), 5285 diag::note_constexpr_baa_insufficient_alignment) << 1 5286 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment); 5287 else 5288 CCEDiag(E->getArg(0), 5289 diag::note_constexpr_baa_value_insufficient_alignment) 5290 << Offset << (unsigned) getExtValue(Alignment); 5291 5292 return false; 5293 } 5294 5295 return true; 5296 } 5297 default: 5298 return ExprEvaluatorBaseTy::VisitCallExpr(E); 5299 } 5300 } 5301 5302 //===----------------------------------------------------------------------===// 5303 // Member Pointer Evaluation 5304 //===----------------------------------------------------------------------===// 5305 5306 namespace { 5307 class MemberPointerExprEvaluator 5308 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 5309 MemberPtr &Result; 5310 5311 bool Success(const ValueDecl *D) { 5312 Result = MemberPtr(D); 5313 return true; 5314 } 5315 public: 5316 5317 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 5318 : ExprEvaluatorBaseTy(Info), Result(Result) {} 5319 5320 bool Success(const APValue &V, const Expr *E) { 5321 Result.setFrom(V); 5322 return true; 5323 } 5324 bool ZeroInitialization(const Expr *E) { 5325 return Success((const ValueDecl*)nullptr); 5326 } 5327 5328 bool VisitCastExpr(const CastExpr *E); 5329 bool VisitUnaryAddrOf(const UnaryOperator *E); 5330 }; 5331 } // end anonymous namespace 5332 5333 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 5334 EvalInfo &Info) { 5335 assert(E->isRValue() && E->getType()->isMemberPointerType()); 5336 return MemberPointerExprEvaluator(Info, Result).Visit(E); 5337 } 5338 5339 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 5340 switch (E->getCastKind()) { 5341 default: 5342 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5343 5344 case CK_NullToMemberPointer: 5345 VisitIgnoredValue(E->getSubExpr()); 5346 return ZeroInitialization(E); 5347 5348 case CK_BaseToDerivedMemberPointer: { 5349 if (!Visit(E->getSubExpr())) 5350 return false; 5351 if (E->path_empty()) 5352 return true; 5353 // Base-to-derived member pointer casts store the path in derived-to-base 5354 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 5355 // the wrong end of the derived->base arc, so stagger the path by one class. 5356 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 5357 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 5358 PathI != PathE; ++PathI) { 5359 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 5360 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 5361 if (!Result.castToDerived(Derived)) 5362 return Error(E); 5363 } 5364 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 5365 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 5366 return Error(E); 5367 return true; 5368 } 5369 5370 case CK_DerivedToBaseMemberPointer: 5371 if (!Visit(E->getSubExpr())) 5372 return false; 5373 for (CastExpr::path_const_iterator PathI = E->path_begin(), 5374 PathE = E->path_end(); PathI != PathE; ++PathI) { 5375 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 5376 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 5377 if (!Result.castToBase(Base)) 5378 return Error(E); 5379 } 5380 return true; 5381 } 5382 } 5383 5384 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 5385 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 5386 // member can be formed. 5387 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 5388 } 5389 5390 //===----------------------------------------------------------------------===// 5391 // Record Evaluation 5392 //===----------------------------------------------------------------------===// 5393 5394 namespace { 5395 class RecordExprEvaluator 5396 : public ExprEvaluatorBase<RecordExprEvaluator> { 5397 const LValue &This; 5398 APValue &Result; 5399 public: 5400 5401 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 5402 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 5403 5404 bool Success(const APValue &V, const Expr *E) { 5405 Result = V; 5406 return true; 5407 } 5408 bool ZeroInitialization(const Expr *E) { 5409 return ZeroInitialization(E, E->getType()); 5410 } 5411 bool ZeroInitialization(const Expr *E, QualType T); 5412 5413 bool VisitCallExpr(const CallExpr *E) { 5414 return handleCallExpr(E, Result, &This); 5415 } 5416 bool VisitCastExpr(const CastExpr *E); 5417 bool VisitInitListExpr(const InitListExpr *E); 5418 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 5419 return VisitCXXConstructExpr(E, E->getType()); 5420 } 5421 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 5422 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 5423 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 5424 }; 5425 } 5426 5427 /// Perform zero-initialization on an object of non-union class type. 5428 /// C++11 [dcl.init]p5: 5429 /// To zero-initialize an object or reference of type T means: 5430 /// [...] 5431 /// -- if T is a (possibly cv-qualified) non-union class type, 5432 /// each non-static data member and each base-class subobject is 5433 /// zero-initialized 5434 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 5435 const RecordDecl *RD, 5436 const LValue &This, APValue &Result) { 5437 assert(!RD->isUnion() && "Expected non-union class type"); 5438 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 5439 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 5440 std::distance(RD->field_begin(), RD->field_end())); 5441 5442 if (RD->isInvalidDecl()) return false; 5443 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5444 5445 if (CD) { 5446 unsigned Index = 0; 5447 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 5448 End = CD->bases_end(); I != End; ++I, ++Index) { 5449 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 5450 LValue Subobject = This; 5451 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 5452 return false; 5453 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 5454 Result.getStructBase(Index))) 5455 return false; 5456 } 5457 } 5458 5459 for (const auto *I : RD->fields()) { 5460 // -- if T is a reference type, no initialization is performed. 5461 if (I->getType()->isReferenceType()) 5462 continue; 5463 5464 LValue Subobject = This; 5465 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 5466 return false; 5467 5468 ImplicitValueInitExpr VIE(I->getType()); 5469 if (!EvaluateInPlace( 5470 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 5471 return false; 5472 } 5473 5474 return true; 5475 } 5476 5477 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 5478 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 5479 if (RD->isInvalidDecl()) return false; 5480 if (RD->isUnion()) { 5481 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 5482 // object's first non-static named data member is zero-initialized 5483 RecordDecl::field_iterator I = RD->field_begin(); 5484 if (I == RD->field_end()) { 5485 Result = APValue((const FieldDecl*)nullptr); 5486 return true; 5487 } 5488 5489 LValue Subobject = This; 5490 if (!HandleLValueMember(Info, E, Subobject, *I)) 5491 return false; 5492 Result = APValue(*I); 5493 ImplicitValueInitExpr VIE(I->getType()); 5494 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 5495 } 5496 5497 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 5498 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 5499 return false; 5500 } 5501 5502 return HandleClassZeroInitialization(Info, E, RD, This, Result); 5503 } 5504 5505 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 5506 switch (E->getCastKind()) { 5507 default: 5508 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5509 5510 case CK_ConstructorConversion: 5511 return Visit(E->getSubExpr()); 5512 5513 case CK_DerivedToBase: 5514 case CK_UncheckedDerivedToBase: { 5515 APValue DerivedObject; 5516 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 5517 return false; 5518 if (!DerivedObject.isStruct()) 5519 return Error(E->getSubExpr()); 5520 5521 // Derived-to-base rvalue conversion: just slice off the derived part. 5522 APValue *Value = &DerivedObject; 5523 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 5524 for (CastExpr::path_const_iterator PathI = E->path_begin(), 5525 PathE = E->path_end(); PathI != PathE; ++PathI) { 5526 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 5527 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 5528 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 5529 RD = Base; 5530 } 5531 Result = *Value; 5532 return true; 5533 } 5534 } 5535 } 5536 5537 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 5538 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 5539 if (RD->isInvalidDecl()) return false; 5540 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5541 5542 if (RD->isUnion()) { 5543 const FieldDecl *Field = E->getInitializedFieldInUnion(); 5544 Result = APValue(Field); 5545 if (!Field) 5546 return true; 5547 5548 // If the initializer list for a union does not contain any elements, the 5549 // first element of the union is value-initialized. 5550 // FIXME: The element should be initialized from an initializer list. 5551 // Is this difference ever observable for initializer lists which 5552 // we don't build? 5553 ImplicitValueInitExpr VIE(Field->getType()); 5554 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 5555 5556 LValue Subobject = This; 5557 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 5558 return false; 5559 5560 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 5561 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 5562 isa<CXXDefaultInitExpr>(InitExpr)); 5563 5564 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 5565 } 5566 5567 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 5568 if (Result.isUninit()) 5569 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 5570 std::distance(RD->field_begin(), RD->field_end())); 5571 unsigned ElementNo = 0; 5572 bool Success = true; 5573 5574 // Initialize base classes. 5575 if (CXXRD) { 5576 for (const auto &Base : CXXRD->bases()) { 5577 assert(ElementNo < E->getNumInits() && "missing init for base class"); 5578 const Expr *Init = E->getInit(ElementNo); 5579 5580 LValue Subobject = This; 5581 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 5582 return false; 5583 5584 APValue &FieldVal = Result.getStructBase(ElementNo); 5585 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 5586 if (!Info.noteFailure()) 5587 return false; 5588 Success = false; 5589 } 5590 ++ElementNo; 5591 } 5592 } 5593 5594 // Initialize members. 5595 for (const auto *Field : RD->fields()) { 5596 // Anonymous bit-fields are not considered members of the class for 5597 // purposes of aggregate initialization. 5598 if (Field->isUnnamedBitfield()) 5599 continue; 5600 5601 LValue Subobject = This; 5602 5603 bool HaveInit = ElementNo < E->getNumInits(); 5604 5605 // FIXME: Diagnostics here should point to the end of the initializer 5606 // list, not the start. 5607 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 5608 Subobject, Field, &Layout)) 5609 return false; 5610 5611 // Perform an implicit value-initialization for members beyond the end of 5612 // the initializer list. 5613 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 5614 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 5615 5616 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 5617 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 5618 isa<CXXDefaultInitExpr>(Init)); 5619 5620 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 5621 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 5622 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 5623 FieldVal, Field))) { 5624 if (!Info.noteFailure()) 5625 return false; 5626 Success = false; 5627 } 5628 } 5629 5630 return Success; 5631 } 5632 5633 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 5634 QualType T) { 5635 // Note that E's type is not necessarily the type of our class here; we might 5636 // be initializing an array element instead. 5637 const CXXConstructorDecl *FD = E->getConstructor(); 5638 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 5639 5640 bool ZeroInit = E->requiresZeroInitialization(); 5641 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 5642 // If we've already performed zero-initialization, we're already done. 5643 if (!Result.isUninit()) 5644 return true; 5645 5646 // We can get here in two different ways: 5647 // 1) We're performing value-initialization, and should zero-initialize 5648 // the object, or 5649 // 2) We're performing default-initialization of an object with a trivial 5650 // constexpr default constructor, in which case we should start the 5651 // lifetimes of all the base subobjects (there can be no data member 5652 // subobjects in this case) per [basic.life]p1. 5653 // Either way, ZeroInitialization is appropriate. 5654 return ZeroInitialization(E, T); 5655 } 5656 5657 const FunctionDecl *Definition = nullptr; 5658 auto Body = FD->getBody(Definition); 5659 5660 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 5661 return false; 5662 5663 // Avoid materializing a temporary for an elidable copy/move constructor. 5664 if (E->isElidable() && !ZeroInit) 5665 if (const MaterializeTemporaryExpr *ME 5666 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 5667 return Visit(ME->GetTemporaryExpr()); 5668 5669 if (ZeroInit && !ZeroInitialization(E, T)) 5670 return false; 5671 5672 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 5673 return HandleConstructorCall(E, This, Args, 5674 cast<CXXConstructorDecl>(Definition), Info, 5675 Result); 5676 } 5677 5678 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 5679 const CXXInheritedCtorInitExpr *E) { 5680 if (!Info.CurrentCall) { 5681 assert(Info.checkingPotentialConstantExpression()); 5682 return false; 5683 } 5684 5685 const CXXConstructorDecl *FD = E->getConstructor(); 5686 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 5687 return false; 5688 5689 const FunctionDecl *Definition = nullptr; 5690 auto Body = FD->getBody(Definition); 5691 5692 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 5693 return false; 5694 5695 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 5696 cast<CXXConstructorDecl>(Definition), Info, 5697 Result); 5698 } 5699 5700 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 5701 const CXXStdInitializerListExpr *E) { 5702 const ConstantArrayType *ArrayType = 5703 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 5704 5705 LValue Array; 5706 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 5707 return false; 5708 5709 // Get a pointer to the first element of the array. 5710 Array.addArray(Info, E, ArrayType); 5711 5712 // FIXME: Perform the checks on the field types in SemaInit. 5713 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 5714 RecordDecl::field_iterator Field = Record->field_begin(); 5715 if (Field == Record->field_end()) 5716 return Error(E); 5717 5718 // Start pointer. 5719 if (!Field->getType()->isPointerType() || 5720 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 5721 ArrayType->getElementType())) 5722 return Error(E); 5723 5724 // FIXME: What if the initializer_list type has base classes, etc? 5725 Result = APValue(APValue::UninitStruct(), 0, 2); 5726 Array.moveInto(Result.getStructField(0)); 5727 5728 if (++Field == Record->field_end()) 5729 return Error(E); 5730 5731 if (Field->getType()->isPointerType() && 5732 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 5733 ArrayType->getElementType())) { 5734 // End pointer. 5735 if (!HandleLValueArrayAdjustment(Info, E, Array, 5736 ArrayType->getElementType(), 5737 ArrayType->getSize().getZExtValue())) 5738 return false; 5739 Array.moveInto(Result.getStructField(1)); 5740 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 5741 // Length. 5742 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 5743 else 5744 return Error(E); 5745 5746 if (++Field != Record->field_end()) 5747 return Error(E); 5748 5749 return true; 5750 } 5751 5752 static bool EvaluateRecord(const Expr *E, const LValue &This, 5753 APValue &Result, EvalInfo &Info) { 5754 assert(E->isRValue() && E->getType()->isRecordType() && 5755 "can't evaluate expression as a record rvalue"); 5756 return RecordExprEvaluator(Info, This, Result).Visit(E); 5757 } 5758 5759 //===----------------------------------------------------------------------===// 5760 // Temporary Evaluation 5761 // 5762 // Temporaries are represented in the AST as rvalues, but generally behave like 5763 // lvalues. The full-object of which the temporary is a subobject is implicitly 5764 // materialized so that a reference can bind to it. 5765 //===----------------------------------------------------------------------===// 5766 namespace { 5767 class TemporaryExprEvaluator 5768 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 5769 public: 5770 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 5771 LValueExprEvaluatorBaseTy(Info, Result) {} 5772 5773 /// Visit an expression which constructs the value of this temporary. 5774 bool VisitConstructExpr(const Expr *E) { 5775 Result.set(E, Info.CurrentCall->Index); 5776 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false), 5777 Info, Result, E); 5778 } 5779 5780 bool VisitCastExpr(const CastExpr *E) { 5781 switch (E->getCastKind()) { 5782 default: 5783 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 5784 5785 case CK_ConstructorConversion: 5786 return VisitConstructExpr(E->getSubExpr()); 5787 } 5788 } 5789 bool VisitInitListExpr(const InitListExpr *E) { 5790 return VisitConstructExpr(E); 5791 } 5792 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 5793 return VisitConstructExpr(E); 5794 } 5795 bool VisitCallExpr(const CallExpr *E) { 5796 return VisitConstructExpr(E); 5797 } 5798 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 5799 return VisitConstructExpr(E); 5800 } 5801 }; 5802 } // end anonymous namespace 5803 5804 /// Evaluate an expression of record type as a temporary. 5805 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 5806 assert(E->isRValue() && E->getType()->isRecordType()); 5807 return TemporaryExprEvaluator(Info, Result).Visit(E); 5808 } 5809 5810 //===----------------------------------------------------------------------===// 5811 // Vector Evaluation 5812 //===----------------------------------------------------------------------===// 5813 5814 namespace { 5815 class VectorExprEvaluator 5816 : public ExprEvaluatorBase<VectorExprEvaluator> { 5817 APValue &Result; 5818 public: 5819 5820 VectorExprEvaluator(EvalInfo &info, APValue &Result) 5821 : ExprEvaluatorBaseTy(info), Result(Result) {} 5822 5823 bool Success(ArrayRef<APValue> V, const Expr *E) { 5824 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 5825 // FIXME: remove this APValue copy. 5826 Result = APValue(V.data(), V.size()); 5827 return true; 5828 } 5829 bool Success(const APValue &V, const Expr *E) { 5830 assert(V.isVector()); 5831 Result = V; 5832 return true; 5833 } 5834 bool ZeroInitialization(const Expr *E); 5835 5836 bool VisitUnaryReal(const UnaryOperator *E) 5837 { return Visit(E->getSubExpr()); } 5838 bool VisitCastExpr(const CastExpr* E); 5839 bool VisitInitListExpr(const InitListExpr *E); 5840 bool VisitUnaryImag(const UnaryOperator *E); 5841 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 5842 // binary comparisons, binary and/or/xor, 5843 // shufflevector, ExtVectorElementExpr 5844 }; 5845 } // end anonymous namespace 5846 5847 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 5848 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 5849 return VectorExprEvaluator(Info, Result).Visit(E); 5850 } 5851 5852 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 5853 const VectorType *VTy = E->getType()->castAs<VectorType>(); 5854 unsigned NElts = VTy->getNumElements(); 5855 5856 const Expr *SE = E->getSubExpr(); 5857 QualType SETy = SE->getType(); 5858 5859 switch (E->getCastKind()) { 5860 case CK_VectorSplat: { 5861 APValue Val = APValue(); 5862 if (SETy->isIntegerType()) { 5863 APSInt IntResult; 5864 if (!EvaluateInteger(SE, IntResult, Info)) 5865 return false; 5866 Val = APValue(std::move(IntResult)); 5867 } else if (SETy->isRealFloatingType()) { 5868 APFloat FloatResult(0.0); 5869 if (!EvaluateFloat(SE, FloatResult, Info)) 5870 return false; 5871 Val = APValue(std::move(FloatResult)); 5872 } else { 5873 return Error(E); 5874 } 5875 5876 // Splat and create vector APValue. 5877 SmallVector<APValue, 4> Elts(NElts, Val); 5878 return Success(Elts, E); 5879 } 5880 case CK_BitCast: { 5881 // Evaluate the operand into an APInt we can extract from. 5882 llvm::APInt SValInt; 5883 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 5884 return false; 5885 // Extract the elements 5886 QualType EltTy = VTy->getElementType(); 5887 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 5888 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 5889 SmallVector<APValue, 4> Elts; 5890 if (EltTy->isRealFloatingType()) { 5891 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 5892 unsigned FloatEltSize = EltSize; 5893 if (&Sem == &APFloat::x87DoubleExtended) 5894 FloatEltSize = 80; 5895 for (unsigned i = 0; i < NElts; i++) { 5896 llvm::APInt Elt; 5897 if (BigEndian) 5898 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 5899 else 5900 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 5901 Elts.push_back(APValue(APFloat(Sem, Elt))); 5902 } 5903 } else if (EltTy->isIntegerType()) { 5904 for (unsigned i = 0; i < NElts; i++) { 5905 llvm::APInt Elt; 5906 if (BigEndian) 5907 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 5908 else 5909 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 5910 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 5911 } 5912 } else { 5913 return Error(E); 5914 } 5915 return Success(Elts, E); 5916 } 5917 default: 5918 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5919 } 5920 } 5921 5922 bool 5923 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 5924 const VectorType *VT = E->getType()->castAs<VectorType>(); 5925 unsigned NumInits = E->getNumInits(); 5926 unsigned NumElements = VT->getNumElements(); 5927 5928 QualType EltTy = VT->getElementType(); 5929 SmallVector<APValue, 4> Elements; 5930 5931 // The number of initializers can be less than the number of 5932 // vector elements. For OpenCL, this can be due to nested vector 5933 // initialization. For GCC compatibility, missing trailing elements 5934 // should be initialized with zeroes. 5935 unsigned CountInits = 0, CountElts = 0; 5936 while (CountElts < NumElements) { 5937 // Handle nested vector initialization. 5938 if (CountInits < NumInits 5939 && E->getInit(CountInits)->getType()->isVectorType()) { 5940 APValue v; 5941 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 5942 return Error(E); 5943 unsigned vlen = v.getVectorLength(); 5944 for (unsigned j = 0; j < vlen; j++) 5945 Elements.push_back(v.getVectorElt(j)); 5946 CountElts += vlen; 5947 } else if (EltTy->isIntegerType()) { 5948 llvm::APSInt sInt(32); 5949 if (CountInits < NumInits) { 5950 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 5951 return false; 5952 } else // trailing integer zero. 5953 sInt = Info.Ctx.MakeIntValue(0, EltTy); 5954 Elements.push_back(APValue(sInt)); 5955 CountElts++; 5956 } else { 5957 llvm::APFloat f(0.0); 5958 if (CountInits < NumInits) { 5959 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 5960 return false; 5961 } else // trailing float zero. 5962 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 5963 Elements.push_back(APValue(f)); 5964 CountElts++; 5965 } 5966 CountInits++; 5967 } 5968 return Success(Elements, E); 5969 } 5970 5971 bool 5972 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 5973 const VectorType *VT = E->getType()->getAs<VectorType>(); 5974 QualType EltTy = VT->getElementType(); 5975 APValue ZeroElement; 5976 if (EltTy->isIntegerType()) 5977 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 5978 else 5979 ZeroElement = 5980 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 5981 5982 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 5983 return Success(Elements, E); 5984 } 5985 5986 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 5987 VisitIgnoredValue(E->getSubExpr()); 5988 return ZeroInitialization(E); 5989 } 5990 5991 //===----------------------------------------------------------------------===// 5992 // Array Evaluation 5993 //===----------------------------------------------------------------------===// 5994 5995 namespace { 5996 class ArrayExprEvaluator 5997 : public ExprEvaluatorBase<ArrayExprEvaluator> { 5998 const LValue &This; 5999 APValue &Result; 6000 public: 6001 6002 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 6003 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 6004 6005 bool Success(const APValue &V, const Expr *E) { 6006 assert((V.isArray() || V.isLValue()) && 6007 "expected array or string literal"); 6008 Result = V; 6009 return true; 6010 } 6011 6012 bool ZeroInitialization(const Expr *E) { 6013 const ConstantArrayType *CAT = 6014 Info.Ctx.getAsConstantArrayType(E->getType()); 6015 if (!CAT) 6016 return Error(E); 6017 6018 Result = APValue(APValue::UninitArray(), 0, 6019 CAT->getSize().getZExtValue()); 6020 if (!Result.hasArrayFiller()) return true; 6021 6022 // Zero-initialize all elements. 6023 LValue Subobject = This; 6024 Subobject.addArray(Info, E, CAT); 6025 ImplicitValueInitExpr VIE(CAT->getElementType()); 6026 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 6027 } 6028 6029 bool VisitCallExpr(const CallExpr *E) { 6030 return handleCallExpr(E, Result, &This); 6031 } 6032 bool VisitInitListExpr(const InitListExpr *E); 6033 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 6034 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 6035 const LValue &Subobject, 6036 APValue *Value, QualType Type); 6037 }; 6038 } // end anonymous namespace 6039 6040 static bool EvaluateArray(const Expr *E, const LValue &This, 6041 APValue &Result, EvalInfo &Info) { 6042 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 6043 return ArrayExprEvaluator(Info, This, Result).Visit(E); 6044 } 6045 6046 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6047 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 6048 if (!CAT) 6049 return Error(E); 6050 6051 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 6052 // an appropriately-typed string literal enclosed in braces. 6053 if (E->isStringLiteralInit()) { 6054 LValue LV; 6055 if (!EvaluateLValue(E->getInit(0), LV, Info)) 6056 return false; 6057 APValue Val; 6058 LV.moveInto(Val); 6059 return Success(Val, E); 6060 } 6061 6062 bool Success = true; 6063 6064 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 6065 "zero-initialized array shouldn't have any initialized elts"); 6066 APValue Filler; 6067 if (Result.isArray() && Result.hasArrayFiller()) 6068 Filler = Result.getArrayFiller(); 6069 6070 unsigned NumEltsToInit = E->getNumInits(); 6071 unsigned NumElts = CAT->getSize().getZExtValue(); 6072 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 6073 6074 // If the initializer might depend on the array index, run it for each 6075 // array element. For now, just whitelist non-class value-initialization. 6076 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr)) 6077 NumEltsToInit = NumElts; 6078 6079 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 6080 6081 // If the array was previously zero-initialized, preserve the 6082 // zero-initialized values. 6083 if (!Filler.isUninit()) { 6084 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 6085 Result.getArrayInitializedElt(I) = Filler; 6086 if (Result.hasArrayFiller()) 6087 Result.getArrayFiller() = Filler; 6088 } 6089 6090 LValue Subobject = This; 6091 Subobject.addArray(Info, E, CAT); 6092 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 6093 const Expr *Init = 6094 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 6095 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 6096 Info, Subobject, Init) || 6097 !HandleLValueArrayAdjustment(Info, Init, Subobject, 6098 CAT->getElementType(), 1)) { 6099 if (!Info.noteFailure()) 6100 return false; 6101 Success = false; 6102 } 6103 } 6104 6105 if (!Result.hasArrayFiller()) 6106 return Success; 6107 6108 // If we get here, we have a trivial filler, which we can just evaluate 6109 // once and splat over the rest of the array elements. 6110 assert(FillerExpr && "no array filler for incomplete init list"); 6111 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 6112 FillerExpr) && Success; 6113 } 6114 6115 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 6116 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 6117 } 6118 6119 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 6120 const LValue &Subobject, 6121 APValue *Value, 6122 QualType Type) { 6123 bool HadZeroInit = !Value->isUninit(); 6124 6125 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 6126 unsigned N = CAT->getSize().getZExtValue(); 6127 6128 // Preserve the array filler if we had prior zero-initialization. 6129 APValue Filler = 6130 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 6131 : APValue(); 6132 6133 *Value = APValue(APValue::UninitArray(), N, N); 6134 6135 if (HadZeroInit) 6136 for (unsigned I = 0; I != N; ++I) 6137 Value->getArrayInitializedElt(I) = Filler; 6138 6139 // Initialize the elements. 6140 LValue ArrayElt = Subobject; 6141 ArrayElt.addArray(Info, E, CAT); 6142 for (unsigned I = 0; I != N; ++I) 6143 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 6144 CAT->getElementType()) || 6145 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 6146 CAT->getElementType(), 1)) 6147 return false; 6148 6149 return true; 6150 } 6151 6152 if (!Type->isRecordType()) 6153 return Error(E); 6154 6155 return RecordExprEvaluator(Info, Subobject, *Value) 6156 .VisitCXXConstructExpr(E, Type); 6157 } 6158 6159 //===----------------------------------------------------------------------===// 6160 // Integer Evaluation 6161 // 6162 // As a GNU extension, we support casting pointers to sufficiently-wide integer 6163 // types and back in constant folding. Integer values are thus represented 6164 // either as an integer-valued APValue, or as an lvalue-valued APValue. 6165 //===----------------------------------------------------------------------===// 6166 6167 namespace { 6168 class IntExprEvaluator 6169 : public ExprEvaluatorBase<IntExprEvaluator> { 6170 APValue &Result; 6171 public: 6172 IntExprEvaluator(EvalInfo &info, APValue &result) 6173 : ExprEvaluatorBaseTy(info), Result(result) {} 6174 6175 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 6176 assert(E->getType()->isIntegralOrEnumerationType() && 6177 "Invalid evaluation result."); 6178 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 6179 "Invalid evaluation result."); 6180 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 6181 "Invalid evaluation result."); 6182 Result = APValue(SI); 6183 return true; 6184 } 6185 bool Success(const llvm::APSInt &SI, const Expr *E) { 6186 return Success(SI, E, Result); 6187 } 6188 6189 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 6190 assert(E->getType()->isIntegralOrEnumerationType() && 6191 "Invalid evaluation result."); 6192 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 6193 "Invalid evaluation result."); 6194 Result = APValue(APSInt(I)); 6195 Result.getInt().setIsUnsigned( 6196 E->getType()->isUnsignedIntegerOrEnumerationType()); 6197 return true; 6198 } 6199 bool Success(const llvm::APInt &I, const Expr *E) { 6200 return Success(I, E, Result); 6201 } 6202 6203 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 6204 assert(E->getType()->isIntegralOrEnumerationType() && 6205 "Invalid evaluation result."); 6206 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 6207 return true; 6208 } 6209 bool Success(uint64_t Value, const Expr *E) { 6210 return Success(Value, E, Result); 6211 } 6212 6213 bool Success(CharUnits Size, const Expr *E) { 6214 return Success(Size.getQuantity(), E); 6215 } 6216 6217 bool Success(const APValue &V, const Expr *E) { 6218 if (V.isLValue() || V.isAddrLabelDiff()) { 6219 Result = V; 6220 return true; 6221 } 6222 return Success(V.getInt(), E); 6223 } 6224 6225 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 6226 6227 //===--------------------------------------------------------------------===// 6228 // Visitor Methods 6229 //===--------------------------------------------------------------------===// 6230 6231 bool VisitIntegerLiteral(const IntegerLiteral *E) { 6232 return Success(E->getValue(), E); 6233 } 6234 bool VisitCharacterLiteral(const CharacterLiteral *E) { 6235 return Success(E->getValue(), E); 6236 } 6237 6238 bool CheckReferencedDecl(const Expr *E, const Decl *D); 6239 bool VisitDeclRefExpr(const DeclRefExpr *E) { 6240 if (CheckReferencedDecl(E, E->getDecl())) 6241 return true; 6242 6243 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 6244 } 6245 bool VisitMemberExpr(const MemberExpr *E) { 6246 if (CheckReferencedDecl(E, E->getMemberDecl())) { 6247 VisitIgnoredBaseExpression(E->getBase()); 6248 return true; 6249 } 6250 6251 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 6252 } 6253 6254 bool VisitCallExpr(const CallExpr *E); 6255 bool VisitBinaryOperator(const BinaryOperator *E); 6256 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 6257 bool VisitUnaryOperator(const UnaryOperator *E); 6258 6259 bool VisitCastExpr(const CastExpr* E); 6260 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 6261 6262 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 6263 return Success(E->getValue(), E); 6264 } 6265 6266 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 6267 return Success(E->getValue(), E); 6268 } 6269 6270 // Note, GNU defines __null as an integer, not a pointer. 6271 bool VisitGNUNullExpr(const GNUNullExpr *E) { 6272 return ZeroInitialization(E); 6273 } 6274 6275 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 6276 return Success(E->getValue(), E); 6277 } 6278 6279 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 6280 return Success(E->getValue(), E); 6281 } 6282 6283 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 6284 return Success(E->getValue(), E); 6285 } 6286 6287 bool VisitUnaryReal(const UnaryOperator *E); 6288 bool VisitUnaryImag(const UnaryOperator *E); 6289 6290 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 6291 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 6292 6293 private: 6294 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type); 6295 // FIXME: Missing: array subscript of vector, member of vector 6296 }; 6297 } // end anonymous namespace 6298 6299 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 6300 /// produce either the integer value or a pointer. 6301 /// 6302 /// GCC has a heinous extension which folds casts between pointer types and 6303 /// pointer-sized integral types. We support this by allowing the evaluation of 6304 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 6305 /// Some simple arithmetic on such values is supported (they are treated much 6306 /// like char*). 6307 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 6308 EvalInfo &Info) { 6309 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 6310 return IntExprEvaluator(Info, Result).Visit(E); 6311 } 6312 6313 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 6314 APValue Val; 6315 if (!EvaluateIntegerOrLValue(E, Val, Info)) 6316 return false; 6317 if (!Val.isInt()) { 6318 // FIXME: It would be better to produce the diagnostic for casting 6319 // a pointer to an integer. 6320 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 6321 return false; 6322 } 6323 Result = Val.getInt(); 6324 return true; 6325 } 6326 6327 /// Check whether the given declaration can be directly converted to an integral 6328 /// rvalue. If not, no diagnostic is produced; there are other things we can 6329 /// try. 6330 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 6331 // Enums are integer constant exprs. 6332 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 6333 // Check for signedness/width mismatches between E type and ECD value. 6334 bool SameSign = (ECD->getInitVal().isSigned() 6335 == E->getType()->isSignedIntegerOrEnumerationType()); 6336 bool SameWidth = (ECD->getInitVal().getBitWidth() 6337 == Info.Ctx.getIntWidth(E->getType())); 6338 if (SameSign && SameWidth) 6339 return Success(ECD->getInitVal(), E); 6340 else { 6341 // Get rid of mismatch (otherwise Success assertions will fail) 6342 // by computing a new value matching the type of E. 6343 llvm::APSInt Val = ECD->getInitVal(); 6344 if (!SameSign) 6345 Val.setIsSigned(!ECD->getInitVal().isSigned()); 6346 if (!SameWidth) 6347 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 6348 return Success(Val, E); 6349 } 6350 } 6351 return false; 6352 } 6353 6354 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 6355 /// as GCC. 6356 static int EvaluateBuiltinClassifyType(const CallExpr *E, 6357 const LangOptions &LangOpts) { 6358 // The following enum mimics the values returned by GCC. 6359 // FIXME: Does GCC differ between lvalue and rvalue references here? 6360 enum gcc_type_class { 6361 no_type_class = -1, 6362 void_type_class, integer_type_class, char_type_class, 6363 enumeral_type_class, boolean_type_class, 6364 pointer_type_class, reference_type_class, offset_type_class, 6365 real_type_class, complex_type_class, 6366 function_type_class, method_type_class, 6367 record_type_class, union_type_class, 6368 array_type_class, string_type_class, 6369 lang_type_class 6370 }; 6371 6372 // If no argument was supplied, default to "no_type_class". This isn't 6373 // ideal, however it is what gcc does. 6374 if (E->getNumArgs() == 0) 6375 return no_type_class; 6376 6377 QualType CanTy = E->getArg(0)->getType().getCanonicalType(); 6378 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 6379 6380 switch (CanTy->getTypeClass()) { 6381 #define TYPE(ID, BASE) 6382 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 6383 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 6384 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 6385 #include "clang/AST/TypeNodes.def" 6386 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 6387 6388 case Type::Builtin: 6389 switch (BT->getKind()) { 6390 #define BUILTIN_TYPE(ID, SINGLETON_ID) 6391 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class; 6392 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class; 6393 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break; 6394 #include "clang/AST/BuiltinTypes.def" 6395 case BuiltinType::Void: 6396 return void_type_class; 6397 6398 case BuiltinType::Bool: 6399 return boolean_type_class; 6400 6401 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class 6402 case BuiltinType::UChar: 6403 case BuiltinType::UShort: 6404 case BuiltinType::UInt: 6405 case BuiltinType::ULong: 6406 case BuiltinType::ULongLong: 6407 case BuiltinType::UInt128: 6408 return integer_type_class; 6409 6410 case BuiltinType::NullPtr: 6411 return pointer_type_class; 6412 6413 case BuiltinType::WChar_U: 6414 case BuiltinType::Char16: 6415 case BuiltinType::Char32: 6416 case BuiltinType::ObjCId: 6417 case BuiltinType::ObjCClass: 6418 case BuiltinType::ObjCSel: 6419 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6420 case BuiltinType::Id: 6421 #include "clang/Basic/OpenCLImageTypes.def" 6422 case BuiltinType::OCLSampler: 6423 case BuiltinType::OCLEvent: 6424 case BuiltinType::OCLClkEvent: 6425 case BuiltinType::OCLQueue: 6426 case BuiltinType::OCLNDRange: 6427 case BuiltinType::OCLReserveID: 6428 case BuiltinType::Dependent: 6429 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 6430 }; 6431 6432 case Type::Enum: 6433 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class; 6434 break; 6435 6436 case Type::Pointer: 6437 return pointer_type_class; 6438 break; 6439 6440 case Type::MemberPointer: 6441 if (CanTy->isMemberDataPointerType()) 6442 return offset_type_class; 6443 else { 6444 // We expect member pointers to be either data or function pointers, 6445 // nothing else. 6446 assert(CanTy->isMemberFunctionPointerType()); 6447 return method_type_class; 6448 } 6449 6450 case Type::Complex: 6451 return complex_type_class; 6452 6453 case Type::FunctionNoProto: 6454 case Type::FunctionProto: 6455 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class; 6456 6457 case Type::Record: 6458 if (const RecordType *RT = CanTy->getAs<RecordType>()) { 6459 switch (RT->getDecl()->getTagKind()) { 6460 case TagTypeKind::TTK_Struct: 6461 case TagTypeKind::TTK_Class: 6462 case TagTypeKind::TTK_Interface: 6463 return record_type_class; 6464 6465 case TagTypeKind::TTK_Enum: 6466 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class; 6467 6468 case TagTypeKind::TTK_Union: 6469 return union_type_class; 6470 } 6471 } 6472 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 6473 6474 case Type::ConstantArray: 6475 case Type::VariableArray: 6476 case Type::IncompleteArray: 6477 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class; 6478 6479 case Type::BlockPointer: 6480 case Type::LValueReference: 6481 case Type::RValueReference: 6482 case Type::Vector: 6483 case Type::ExtVector: 6484 case Type::Auto: 6485 case Type::ObjCObject: 6486 case Type::ObjCInterface: 6487 case Type::ObjCObjectPointer: 6488 case Type::Pipe: 6489 case Type::Atomic: 6490 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 6491 } 6492 6493 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 6494 } 6495 6496 /// EvaluateBuiltinConstantPForLValue - Determine the result of 6497 /// __builtin_constant_p when applied to the given lvalue. 6498 /// 6499 /// An lvalue is only "constant" if it is a pointer or reference to the first 6500 /// character of a string literal. 6501 template<typename LValue> 6502 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) { 6503 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>(); 6504 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero(); 6505 } 6506 6507 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 6508 /// GCC as we can manage. 6509 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) { 6510 QualType ArgType = Arg->getType(); 6511 6512 // __builtin_constant_p always has one operand. The rules which gcc follows 6513 // are not precisely documented, but are as follows: 6514 // 6515 // - If the operand is of integral, floating, complex or enumeration type, 6516 // and can be folded to a known value of that type, it returns 1. 6517 // - If the operand and can be folded to a pointer to the first character 6518 // of a string literal (or such a pointer cast to an integral type), it 6519 // returns 1. 6520 // 6521 // Otherwise, it returns 0. 6522 // 6523 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 6524 // its support for this does not currently work. 6525 if (ArgType->isIntegralOrEnumerationType()) { 6526 Expr::EvalResult Result; 6527 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects) 6528 return false; 6529 6530 APValue &V = Result.Val; 6531 if (V.getKind() == APValue::Int) 6532 return true; 6533 if (V.getKind() == APValue::LValue) 6534 return EvaluateBuiltinConstantPForLValue(V); 6535 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) { 6536 return Arg->isEvaluatable(Ctx); 6537 } else if (ArgType->isPointerType() || Arg->isGLValue()) { 6538 LValue LV; 6539 Expr::EvalStatus Status; 6540 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 6541 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info) 6542 : EvaluatePointer(Arg, LV, Info)) && 6543 !Status.HasSideEffects) 6544 return EvaluateBuiltinConstantPForLValue(LV); 6545 } 6546 6547 // Anything else isn't considered to be sufficiently constant. 6548 return false; 6549 } 6550 6551 /// Retrieves the "underlying object type" of the given expression, 6552 /// as used by __builtin_object_size. 6553 static QualType getObjectType(APValue::LValueBase B) { 6554 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 6555 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 6556 return VD->getType(); 6557 } else if (const Expr *E = B.get<const Expr*>()) { 6558 if (isa<CompoundLiteralExpr>(E)) 6559 return E->getType(); 6560 } 6561 6562 return QualType(); 6563 } 6564 6565 /// A more selective version of E->IgnoreParenCasts for 6566 /// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 6567 /// to change the type of E. 6568 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 6569 /// 6570 /// Always returns an RValue with a pointer representation. 6571 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 6572 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 6573 6574 auto *NoParens = E->IgnoreParens(); 6575 auto *Cast = dyn_cast<CastExpr>(NoParens); 6576 if (Cast == nullptr) 6577 return NoParens; 6578 6579 // We only conservatively allow a few kinds of casts, because this code is 6580 // inherently a simple solution that seeks to support the common case. 6581 auto CastKind = Cast->getCastKind(); 6582 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 6583 CastKind != CK_AddressSpaceConversion) 6584 return NoParens; 6585 6586 auto *SubExpr = Cast->getSubExpr(); 6587 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 6588 return NoParens; 6589 return ignorePointerCastsAndParens(SubExpr); 6590 } 6591 6592 /// Checks to see if the given LValue's Designator is at the end of the LValue's 6593 /// record layout. e.g. 6594 /// struct { struct { int a, b; } fst, snd; } obj; 6595 /// obj.fst // no 6596 /// obj.snd // yes 6597 /// obj.fst.a // no 6598 /// obj.fst.b // no 6599 /// obj.snd.a // no 6600 /// obj.snd.b // yes 6601 /// 6602 /// Please note: this function is specialized for how __builtin_object_size 6603 /// views "objects". 6604 /// 6605 /// If this encounters an invalid RecordDecl, it will always return true. 6606 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 6607 assert(!LVal.Designator.Invalid); 6608 6609 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 6610 const RecordDecl *Parent = FD->getParent(); 6611 Invalid = Parent->isInvalidDecl(); 6612 if (Invalid || Parent->isUnion()) 6613 return true; 6614 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 6615 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 6616 }; 6617 6618 auto &Base = LVal.getLValueBase(); 6619 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 6620 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 6621 bool Invalid; 6622 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 6623 return Invalid; 6624 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 6625 for (auto *FD : IFD->chain()) { 6626 bool Invalid; 6627 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 6628 return Invalid; 6629 } 6630 } 6631 } 6632 6633 QualType BaseType = getType(Base); 6634 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) { 6635 if (BaseType->isArrayType()) { 6636 // Because __builtin_object_size treats arrays as objects, we can ignore 6637 // the index iff this is the last array in the Designator. 6638 if (I + 1 == E) 6639 return true; 6640 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 6641 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex; 6642 if (Index + 1 != CAT->getSize()) 6643 return false; 6644 BaseType = CAT->getElementType(); 6645 } else if (BaseType->isAnyComplexType()) { 6646 auto *CT = BaseType->castAs<ComplexType>(); 6647 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex; 6648 if (Index != 1) 6649 return false; 6650 BaseType = CT->getElementType(); 6651 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) { 6652 bool Invalid; 6653 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 6654 return Invalid; 6655 BaseType = FD->getType(); 6656 } else { 6657 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr && 6658 "Expecting cast to a base class"); 6659 return false; 6660 } 6661 } 6662 return true; 6663 } 6664 6665 /// Tests to see if the LValue has a designator (that isn't necessarily valid). 6666 static bool refersToCompleteObject(const LValue &LVal) { 6667 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty()) 6668 return false; 6669 6670 if (!LVal.InvalidBase) 6671 return true; 6672 6673 auto *E = LVal.Base.dyn_cast<const Expr *>(); 6674 (void)E; 6675 assert(E != nullptr && isa<MemberExpr>(E)); 6676 return false; 6677 } 6678 6679 /// Tries to evaluate the __builtin_object_size for @p E. If successful, returns 6680 /// true and stores the result in @p Size. 6681 /// 6682 /// If @p WasError is non-null, this will report whether the failure to evaluate 6683 /// is to be treated as an Error in IntExprEvaluator. 6684 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 6685 EvalInfo &Info, uint64_t &Size, 6686 bool *WasError = nullptr) { 6687 if (WasError != nullptr) 6688 *WasError = false; 6689 6690 auto Error = [&](const Expr *E) { 6691 if (WasError != nullptr) 6692 *WasError = true; 6693 return false; 6694 }; 6695 6696 auto Success = [&](uint64_t S, const Expr *E) { 6697 Size = S; 6698 return true; 6699 }; 6700 6701 // Determine the denoted object. 6702 LValue Base; 6703 { 6704 // The operand of __builtin_object_size is never evaluated for side-effects. 6705 // If there are any, but we can determine the pointed-to object anyway, then 6706 // ignore the side-effects. 6707 SpeculativeEvaluationRAII SpeculativeEval(Info); 6708 FoldOffsetRAII Fold(Info, Type & 1); 6709 6710 if (E->isGLValue()) { 6711 // It's possible for us to be given GLValues if we're called via 6712 // Expr::tryEvaluateObjectSize. 6713 APValue RVal; 6714 if (!EvaluateAsRValue(Info, E, RVal)) 6715 return false; 6716 Base.setFrom(Info.Ctx, RVal); 6717 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info)) 6718 return false; 6719 } 6720 6721 CharUnits BaseOffset = Base.getLValueOffset(); 6722 // If we point to before the start of the object, there are no accessible 6723 // bytes. 6724 if (BaseOffset.isNegative()) 6725 return Success(0, E); 6726 6727 // In the case where we're not dealing with a subobject, we discard the 6728 // subobject bit. 6729 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base); 6730 6731 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes 6732 // exist. If we can't verify the base, then we can't do that. 6733 // 6734 // As a special case, we produce a valid object size for an unknown object 6735 // with a known designator if Type & 1 is 1. For instance: 6736 // 6737 // extern struct X { char buff[32]; int a, b, c; } *p; 6738 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28 6739 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40 6740 // 6741 // This matches GCC's behavior. 6742 if (Base.InvalidBase && !SubobjectOnly) 6743 return Error(E); 6744 6745 // If we're not examining only the subobject, then we reset to a complete 6746 // object designator 6747 // 6748 // If Type is 1 and we've lost track of the subobject, just find the complete 6749 // object instead. (If Type is 3, that's not correct behavior and we should 6750 // return 0 instead.) 6751 LValue End = Base; 6752 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) { 6753 QualType T = getObjectType(End.getLValueBase()); 6754 if (T.isNull()) 6755 End.Designator.setInvalid(); 6756 else { 6757 End.Designator = SubobjectDesignator(T); 6758 End.Offset = CharUnits::Zero(); 6759 } 6760 } 6761 6762 // If it is not possible to determine which objects ptr points to at compile 6763 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1 6764 // and (size_t) 0 for type 2 or 3. 6765 if (End.Designator.Invalid) 6766 return false; 6767 6768 // According to the GCC documentation, we want the size of the subobject 6769 // denoted by the pointer. But that's not quite right -- what we actually 6770 // want is the size of the immediately-enclosing array, if there is one. 6771 int64_t AmountToAdd = 1; 6772 if (End.Designator.MostDerivedIsArrayElement && 6773 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) { 6774 // We got a pointer to an array. Step to its end. 6775 AmountToAdd = End.Designator.MostDerivedArraySize - 6776 End.Designator.Entries.back().ArrayIndex; 6777 } else if (End.Designator.isOnePastTheEnd()) { 6778 // We're already pointing at the end of the object. 6779 AmountToAdd = 0; 6780 } 6781 6782 QualType PointeeType = End.Designator.MostDerivedType; 6783 assert(!PointeeType.isNull()); 6784 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType()) 6785 return Error(E); 6786 6787 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType, 6788 AmountToAdd)) 6789 return false; 6790 6791 auto EndOffset = End.getLValueOffset(); 6792 6793 // The following is a moderately common idiom in C: 6794 // 6795 // struct Foo { int a; char c[1]; }; 6796 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 6797 // strcpy(&F->c[0], Bar); 6798 // 6799 // So, if we see that we're examining a 1-length (or 0-length) array at the 6800 // end of a struct with an unknown base, we give up instead of breaking code 6801 // that behaves this way. Note that we only do this when Type=1, because 6802 // Type=3 is a lower bound, so answering conservatively is fine. 6803 if (End.InvalidBase && SubobjectOnly && Type == 1 && 6804 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength && 6805 End.Designator.MostDerivedIsArrayElement && 6806 End.Designator.MostDerivedArraySize < 2 && 6807 isDesignatorAtObjectEnd(Info.Ctx, End)) 6808 return false; 6809 6810 if (BaseOffset > EndOffset) 6811 return Success(0, E); 6812 6813 return Success((EndOffset - BaseOffset).getQuantity(), E); 6814 } 6815 6816 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E, 6817 unsigned Type) { 6818 uint64_t Size; 6819 bool WasError; 6820 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError)) 6821 return Success(Size, E); 6822 if (WasError) 6823 return Error(E); 6824 return false; 6825 } 6826 6827 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 6828 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 6829 default: 6830 return ExprEvaluatorBaseTy::VisitCallExpr(E); 6831 6832 case Builtin::BI__builtin_object_size: { 6833 // The type was checked when we built the expression. 6834 unsigned Type = 6835 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 6836 assert(Type <= 3 && "unexpected type"); 6837 6838 if (TryEvaluateBuiltinObjectSize(E, Type)) 6839 return true; 6840 6841 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 6842 return Success((Type & 2) ? 0 : -1, E); 6843 6844 // Expression had no side effects, but we couldn't statically determine the 6845 // size of the referenced object. 6846 switch (Info.EvalMode) { 6847 case EvalInfo::EM_ConstantExpression: 6848 case EvalInfo::EM_PotentialConstantExpression: 6849 case EvalInfo::EM_ConstantFold: 6850 case EvalInfo::EM_EvaluateForOverflow: 6851 case EvalInfo::EM_IgnoreSideEffects: 6852 case EvalInfo::EM_DesignatorFold: 6853 // Leave it to IR generation. 6854 return Error(E); 6855 case EvalInfo::EM_ConstantExpressionUnevaluated: 6856 case EvalInfo::EM_PotentialConstantExpressionUnevaluated: 6857 // Reduce it to a constant now. 6858 return Success((Type & 2) ? 0 : -1, E); 6859 } 6860 } 6861 6862 case Builtin::BI__builtin_bswap16: 6863 case Builtin::BI__builtin_bswap32: 6864 case Builtin::BI__builtin_bswap64: { 6865 APSInt Val; 6866 if (!EvaluateInteger(E->getArg(0), Val, Info)) 6867 return false; 6868 6869 return Success(Val.byteSwap(), E); 6870 } 6871 6872 case Builtin::BI__builtin_classify_type: 6873 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 6874 6875 // FIXME: BI__builtin_clrsb 6876 // FIXME: BI__builtin_clrsbl 6877 // FIXME: BI__builtin_clrsbll 6878 6879 case Builtin::BI__builtin_clz: 6880 case Builtin::BI__builtin_clzl: 6881 case Builtin::BI__builtin_clzll: 6882 case Builtin::BI__builtin_clzs: { 6883 APSInt Val; 6884 if (!EvaluateInteger(E->getArg(0), Val, Info)) 6885 return false; 6886 if (!Val) 6887 return Error(E); 6888 6889 return Success(Val.countLeadingZeros(), E); 6890 } 6891 6892 case Builtin::BI__builtin_constant_p: 6893 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E); 6894 6895 case Builtin::BI__builtin_ctz: 6896 case Builtin::BI__builtin_ctzl: 6897 case Builtin::BI__builtin_ctzll: 6898 case Builtin::BI__builtin_ctzs: { 6899 APSInt Val; 6900 if (!EvaluateInteger(E->getArg(0), Val, Info)) 6901 return false; 6902 if (!Val) 6903 return Error(E); 6904 6905 return Success(Val.countTrailingZeros(), E); 6906 } 6907 6908 case Builtin::BI__builtin_eh_return_data_regno: { 6909 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 6910 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 6911 return Success(Operand, E); 6912 } 6913 6914 case Builtin::BI__builtin_expect: 6915 return Visit(E->getArg(0)); 6916 6917 case Builtin::BI__builtin_ffs: 6918 case Builtin::BI__builtin_ffsl: 6919 case Builtin::BI__builtin_ffsll: { 6920 APSInt Val; 6921 if (!EvaluateInteger(E->getArg(0), Val, Info)) 6922 return false; 6923 6924 unsigned N = Val.countTrailingZeros(); 6925 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 6926 } 6927 6928 case Builtin::BI__builtin_fpclassify: { 6929 APFloat Val(0.0); 6930 if (!EvaluateFloat(E->getArg(5), Val, Info)) 6931 return false; 6932 unsigned Arg; 6933 switch (Val.getCategory()) { 6934 case APFloat::fcNaN: Arg = 0; break; 6935 case APFloat::fcInfinity: Arg = 1; break; 6936 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 6937 case APFloat::fcZero: Arg = 4; break; 6938 } 6939 return Visit(E->getArg(Arg)); 6940 } 6941 6942 case Builtin::BI__builtin_isinf_sign: { 6943 APFloat Val(0.0); 6944 return EvaluateFloat(E->getArg(0), Val, Info) && 6945 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 6946 } 6947 6948 case Builtin::BI__builtin_isinf: { 6949 APFloat Val(0.0); 6950 return EvaluateFloat(E->getArg(0), Val, Info) && 6951 Success(Val.isInfinity() ? 1 : 0, E); 6952 } 6953 6954 case Builtin::BI__builtin_isfinite: { 6955 APFloat Val(0.0); 6956 return EvaluateFloat(E->getArg(0), Val, Info) && 6957 Success(Val.isFinite() ? 1 : 0, E); 6958 } 6959 6960 case Builtin::BI__builtin_isnan: { 6961 APFloat Val(0.0); 6962 return EvaluateFloat(E->getArg(0), Val, Info) && 6963 Success(Val.isNaN() ? 1 : 0, E); 6964 } 6965 6966 case Builtin::BI__builtin_isnormal: { 6967 APFloat Val(0.0); 6968 return EvaluateFloat(E->getArg(0), Val, Info) && 6969 Success(Val.isNormal() ? 1 : 0, E); 6970 } 6971 6972 case Builtin::BI__builtin_parity: 6973 case Builtin::BI__builtin_parityl: 6974 case Builtin::BI__builtin_parityll: { 6975 APSInt Val; 6976 if (!EvaluateInteger(E->getArg(0), Val, Info)) 6977 return false; 6978 6979 return Success(Val.countPopulation() % 2, E); 6980 } 6981 6982 case Builtin::BI__builtin_popcount: 6983 case Builtin::BI__builtin_popcountl: 6984 case Builtin::BI__builtin_popcountll: { 6985 APSInt Val; 6986 if (!EvaluateInteger(E->getArg(0), Val, Info)) 6987 return false; 6988 6989 return Success(Val.countPopulation(), E); 6990 } 6991 6992 case Builtin::BIstrlen: 6993 // A call to strlen is not a constant expression. 6994 if (Info.getLangOpts().CPlusPlus11) 6995 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6996 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'"; 6997 else 6998 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6999 // Fall through. 7000 case Builtin::BI__builtin_strlen: { 7001 // As an extension, we support __builtin_strlen() as a constant expression, 7002 // and support folding strlen() to a constant. 7003 LValue String; 7004 if (!EvaluatePointer(E->getArg(0), String, Info)) 7005 return false; 7006 7007 // Fast path: if it's a string literal, search the string value. 7008 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 7009 String.getLValueBase().dyn_cast<const Expr *>())) { 7010 // The string literal may have embedded null characters. Find the first 7011 // one and truncate there. 7012 StringRef Str = S->getBytes(); 7013 int64_t Off = String.Offset.getQuantity(); 7014 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 7015 S->getCharByteWidth() == 1) { 7016 Str = Str.substr(Off); 7017 7018 StringRef::size_type Pos = Str.find(0); 7019 if (Pos != StringRef::npos) 7020 Str = Str.substr(0, Pos); 7021 7022 return Success(Str.size(), E); 7023 } 7024 7025 // Fall through to slow path to issue appropriate diagnostic. 7026 } 7027 7028 // Slow path: scan the bytes of the string looking for the terminating 0. 7029 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 7030 for (uint64_t Strlen = 0; /**/; ++Strlen) { 7031 APValue Char; 7032 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 7033 !Char.isInt()) 7034 return false; 7035 if (!Char.getInt()) 7036 return Success(Strlen, E); 7037 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 7038 return false; 7039 } 7040 } 7041 7042 case Builtin::BI__atomic_always_lock_free: 7043 case Builtin::BI__atomic_is_lock_free: 7044 case Builtin::BI__c11_atomic_is_lock_free: { 7045 APSInt SizeVal; 7046 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 7047 return false; 7048 7049 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 7050 // of two less than the maximum inline atomic width, we know it is 7051 // lock-free. If the size isn't a power of two, or greater than the 7052 // maximum alignment where we promote atomics, we know it is not lock-free 7053 // (at least not in the sense of atomic_is_lock_free). Otherwise, 7054 // the answer can only be determined at runtime; for example, 16-byte 7055 // atomics have lock-free implementations on some, but not all, 7056 // x86-64 processors. 7057 7058 // Check power-of-two. 7059 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 7060 if (Size.isPowerOfTwo()) { 7061 // Check against inlining width. 7062 unsigned InlineWidthBits = 7063 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 7064 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 7065 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 7066 Size == CharUnits::One() || 7067 E->getArg(1)->isNullPointerConstant(Info.Ctx, 7068 Expr::NPC_NeverValueDependent)) 7069 // OK, we will inline appropriately-aligned operations of this size, 7070 // and _Atomic(T) is appropriately-aligned. 7071 return Success(1, E); 7072 7073 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 7074 castAs<PointerType>()->getPointeeType(); 7075 if (!PointeeType->isIncompleteType() && 7076 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 7077 // OK, we will inline operations on this object. 7078 return Success(1, E); 7079 } 7080 } 7081 } 7082 7083 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 7084 Success(0, E) : Error(E); 7085 } 7086 } 7087 } 7088 7089 static bool HasSameBase(const LValue &A, const LValue &B) { 7090 if (!A.getLValueBase()) 7091 return !B.getLValueBase(); 7092 if (!B.getLValueBase()) 7093 return false; 7094 7095 if (A.getLValueBase().getOpaqueValue() != 7096 B.getLValueBase().getOpaqueValue()) { 7097 const Decl *ADecl = GetLValueBaseDecl(A); 7098 if (!ADecl) 7099 return false; 7100 const Decl *BDecl = GetLValueBaseDecl(B); 7101 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 7102 return false; 7103 } 7104 7105 return IsGlobalLValue(A.getLValueBase()) || 7106 A.getLValueCallIndex() == B.getLValueCallIndex(); 7107 } 7108 7109 /// \brief Determine whether this is a pointer past the end of the complete 7110 /// object referred to by the lvalue. 7111 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 7112 const LValue &LV) { 7113 // A null pointer can be viewed as being "past the end" but we don't 7114 // choose to look at it that way here. 7115 if (!LV.getLValueBase()) 7116 return false; 7117 7118 // If the designator is valid and refers to a subobject, we're not pointing 7119 // past the end. 7120 if (!LV.getLValueDesignator().Invalid && 7121 !LV.getLValueDesignator().isOnePastTheEnd()) 7122 return false; 7123 7124 // A pointer to an incomplete type might be past-the-end if the type's size is 7125 // zero. We cannot tell because the type is incomplete. 7126 QualType Ty = getType(LV.getLValueBase()); 7127 if (Ty->isIncompleteType()) 7128 return true; 7129 7130 // We're a past-the-end pointer if we point to the byte after the object, 7131 // no matter what our type or path is. 7132 auto Size = Ctx.getTypeSizeInChars(Ty); 7133 return LV.getLValueOffset() == Size; 7134 } 7135 7136 namespace { 7137 7138 /// \brief Data recursive integer evaluator of certain binary operators. 7139 /// 7140 /// We use a data recursive algorithm for binary operators so that we are able 7141 /// to handle extreme cases of chained binary operators without causing stack 7142 /// overflow. 7143 class DataRecursiveIntBinOpEvaluator { 7144 struct EvalResult { 7145 APValue Val; 7146 bool Failed; 7147 7148 EvalResult() : Failed(false) { } 7149 7150 void swap(EvalResult &RHS) { 7151 Val.swap(RHS.Val); 7152 Failed = RHS.Failed; 7153 RHS.Failed = false; 7154 } 7155 }; 7156 7157 struct Job { 7158 const Expr *E; 7159 EvalResult LHSResult; // meaningful only for binary operator expression. 7160 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 7161 7162 Job() = default; 7163 Job(Job &&J) 7164 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind), 7165 SpecEvalRAII(std::move(J.SpecEvalRAII)) {} 7166 7167 void startSpeculativeEval(EvalInfo &Info) { 7168 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 7169 } 7170 7171 private: 7172 SpeculativeEvaluationRAII SpecEvalRAII; 7173 }; 7174 7175 SmallVector<Job, 16> Queue; 7176 7177 IntExprEvaluator &IntEval; 7178 EvalInfo &Info; 7179 APValue &FinalResult; 7180 7181 public: 7182 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 7183 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 7184 7185 /// \brief True if \param E is a binary operator that we are going to handle 7186 /// data recursively. 7187 /// We handle binary operators that are comma, logical, or that have operands 7188 /// with integral or enumeration type. 7189 static bool shouldEnqueue(const BinaryOperator *E) { 7190 return E->getOpcode() == BO_Comma || 7191 E->isLogicalOp() || 7192 (E->isRValue() && 7193 E->getType()->isIntegralOrEnumerationType() && 7194 E->getLHS()->getType()->isIntegralOrEnumerationType() && 7195 E->getRHS()->getType()->isIntegralOrEnumerationType()); 7196 } 7197 7198 bool Traverse(const BinaryOperator *E) { 7199 enqueue(E); 7200 EvalResult PrevResult; 7201 while (!Queue.empty()) 7202 process(PrevResult); 7203 7204 if (PrevResult.Failed) return false; 7205 7206 FinalResult.swap(PrevResult.Val); 7207 return true; 7208 } 7209 7210 private: 7211 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 7212 return IntEval.Success(Value, E, Result); 7213 } 7214 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 7215 return IntEval.Success(Value, E, Result); 7216 } 7217 bool Error(const Expr *E) { 7218 return IntEval.Error(E); 7219 } 7220 bool Error(const Expr *E, diag::kind D) { 7221 return IntEval.Error(E, D); 7222 } 7223 7224 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 7225 return Info.CCEDiag(E, D); 7226 } 7227 7228 // \brief Returns true if visiting the RHS is necessary, false otherwise. 7229 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 7230 bool &SuppressRHSDiags); 7231 7232 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 7233 const BinaryOperator *E, APValue &Result); 7234 7235 void EvaluateExpr(const Expr *E, EvalResult &Result) { 7236 Result.Failed = !Evaluate(Result.Val, Info, E); 7237 if (Result.Failed) 7238 Result.Val = APValue(); 7239 } 7240 7241 void process(EvalResult &Result); 7242 7243 void enqueue(const Expr *E) { 7244 E = E->IgnoreParens(); 7245 Queue.resize(Queue.size()+1); 7246 Queue.back().E = E; 7247 Queue.back().Kind = Job::AnyExprKind; 7248 } 7249 }; 7250 7251 } 7252 7253 bool DataRecursiveIntBinOpEvaluator:: 7254 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 7255 bool &SuppressRHSDiags) { 7256 if (E->getOpcode() == BO_Comma) { 7257 // Ignore LHS but note if we could not evaluate it. 7258 if (LHSResult.Failed) 7259 return Info.noteSideEffect(); 7260 return true; 7261 } 7262 7263 if (E->isLogicalOp()) { 7264 bool LHSAsBool; 7265 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 7266 // We were able to evaluate the LHS, see if we can get away with not 7267 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 7268 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 7269 Success(LHSAsBool, E, LHSResult.Val); 7270 return false; // Ignore RHS 7271 } 7272 } else { 7273 LHSResult.Failed = true; 7274 7275 // Since we weren't able to evaluate the left hand side, it 7276 // might have had side effects. 7277 if (!Info.noteSideEffect()) 7278 return false; 7279 7280 // We can't evaluate the LHS; however, sometimes the result 7281 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 7282 // Don't ignore RHS and suppress diagnostics from this arm. 7283 SuppressRHSDiags = true; 7284 } 7285 7286 return true; 7287 } 7288 7289 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 7290 E->getRHS()->getType()->isIntegralOrEnumerationType()); 7291 7292 if (LHSResult.Failed && !Info.noteFailure()) 7293 return false; // Ignore RHS; 7294 7295 return true; 7296 } 7297 7298 bool DataRecursiveIntBinOpEvaluator:: 7299 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 7300 const BinaryOperator *E, APValue &Result) { 7301 if (E->getOpcode() == BO_Comma) { 7302 if (RHSResult.Failed) 7303 return false; 7304 Result = RHSResult.Val; 7305 return true; 7306 } 7307 7308 if (E->isLogicalOp()) { 7309 bool lhsResult, rhsResult; 7310 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 7311 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 7312 7313 if (LHSIsOK) { 7314 if (RHSIsOK) { 7315 if (E->getOpcode() == BO_LOr) 7316 return Success(lhsResult || rhsResult, E, Result); 7317 else 7318 return Success(lhsResult && rhsResult, E, Result); 7319 } 7320 } else { 7321 if (RHSIsOK) { 7322 // We can't evaluate the LHS; however, sometimes the result 7323 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 7324 if (rhsResult == (E->getOpcode() == BO_LOr)) 7325 return Success(rhsResult, E, Result); 7326 } 7327 } 7328 7329 return false; 7330 } 7331 7332 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 7333 E->getRHS()->getType()->isIntegralOrEnumerationType()); 7334 7335 if (LHSResult.Failed || RHSResult.Failed) 7336 return false; 7337 7338 const APValue &LHSVal = LHSResult.Val; 7339 const APValue &RHSVal = RHSResult.Val; 7340 7341 // Handle cases like (unsigned long)&a + 4. 7342 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 7343 Result = LHSVal; 7344 CharUnits AdditionalOffset = 7345 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue()); 7346 if (E->getOpcode() == BO_Add) 7347 Result.getLValueOffset() += AdditionalOffset; 7348 else 7349 Result.getLValueOffset() -= AdditionalOffset; 7350 return true; 7351 } 7352 7353 // Handle cases like 4 + (unsigned long)&a 7354 if (E->getOpcode() == BO_Add && 7355 RHSVal.isLValue() && LHSVal.isInt()) { 7356 Result = RHSVal; 7357 Result.getLValueOffset() += 7358 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue()); 7359 return true; 7360 } 7361 7362 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 7363 // Handle (intptr_t)&&A - (intptr_t)&&B. 7364 if (!LHSVal.getLValueOffset().isZero() || 7365 !RHSVal.getLValueOffset().isZero()) 7366 return false; 7367 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 7368 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 7369 if (!LHSExpr || !RHSExpr) 7370 return false; 7371 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 7372 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 7373 if (!LHSAddrExpr || !RHSAddrExpr) 7374 return false; 7375 // Make sure both labels come from the same function. 7376 if (LHSAddrExpr->getLabel()->getDeclContext() != 7377 RHSAddrExpr->getLabel()->getDeclContext()) 7378 return false; 7379 Result = APValue(LHSAddrExpr, RHSAddrExpr); 7380 return true; 7381 } 7382 7383 // All the remaining cases expect both operands to be an integer 7384 if (!LHSVal.isInt() || !RHSVal.isInt()) 7385 return Error(E); 7386 7387 // Set up the width and signedness manually, in case it can't be deduced 7388 // from the operation we're performing. 7389 // FIXME: Don't do this in the cases where we can deduce it. 7390 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 7391 E->getType()->isUnsignedIntegerOrEnumerationType()); 7392 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 7393 RHSVal.getInt(), Value)) 7394 return false; 7395 return Success(Value, E, Result); 7396 } 7397 7398 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 7399 Job &job = Queue.back(); 7400 7401 switch (job.Kind) { 7402 case Job::AnyExprKind: { 7403 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 7404 if (shouldEnqueue(Bop)) { 7405 job.Kind = Job::BinOpKind; 7406 enqueue(Bop->getLHS()); 7407 return; 7408 } 7409 } 7410 7411 EvaluateExpr(job.E, Result); 7412 Queue.pop_back(); 7413 return; 7414 } 7415 7416 case Job::BinOpKind: { 7417 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 7418 bool SuppressRHSDiags = false; 7419 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 7420 Queue.pop_back(); 7421 return; 7422 } 7423 if (SuppressRHSDiags) 7424 job.startSpeculativeEval(Info); 7425 job.LHSResult.swap(Result); 7426 job.Kind = Job::BinOpVisitedLHSKind; 7427 enqueue(Bop->getRHS()); 7428 return; 7429 } 7430 7431 case Job::BinOpVisitedLHSKind: { 7432 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 7433 EvalResult RHS; 7434 RHS.swap(Result); 7435 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 7436 Queue.pop_back(); 7437 return; 7438 } 7439 } 7440 7441 llvm_unreachable("Invalid Job::Kind!"); 7442 } 7443 7444 namespace { 7445 /// Used when we determine that we should fail, but can keep evaluating prior to 7446 /// noting that we had a failure. 7447 class DelayedNoteFailureRAII { 7448 EvalInfo &Info; 7449 bool NoteFailure; 7450 7451 public: 7452 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 7453 : Info(Info), NoteFailure(NoteFailure) {} 7454 ~DelayedNoteFailureRAII() { 7455 if (NoteFailure) { 7456 bool ContinueAfterFailure = Info.noteFailure(); 7457 (void)ContinueAfterFailure; 7458 assert(ContinueAfterFailure && 7459 "Shouldn't have kept evaluating on failure."); 7460 } 7461 } 7462 }; 7463 } 7464 7465 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 7466 // We don't call noteFailure immediately because the assignment happens after 7467 // we evaluate LHS and RHS. 7468 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 7469 return Error(E); 7470 7471 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 7472 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 7473 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 7474 7475 QualType LHSTy = E->getLHS()->getType(); 7476 QualType RHSTy = E->getRHS()->getType(); 7477 7478 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 7479 ComplexValue LHS, RHS; 7480 bool LHSOK; 7481 if (E->isAssignmentOp()) { 7482 LValue LV; 7483 EvaluateLValue(E->getLHS(), LV, Info); 7484 LHSOK = false; 7485 } else if (LHSTy->isRealFloatingType()) { 7486 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 7487 if (LHSOK) { 7488 LHS.makeComplexFloat(); 7489 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 7490 } 7491 } else { 7492 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 7493 } 7494 if (!LHSOK && !Info.noteFailure()) 7495 return false; 7496 7497 if (E->getRHS()->getType()->isRealFloatingType()) { 7498 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 7499 return false; 7500 RHS.makeComplexFloat(); 7501 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 7502 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 7503 return false; 7504 7505 if (LHS.isComplexFloat()) { 7506 APFloat::cmpResult CR_r = 7507 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 7508 APFloat::cmpResult CR_i = 7509 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 7510 7511 if (E->getOpcode() == BO_EQ) 7512 return Success((CR_r == APFloat::cmpEqual && 7513 CR_i == APFloat::cmpEqual), E); 7514 else { 7515 assert(E->getOpcode() == BO_NE && 7516 "Invalid complex comparison."); 7517 return Success(((CR_r == APFloat::cmpGreaterThan || 7518 CR_r == APFloat::cmpLessThan || 7519 CR_r == APFloat::cmpUnordered) || 7520 (CR_i == APFloat::cmpGreaterThan || 7521 CR_i == APFloat::cmpLessThan || 7522 CR_i == APFloat::cmpUnordered)), E); 7523 } 7524 } else { 7525 if (E->getOpcode() == BO_EQ) 7526 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() && 7527 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E); 7528 else { 7529 assert(E->getOpcode() == BO_NE && 7530 "Invalid compex comparison."); 7531 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() || 7532 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E); 7533 } 7534 } 7535 } 7536 7537 if (LHSTy->isRealFloatingType() && 7538 RHSTy->isRealFloatingType()) { 7539 APFloat RHS(0.0), LHS(0.0); 7540 7541 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 7542 if (!LHSOK && !Info.noteFailure()) 7543 return false; 7544 7545 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 7546 return false; 7547 7548 APFloat::cmpResult CR = LHS.compare(RHS); 7549 7550 switch (E->getOpcode()) { 7551 default: 7552 llvm_unreachable("Invalid binary operator!"); 7553 case BO_LT: 7554 return Success(CR == APFloat::cmpLessThan, E); 7555 case BO_GT: 7556 return Success(CR == APFloat::cmpGreaterThan, E); 7557 case BO_LE: 7558 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E); 7559 case BO_GE: 7560 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual, 7561 E); 7562 case BO_EQ: 7563 return Success(CR == APFloat::cmpEqual, E); 7564 case BO_NE: 7565 return Success(CR == APFloat::cmpGreaterThan 7566 || CR == APFloat::cmpLessThan 7567 || CR == APFloat::cmpUnordered, E); 7568 } 7569 } 7570 7571 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 7572 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) { 7573 LValue LHSValue, RHSValue; 7574 7575 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 7576 if (!LHSOK && !Info.noteFailure()) 7577 return false; 7578 7579 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 7580 return false; 7581 7582 // Reject differing bases from the normal codepath; we special-case 7583 // comparisons to null. 7584 if (!HasSameBase(LHSValue, RHSValue)) { 7585 if (E->getOpcode() == BO_Sub) { 7586 // Handle &&A - &&B. 7587 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 7588 return Error(E); 7589 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>(); 7590 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>(); 7591 if (!LHSExpr || !RHSExpr) 7592 return Error(E); 7593 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 7594 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 7595 if (!LHSAddrExpr || !RHSAddrExpr) 7596 return Error(E); 7597 // Make sure both labels come from the same function. 7598 if (LHSAddrExpr->getLabel()->getDeclContext() != 7599 RHSAddrExpr->getLabel()->getDeclContext()) 7600 return Error(E); 7601 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 7602 } 7603 // Inequalities and subtractions between unrelated pointers have 7604 // unspecified or undefined behavior. 7605 if (!E->isEqualityOp()) 7606 return Error(E); 7607 // A constant address may compare equal to the address of a symbol. 7608 // The one exception is that address of an object cannot compare equal 7609 // to a null pointer constant. 7610 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 7611 (!RHSValue.Base && !RHSValue.Offset.isZero())) 7612 return Error(E); 7613 // It's implementation-defined whether distinct literals will have 7614 // distinct addresses. In clang, the result of such a comparison is 7615 // unspecified, so it is not a constant expression. However, we do know 7616 // that the address of a literal will be non-null. 7617 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 7618 LHSValue.Base && RHSValue.Base) 7619 return Error(E); 7620 // We can't tell whether weak symbols will end up pointing to the same 7621 // object. 7622 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 7623 return Error(E); 7624 // We can't compare the address of the start of one object with the 7625 // past-the-end address of another object, per C++ DR1652. 7626 if ((LHSValue.Base && LHSValue.Offset.isZero() && 7627 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 7628 (RHSValue.Base && RHSValue.Offset.isZero() && 7629 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 7630 return Error(E); 7631 // We can't tell whether an object is at the same address as another 7632 // zero sized object. 7633 if ((RHSValue.Base && isZeroSized(LHSValue)) || 7634 (LHSValue.Base && isZeroSized(RHSValue))) 7635 return Error(E); 7636 // Pointers with different bases cannot represent the same object. 7637 // (Note that clang defaults to -fmerge-all-constants, which can 7638 // lead to inconsistent results for comparisons involving the address 7639 // of a constant; this generally doesn't matter in practice.) 7640 return Success(E->getOpcode() == BO_NE, E); 7641 } 7642 7643 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 7644 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 7645 7646 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 7647 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 7648 7649 if (E->getOpcode() == BO_Sub) { 7650 // C++11 [expr.add]p6: 7651 // Unless both pointers point to elements of the same array object, or 7652 // one past the last element of the array object, the behavior is 7653 // undefined. 7654 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 7655 !AreElementsOfSameArray(getType(LHSValue.Base), 7656 LHSDesignator, RHSDesignator)) 7657 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 7658 7659 QualType Type = E->getLHS()->getType(); 7660 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 7661 7662 CharUnits ElementSize; 7663 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 7664 return false; 7665 7666 // As an extension, a type may have zero size (empty struct or union in 7667 // C, array of zero length). Pointer subtraction in such cases has 7668 // undefined behavior, so is not constant. 7669 if (ElementSize.isZero()) { 7670 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 7671 << ElementType; 7672 return false; 7673 } 7674 7675 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 7676 // and produce incorrect results when it overflows. Such behavior 7677 // appears to be non-conforming, but is common, so perhaps we should 7678 // assume the standard intended for such cases to be undefined behavior 7679 // and check for them. 7680 7681 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 7682 // overflow in the final conversion to ptrdiff_t. 7683 APSInt LHS( 7684 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 7685 APSInt RHS( 7686 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 7687 APSInt ElemSize( 7688 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false); 7689 APSInt TrueResult = (LHS - RHS) / ElemSize; 7690 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 7691 7692 if (Result.extend(65) != TrueResult && 7693 !HandleOverflow(Info, E, TrueResult, E->getType())) 7694 return false; 7695 return Success(Result, E); 7696 } 7697 7698 // C++11 [expr.rel]p3: 7699 // Pointers to void (after pointer conversions) can be compared, with a 7700 // result defined as follows: If both pointers represent the same 7701 // address or are both the null pointer value, the result is true if the 7702 // operator is <= or >= and false otherwise; otherwise the result is 7703 // unspecified. 7704 // We interpret this as applying to pointers to *cv* void. 7705 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && 7706 E->isRelationalOp()) 7707 CCEDiag(E, diag::note_constexpr_void_comparison); 7708 7709 // C++11 [expr.rel]p2: 7710 // - If two pointers point to non-static data members of the same object, 7711 // or to subobjects or array elements fo such members, recursively, the 7712 // pointer to the later declared member compares greater provided the 7713 // two members have the same access control and provided their class is 7714 // not a union. 7715 // [...] 7716 // - Otherwise pointer comparisons are unspecified. 7717 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 7718 E->isRelationalOp()) { 7719 bool WasArrayIndex; 7720 unsigned Mismatch = 7721 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator, 7722 RHSDesignator, WasArrayIndex); 7723 // At the point where the designators diverge, the comparison has a 7724 // specified value if: 7725 // - we are comparing array indices 7726 // - we are comparing fields of a union, or fields with the same access 7727 // Otherwise, the result is unspecified and thus the comparison is not a 7728 // constant expression. 7729 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 7730 Mismatch < RHSDesignator.Entries.size()) { 7731 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 7732 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 7733 if (!LF && !RF) 7734 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 7735 else if (!LF) 7736 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 7737 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 7738 << RF->getParent() << RF; 7739 else if (!RF) 7740 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 7741 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 7742 << LF->getParent() << LF; 7743 else if (!LF->getParent()->isUnion() && 7744 LF->getAccess() != RF->getAccess()) 7745 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access) 7746 << LF << LF->getAccess() << RF << RF->getAccess() 7747 << LF->getParent(); 7748 } 7749 } 7750 7751 // The comparison here must be unsigned, and performed with the same 7752 // width as the pointer. 7753 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 7754 uint64_t CompareLHS = LHSOffset.getQuantity(); 7755 uint64_t CompareRHS = RHSOffset.getQuantity(); 7756 assert(PtrSize <= 64 && "Unexpected pointer width"); 7757 uint64_t Mask = ~0ULL >> (64 - PtrSize); 7758 CompareLHS &= Mask; 7759 CompareRHS &= Mask; 7760 7761 // If there is a base and this is a relational operator, we can only 7762 // compare pointers within the object in question; otherwise, the result 7763 // depends on where the object is located in memory. 7764 if (!LHSValue.Base.isNull() && E->isRelationalOp()) { 7765 QualType BaseTy = getType(LHSValue.Base); 7766 if (BaseTy->isIncompleteType()) 7767 return Error(E); 7768 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 7769 uint64_t OffsetLimit = Size.getQuantity(); 7770 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 7771 return Error(E); 7772 } 7773 7774 switch (E->getOpcode()) { 7775 default: llvm_unreachable("missing comparison operator"); 7776 case BO_LT: return Success(CompareLHS < CompareRHS, E); 7777 case BO_GT: return Success(CompareLHS > CompareRHS, E); 7778 case BO_LE: return Success(CompareLHS <= CompareRHS, E); 7779 case BO_GE: return Success(CompareLHS >= CompareRHS, E); 7780 case BO_EQ: return Success(CompareLHS == CompareRHS, E); 7781 case BO_NE: return Success(CompareLHS != CompareRHS, E); 7782 } 7783 } 7784 } 7785 7786 if (LHSTy->isMemberPointerType()) { 7787 assert(E->isEqualityOp() && "unexpected member pointer operation"); 7788 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 7789 7790 MemberPtr LHSValue, RHSValue; 7791 7792 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 7793 if (!LHSOK && !Info.noteFailure()) 7794 return false; 7795 7796 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 7797 return false; 7798 7799 // C++11 [expr.eq]p2: 7800 // If both operands are null, they compare equal. Otherwise if only one is 7801 // null, they compare unequal. 7802 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 7803 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 7804 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E); 7805 } 7806 7807 // Otherwise if either is a pointer to a virtual member function, the 7808 // result is unspecified. 7809 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 7810 if (MD->isVirtual()) 7811 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 7812 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 7813 if (MD->isVirtual()) 7814 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 7815 7816 // Otherwise they compare equal if and only if they would refer to the 7817 // same member of the same most derived object or the same subobject if 7818 // they were dereferenced with a hypothetical object of the associated 7819 // class type. 7820 bool Equal = LHSValue == RHSValue; 7821 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E); 7822 } 7823 7824 if (LHSTy->isNullPtrType()) { 7825 assert(E->isComparisonOp() && "unexpected nullptr operation"); 7826 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 7827 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 7828 // are compared, the result is true of the operator is <=, >= or ==, and 7829 // false otherwise. 7830 BinaryOperator::Opcode Opcode = E->getOpcode(); 7831 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E); 7832 } 7833 7834 assert((!LHSTy->isIntegralOrEnumerationType() || 7835 !RHSTy->isIntegralOrEnumerationType()) && 7836 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 7837 // We can't continue from here for non-integral types. 7838 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7839 } 7840 7841 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 7842 /// a result as the expression's type. 7843 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 7844 const UnaryExprOrTypeTraitExpr *E) { 7845 switch(E->getKind()) { 7846 case UETT_AlignOf: { 7847 if (E->isArgumentType()) 7848 return Success(GetAlignOfType(Info, E->getArgumentType()), E); 7849 else 7850 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E); 7851 } 7852 7853 case UETT_VecStep: { 7854 QualType Ty = E->getTypeOfArgument(); 7855 7856 if (Ty->isVectorType()) { 7857 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 7858 7859 // The vec_step built-in functions that take a 3-component 7860 // vector return 4. (OpenCL 1.1 spec 6.11.12) 7861 if (n == 3) 7862 n = 4; 7863 7864 return Success(n, E); 7865 } else 7866 return Success(1, E); 7867 } 7868 7869 case UETT_SizeOf: { 7870 QualType SrcTy = E->getTypeOfArgument(); 7871 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 7872 // the result is the size of the referenced type." 7873 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 7874 SrcTy = Ref->getPointeeType(); 7875 7876 CharUnits Sizeof; 7877 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 7878 return false; 7879 return Success(Sizeof, E); 7880 } 7881 case UETT_OpenMPRequiredSimdAlign: 7882 assert(E->isArgumentType()); 7883 return Success( 7884 Info.Ctx.toCharUnitsFromBits( 7885 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 7886 .getQuantity(), 7887 E); 7888 } 7889 7890 llvm_unreachable("unknown expr/type trait"); 7891 } 7892 7893 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 7894 CharUnits Result; 7895 unsigned n = OOE->getNumComponents(); 7896 if (n == 0) 7897 return Error(OOE); 7898 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 7899 for (unsigned i = 0; i != n; ++i) { 7900 OffsetOfNode ON = OOE->getComponent(i); 7901 switch (ON.getKind()) { 7902 case OffsetOfNode::Array: { 7903 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 7904 APSInt IdxResult; 7905 if (!EvaluateInteger(Idx, IdxResult, Info)) 7906 return false; 7907 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 7908 if (!AT) 7909 return Error(OOE); 7910 CurrentType = AT->getElementType(); 7911 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 7912 Result += IdxResult.getSExtValue() * ElementSize; 7913 break; 7914 } 7915 7916 case OffsetOfNode::Field: { 7917 FieldDecl *MemberDecl = ON.getField(); 7918 const RecordType *RT = CurrentType->getAs<RecordType>(); 7919 if (!RT) 7920 return Error(OOE); 7921 RecordDecl *RD = RT->getDecl(); 7922 if (RD->isInvalidDecl()) return false; 7923 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 7924 unsigned i = MemberDecl->getFieldIndex(); 7925 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 7926 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 7927 CurrentType = MemberDecl->getType().getNonReferenceType(); 7928 break; 7929 } 7930 7931 case OffsetOfNode::Identifier: 7932 llvm_unreachable("dependent __builtin_offsetof"); 7933 7934 case OffsetOfNode::Base: { 7935 CXXBaseSpecifier *BaseSpec = ON.getBase(); 7936 if (BaseSpec->isVirtual()) 7937 return Error(OOE); 7938 7939 // Find the layout of the class whose base we are looking into. 7940 const RecordType *RT = CurrentType->getAs<RecordType>(); 7941 if (!RT) 7942 return Error(OOE); 7943 RecordDecl *RD = RT->getDecl(); 7944 if (RD->isInvalidDecl()) return false; 7945 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 7946 7947 // Find the base class itself. 7948 CurrentType = BaseSpec->getType(); 7949 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 7950 if (!BaseRT) 7951 return Error(OOE); 7952 7953 // Add the offset to the base. 7954 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 7955 break; 7956 } 7957 } 7958 } 7959 return Success(Result, OOE); 7960 } 7961 7962 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 7963 switch (E->getOpcode()) { 7964 default: 7965 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 7966 // See C99 6.6p3. 7967 return Error(E); 7968 case UO_Extension: 7969 // FIXME: Should extension allow i-c-e extension expressions in its scope? 7970 // If so, we could clear the diagnostic ID. 7971 return Visit(E->getSubExpr()); 7972 case UO_Plus: 7973 // The result is just the value. 7974 return Visit(E->getSubExpr()); 7975 case UO_Minus: { 7976 if (!Visit(E->getSubExpr())) 7977 return false; 7978 if (!Result.isInt()) return Error(E); 7979 const APSInt &Value = Result.getInt(); 7980 if (Value.isSigned() && Value.isMinSignedValue() && 7981 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 7982 E->getType())) 7983 return false; 7984 return Success(-Value, E); 7985 } 7986 case UO_Not: { 7987 if (!Visit(E->getSubExpr())) 7988 return false; 7989 if (!Result.isInt()) return Error(E); 7990 return Success(~Result.getInt(), E); 7991 } 7992 case UO_LNot: { 7993 bool bres; 7994 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 7995 return false; 7996 return Success(!bres, E); 7997 } 7998 } 7999 } 8000 8001 /// HandleCast - This is used to evaluate implicit or explicit casts where the 8002 /// result type is integer. 8003 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 8004 const Expr *SubExpr = E->getSubExpr(); 8005 QualType DestType = E->getType(); 8006 QualType SrcType = SubExpr->getType(); 8007 8008 switch (E->getCastKind()) { 8009 case CK_BaseToDerived: 8010 case CK_DerivedToBase: 8011 case CK_UncheckedDerivedToBase: 8012 case CK_Dynamic: 8013 case CK_ToUnion: 8014 case CK_ArrayToPointerDecay: 8015 case CK_FunctionToPointerDecay: 8016 case CK_NullToPointer: 8017 case CK_NullToMemberPointer: 8018 case CK_BaseToDerivedMemberPointer: 8019 case CK_DerivedToBaseMemberPointer: 8020 case CK_ReinterpretMemberPointer: 8021 case CK_ConstructorConversion: 8022 case CK_IntegralToPointer: 8023 case CK_ToVoid: 8024 case CK_VectorSplat: 8025 case CK_IntegralToFloating: 8026 case CK_FloatingCast: 8027 case CK_CPointerToObjCPointerCast: 8028 case CK_BlockPointerToObjCPointerCast: 8029 case CK_AnyPointerToBlockPointerCast: 8030 case CK_ObjCObjectLValueCast: 8031 case CK_FloatingRealToComplex: 8032 case CK_FloatingComplexToReal: 8033 case CK_FloatingComplexCast: 8034 case CK_FloatingComplexToIntegralComplex: 8035 case CK_IntegralRealToComplex: 8036 case CK_IntegralComplexCast: 8037 case CK_IntegralComplexToFloatingComplex: 8038 case CK_BuiltinFnToFnPtr: 8039 case CK_ZeroToOCLEvent: 8040 case CK_NonAtomicToAtomic: 8041 case CK_AddressSpaceConversion: 8042 llvm_unreachable("invalid cast kind for integral value"); 8043 8044 case CK_BitCast: 8045 case CK_Dependent: 8046 case CK_LValueBitCast: 8047 case CK_ARCProduceObject: 8048 case CK_ARCConsumeObject: 8049 case CK_ARCReclaimReturnedObject: 8050 case CK_ARCExtendBlockObject: 8051 case CK_CopyAndAutoreleaseBlockObject: 8052 return Error(E); 8053 8054 case CK_UserDefinedConversion: 8055 case CK_LValueToRValue: 8056 case CK_AtomicToNonAtomic: 8057 case CK_NoOp: 8058 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8059 8060 case CK_MemberPointerToBoolean: 8061 case CK_PointerToBoolean: 8062 case CK_IntegralToBoolean: 8063 case CK_FloatingToBoolean: 8064 case CK_BooleanToSignedIntegral: 8065 case CK_FloatingComplexToBoolean: 8066 case CK_IntegralComplexToBoolean: { 8067 bool BoolResult; 8068 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 8069 return false; 8070 uint64_t IntResult = BoolResult; 8071 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 8072 IntResult = (uint64_t)-1; 8073 return Success(IntResult, E); 8074 } 8075 8076 case CK_IntegralCast: { 8077 if (!Visit(SubExpr)) 8078 return false; 8079 8080 if (!Result.isInt()) { 8081 // Allow casts of address-of-label differences if they are no-ops 8082 // or narrowing. (The narrowing case isn't actually guaranteed to 8083 // be constant-evaluatable except in some narrow cases which are hard 8084 // to detect here. We let it through on the assumption the user knows 8085 // what they are doing.) 8086 if (Result.isAddrLabelDiff()) 8087 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 8088 // Only allow casts of lvalues if they are lossless. 8089 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 8090 } 8091 8092 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 8093 Result.getInt()), E); 8094 } 8095 8096 case CK_PointerToIntegral: { 8097 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 8098 8099 LValue LV; 8100 if (!EvaluatePointer(SubExpr, LV, Info)) 8101 return false; 8102 8103 if (LV.getLValueBase()) { 8104 // Only allow based lvalue casts if they are lossless. 8105 // FIXME: Allow a larger integer size than the pointer size, and allow 8106 // narrowing back down to pointer width in subsequent integral casts. 8107 // FIXME: Check integer type's active bits, not its type size. 8108 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 8109 return Error(E); 8110 8111 LV.Designator.setInvalid(); 8112 LV.moveInto(Result); 8113 return true; 8114 } 8115 8116 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(), 8117 SrcType); 8118 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 8119 } 8120 8121 case CK_IntegralComplexToReal: { 8122 ComplexValue C; 8123 if (!EvaluateComplex(SubExpr, C, Info)) 8124 return false; 8125 return Success(C.getComplexIntReal(), E); 8126 } 8127 8128 case CK_FloatingToIntegral: { 8129 APFloat F(0.0); 8130 if (!EvaluateFloat(SubExpr, F, Info)) 8131 return false; 8132 8133 APSInt Value; 8134 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 8135 return false; 8136 return Success(Value, E); 8137 } 8138 } 8139 8140 llvm_unreachable("unknown cast resulting in integral value"); 8141 } 8142 8143 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8144 if (E->getSubExpr()->getType()->isAnyComplexType()) { 8145 ComplexValue LV; 8146 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 8147 return false; 8148 if (!LV.isComplexInt()) 8149 return Error(E); 8150 return Success(LV.getComplexIntReal(), E); 8151 } 8152 8153 return Visit(E->getSubExpr()); 8154 } 8155 8156 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8157 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 8158 ComplexValue LV; 8159 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 8160 return false; 8161 if (!LV.isComplexInt()) 8162 return Error(E); 8163 return Success(LV.getComplexIntImag(), E); 8164 } 8165 8166 VisitIgnoredValue(E->getSubExpr()); 8167 return Success(0, E); 8168 } 8169 8170 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 8171 return Success(E->getPackLength(), E); 8172 } 8173 8174 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 8175 return Success(E->getValue(), E); 8176 } 8177 8178 //===----------------------------------------------------------------------===// 8179 // Float Evaluation 8180 //===----------------------------------------------------------------------===// 8181 8182 namespace { 8183 class FloatExprEvaluator 8184 : public ExprEvaluatorBase<FloatExprEvaluator> { 8185 APFloat &Result; 8186 public: 8187 FloatExprEvaluator(EvalInfo &info, APFloat &result) 8188 : ExprEvaluatorBaseTy(info), Result(result) {} 8189 8190 bool Success(const APValue &V, const Expr *e) { 8191 Result = V.getFloat(); 8192 return true; 8193 } 8194 8195 bool ZeroInitialization(const Expr *E) { 8196 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 8197 return true; 8198 } 8199 8200 bool VisitCallExpr(const CallExpr *E); 8201 8202 bool VisitUnaryOperator(const UnaryOperator *E); 8203 bool VisitBinaryOperator(const BinaryOperator *E); 8204 bool VisitFloatingLiteral(const FloatingLiteral *E); 8205 bool VisitCastExpr(const CastExpr *E); 8206 8207 bool VisitUnaryReal(const UnaryOperator *E); 8208 bool VisitUnaryImag(const UnaryOperator *E); 8209 8210 // FIXME: Missing: array subscript of vector, member of vector 8211 }; 8212 } // end anonymous namespace 8213 8214 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 8215 assert(E->isRValue() && E->getType()->isRealFloatingType()); 8216 return FloatExprEvaluator(Info, Result).Visit(E); 8217 } 8218 8219 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 8220 QualType ResultTy, 8221 const Expr *Arg, 8222 bool SNaN, 8223 llvm::APFloat &Result) { 8224 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 8225 if (!S) return false; 8226 8227 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 8228 8229 llvm::APInt fill; 8230 8231 // Treat empty strings as if they were zero. 8232 if (S->getString().empty()) 8233 fill = llvm::APInt(32, 0); 8234 else if (S->getString().getAsInteger(0, fill)) 8235 return false; 8236 8237 if (Context.getTargetInfo().isNan2008()) { 8238 if (SNaN) 8239 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 8240 else 8241 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 8242 } else { 8243 // Prior to IEEE 754-2008, architectures were allowed to choose whether 8244 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 8245 // a different encoding to what became a standard in 2008, and for pre- 8246 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 8247 // sNaN. This is now known as "legacy NaN" encoding. 8248 if (SNaN) 8249 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 8250 else 8251 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 8252 } 8253 8254 return true; 8255 } 8256 8257 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 8258 switch (E->getBuiltinCallee()) { 8259 default: 8260 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8261 8262 case Builtin::BI__builtin_huge_val: 8263 case Builtin::BI__builtin_huge_valf: 8264 case Builtin::BI__builtin_huge_vall: 8265 case Builtin::BI__builtin_inf: 8266 case Builtin::BI__builtin_inff: 8267 case Builtin::BI__builtin_infl: { 8268 const llvm::fltSemantics &Sem = 8269 Info.Ctx.getFloatTypeSemantics(E->getType()); 8270 Result = llvm::APFloat::getInf(Sem); 8271 return true; 8272 } 8273 8274 case Builtin::BI__builtin_nans: 8275 case Builtin::BI__builtin_nansf: 8276 case Builtin::BI__builtin_nansl: 8277 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 8278 true, Result)) 8279 return Error(E); 8280 return true; 8281 8282 case Builtin::BI__builtin_nan: 8283 case Builtin::BI__builtin_nanf: 8284 case Builtin::BI__builtin_nanl: 8285 // If this is __builtin_nan() turn this into a nan, otherwise we 8286 // can't constant fold it. 8287 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 8288 false, Result)) 8289 return Error(E); 8290 return true; 8291 8292 case Builtin::BI__builtin_fabs: 8293 case Builtin::BI__builtin_fabsf: 8294 case Builtin::BI__builtin_fabsl: 8295 if (!EvaluateFloat(E->getArg(0), Result, Info)) 8296 return false; 8297 8298 if (Result.isNegative()) 8299 Result.changeSign(); 8300 return true; 8301 8302 // FIXME: Builtin::BI__builtin_powi 8303 // FIXME: Builtin::BI__builtin_powif 8304 // FIXME: Builtin::BI__builtin_powil 8305 8306 case Builtin::BI__builtin_copysign: 8307 case Builtin::BI__builtin_copysignf: 8308 case Builtin::BI__builtin_copysignl: { 8309 APFloat RHS(0.); 8310 if (!EvaluateFloat(E->getArg(0), Result, Info) || 8311 !EvaluateFloat(E->getArg(1), RHS, Info)) 8312 return false; 8313 Result.copySign(RHS); 8314 return true; 8315 } 8316 } 8317 } 8318 8319 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 8320 if (E->getSubExpr()->getType()->isAnyComplexType()) { 8321 ComplexValue CV; 8322 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 8323 return false; 8324 Result = CV.FloatReal; 8325 return true; 8326 } 8327 8328 return Visit(E->getSubExpr()); 8329 } 8330 8331 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8332 if (E->getSubExpr()->getType()->isAnyComplexType()) { 8333 ComplexValue CV; 8334 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 8335 return false; 8336 Result = CV.FloatImag; 8337 return true; 8338 } 8339 8340 VisitIgnoredValue(E->getSubExpr()); 8341 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 8342 Result = llvm::APFloat::getZero(Sem); 8343 return true; 8344 } 8345 8346 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 8347 switch (E->getOpcode()) { 8348 default: return Error(E); 8349 case UO_Plus: 8350 return EvaluateFloat(E->getSubExpr(), Result, Info); 8351 case UO_Minus: 8352 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 8353 return false; 8354 Result.changeSign(); 8355 return true; 8356 } 8357 } 8358 8359 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8360 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 8361 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8362 8363 APFloat RHS(0.0); 8364 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 8365 if (!LHSOK && !Info.noteFailure()) 8366 return false; 8367 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 8368 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 8369 } 8370 8371 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 8372 Result = E->getValue(); 8373 return true; 8374 } 8375 8376 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 8377 const Expr* SubExpr = E->getSubExpr(); 8378 8379 switch (E->getCastKind()) { 8380 default: 8381 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8382 8383 case CK_IntegralToFloating: { 8384 APSInt IntResult; 8385 return EvaluateInteger(SubExpr, IntResult, Info) && 8386 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 8387 E->getType(), Result); 8388 } 8389 8390 case CK_FloatingCast: { 8391 if (!Visit(SubExpr)) 8392 return false; 8393 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 8394 Result); 8395 } 8396 8397 case CK_FloatingComplexToReal: { 8398 ComplexValue V; 8399 if (!EvaluateComplex(SubExpr, V, Info)) 8400 return false; 8401 Result = V.getComplexFloatReal(); 8402 return true; 8403 } 8404 } 8405 } 8406 8407 //===----------------------------------------------------------------------===// 8408 // Complex Evaluation (for float and integer) 8409 //===----------------------------------------------------------------------===// 8410 8411 namespace { 8412 class ComplexExprEvaluator 8413 : public ExprEvaluatorBase<ComplexExprEvaluator> { 8414 ComplexValue &Result; 8415 8416 public: 8417 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 8418 : ExprEvaluatorBaseTy(info), Result(Result) {} 8419 8420 bool Success(const APValue &V, const Expr *e) { 8421 Result.setFrom(V); 8422 return true; 8423 } 8424 8425 bool ZeroInitialization(const Expr *E); 8426 8427 //===--------------------------------------------------------------------===// 8428 // Visitor Methods 8429 //===--------------------------------------------------------------------===// 8430 8431 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 8432 bool VisitCastExpr(const CastExpr *E); 8433 bool VisitBinaryOperator(const BinaryOperator *E); 8434 bool VisitUnaryOperator(const UnaryOperator *E); 8435 bool VisitInitListExpr(const InitListExpr *E); 8436 }; 8437 } // end anonymous namespace 8438 8439 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 8440 EvalInfo &Info) { 8441 assert(E->isRValue() && E->getType()->isAnyComplexType()); 8442 return ComplexExprEvaluator(Info, Result).Visit(E); 8443 } 8444 8445 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 8446 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 8447 if (ElemTy->isRealFloatingType()) { 8448 Result.makeComplexFloat(); 8449 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 8450 Result.FloatReal = Zero; 8451 Result.FloatImag = Zero; 8452 } else { 8453 Result.makeComplexInt(); 8454 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 8455 Result.IntReal = Zero; 8456 Result.IntImag = Zero; 8457 } 8458 return true; 8459 } 8460 8461 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 8462 const Expr* SubExpr = E->getSubExpr(); 8463 8464 if (SubExpr->getType()->isRealFloatingType()) { 8465 Result.makeComplexFloat(); 8466 APFloat &Imag = Result.FloatImag; 8467 if (!EvaluateFloat(SubExpr, Imag, Info)) 8468 return false; 8469 8470 Result.FloatReal = APFloat(Imag.getSemantics()); 8471 return true; 8472 } else { 8473 assert(SubExpr->getType()->isIntegerType() && 8474 "Unexpected imaginary literal."); 8475 8476 Result.makeComplexInt(); 8477 APSInt &Imag = Result.IntImag; 8478 if (!EvaluateInteger(SubExpr, Imag, Info)) 8479 return false; 8480 8481 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 8482 return true; 8483 } 8484 } 8485 8486 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 8487 8488 switch (E->getCastKind()) { 8489 case CK_BitCast: 8490 case CK_BaseToDerived: 8491 case CK_DerivedToBase: 8492 case CK_UncheckedDerivedToBase: 8493 case CK_Dynamic: 8494 case CK_ToUnion: 8495 case CK_ArrayToPointerDecay: 8496 case CK_FunctionToPointerDecay: 8497 case CK_NullToPointer: 8498 case CK_NullToMemberPointer: 8499 case CK_BaseToDerivedMemberPointer: 8500 case CK_DerivedToBaseMemberPointer: 8501 case CK_MemberPointerToBoolean: 8502 case CK_ReinterpretMemberPointer: 8503 case CK_ConstructorConversion: 8504 case CK_IntegralToPointer: 8505 case CK_PointerToIntegral: 8506 case CK_PointerToBoolean: 8507 case CK_ToVoid: 8508 case CK_VectorSplat: 8509 case CK_IntegralCast: 8510 case CK_BooleanToSignedIntegral: 8511 case CK_IntegralToBoolean: 8512 case CK_IntegralToFloating: 8513 case CK_FloatingToIntegral: 8514 case CK_FloatingToBoolean: 8515 case CK_FloatingCast: 8516 case CK_CPointerToObjCPointerCast: 8517 case CK_BlockPointerToObjCPointerCast: 8518 case CK_AnyPointerToBlockPointerCast: 8519 case CK_ObjCObjectLValueCast: 8520 case CK_FloatingComplexToReal: 8521 case CK_FloatingComplexToBoolean: 8522 case CK_IntegralComplexToReal: 8523 case CK_IntegralComplexToBoolean: 8524 case CK_ARCProduceObject: 8525 case CK_ARCConsumeObject: 8526 case CK_ARCReclaimReturnedObject: 8527 case CK_ARCExtendBlockObject: 8528 case CK_CopyAndAutoreleaseBlockObject: 8529 case CK_BuiltinFnToFnPtr: 8530 case CK_ZeroToOCLEvent: 8531 case CK_NonAtomicToAtomic: 8532 case CK_AddressSpaceConversion: 8533 llvm_unreachable("invalid cast kind for complex value"); 8534 8535 case CK_LValueToRValue: 8536 case CK_AtomicToNonAtomic: 8537 case CK_NoOp: 8538 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8539 8540 case CK_Dependent: 8541 case CK_LValueBitCast: 8542 case CK_UserDefinedConversion: 8543 return Error(E); 8544 8545 case CK_FloatingRealToComplex: { 8546 APFloat &Real = Result.FloatReal; 8547 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 8548 return false; 8549 8550 Result.makeComplexFloat(); 8551 Result.FloatImag = APFloat(Real.getSemantics()); 8552 return true; 8553 } 8554 8555 case CK_FloatingComplexCast: { 8556 if (!Visit(E->getSubExpr())) 8557 return false; 8558 8559 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 8560 QualType From 8561 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 8562 8563 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 8564 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 8565 } 8566 8567 case CK_FloatingComplexToIntegralComplex: { 8568 if (!Visit(E->getSubExpr())) 8569 return false; 8570 8571 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 8572 QualType From 8573 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 8574 Result.makeComplexInt(); 8575 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 8576 To, Result.IntReal) && 8577 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 8578 To, Result.IntImag); 8579 } 8580 8581 case CK_IntegralRealToComplex: { 8582 APSInt &Real = Result.IntReal; 8583 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 8584 return false; 8585 8586 Result.makeComplexInt(); 8587 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 8588 return true; 8589 } 8590 8591 case CK_IntegralComplexCast: { 8592 if (!Visit(E->getSubExpr())) 8593 return false; 8594 8595 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 8596 QualType From 8597 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 8598 8599 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 8600 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 8601 return true; 8602 } 8603 8604 case CK_IntegralComplexToFloatingComplex: { 8605 if (!Visit(E->getSubExpr())) 8606 return false; 8607 8608 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 8609 QualType From 8610 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 8611 Result.makeComplexFloat(); 8612 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 8613 To, Result.FloatReal) && 8614 HandleIntToFloatCast(Info, E, From, Result.IntImag, 8615 To, Result.FloatImag); 8616 } 8617 } 8618 8619 llvm_unreachable("unknown cast resulting in complex value"); 8620 } 8621 8622 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8623 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 8624 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8625 8626 // Track whether the LHS or RHS is real at the type system level. When this is 8627 // the case we can simplify our evaluation strategy. 8628 bool LHSReal = false, RHSReal = false; 8629 8630 bool LHSOK; 8631 if (E->getLHS()->getType()->isRealFloatingType()) { 8632 LHSReal = true; 8633 APFloat &Real = Result.FloatReal; 8634 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 8635 if (LHSOK) { 8636 Result.makeComplexFloat(); 8637 Result.FloatImag = APFloat(Real.getSemantics()); 8638 } 8639 } else { 8640 LHSOK = Visit(E->getLHS()); 8641 } 8642 if (!LHSOK && !Info.noteFailure()) 8643 return false; 8644 8645 ComplexValue RHS; 8646 if (E->getRHS()->getType()->isRealFloatingType()) { 8647 RHSReal = true; 8648 APFloat &Real = RHS.FloatReal; 8649 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 8650 return false; 8651 RHS.makeComplexFloat(); 8652 RHS.FloatImag = APFloat(Real.getSemantics()); 8653 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 8654 return false; 8655 8656 assert(!(LHSReal && RHSReal) && 8657 "Cannot have both operands of a complex operation be real."); 8658 switch (E->getOpcode()) { 8659 default: return Error(E); 8660 case BO_Add: 8661 if (Result.isComplexFloat()) { 8662 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 8663 APFloat::rmNearestTiesToEven); 8664 if (LHSReal) 8665 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 8666 else if (!RHSReal) 8667 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 8668 APFloat::rmNearestTiesToEven); 8669 } else { 8670 Result.getComplexIntReal() += RHS.getComplexIntReal(); 8671 Result.getComplexIntImag() += RHS.getComplexIntImag(); 8672 } 8673 break; 8674 case BO_Sub: 8675 if (Result.isComplexFloat()) { 8676 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 8677 APFloat::rmNearestTiesToEven); 8678 if (LHSReal) { 8679 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 8680 Result.getComplexFloatImag().changeSign(); 8681 } else if (!RHSReal) { 8682 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 8683 APFloat::rmNearestTiesToEven); 8684 } 8685 } else { 8686 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 8687 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 8688 } 8689 break; 8690 case BO_Mul: 8691 if (Result.isComplexFloat()) { 8692 // This is an implementation of complex multiplication according to the 8693 // constraints laid out in C11 Annex G. The implemantion uses the 8694 // following naming scheme: 8695 // (a + ib) * (c + id) 8696 ComplexValue LHS = Result; 8697 APFloat &A = LHS.getComplexFloatReal(); 8698 APFloat &B = LHS.getComplexFloatImag(); 8699 APFloat &C = RHS.getComplexFloatReal(); 8700 APFloat &D = RHS.getComplexFloatImag(); 8701 APFloat &ResR = Result.getComplexFloatReal(); 8702 APFloat &ResI = Result.getComplexFloatImag(); 8703 if (LHSReal) { 8704 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 8705 ResR = A * C; 8706 ResI = A * D; 8707 } else if (RHSReal) { 8708 ResR = C * A; 8709 ResI = C * B; 8710 } else { 8711 // In the fully general case, we need to handle NaNs and infinities 8712 // robustly. 8713 APFloat AC = A * C; 8714 APFloat BD = B * D; 8715 APFloat AD = A * D; 8716 APFloat BC = B * C; 8717 ResR = AC - BD; 8718 ResI = AD + BC; 8719 if (ResR.isNaN() && ResI.isNaN()) { 8720 bool Recalc = false; 8721 if (A.isInfinity() || B.isInfinity()) { 8722 A = APFloat::copySign( 8723 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 8724 B = APFloat::copySign( 8725 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 8726 if (C.isNaN()) 8727 C = APFloat::copySign(APFloat(C.getSemantics()), C); 8728 if (D.isNaN()) 8729 D = APFloat::copySign(APFloat(D.getSemantics()), D); 8730 Recalc = true; 8731 } 8732 if (C.isInfinity() || D.isInfinity()) { 8733 C = APFloat::copySign( 8734 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 8735 D = APFloat::copySign( 8736 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 8737 if (A.isNaN()) 8738 A = APFloat::copySign(APFloat(A.getSemantics()), A); 8739 if (B.isNaN()) 8740 B = APFloat::copySign(APFloat(B.getSemantics()), B); 8741 Recalc = true; 8742 } 8743 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 8744 AD.isInfinity() || BC.isInfinity())) { 8745 if (A.isNaN()) 8746 A = APFloat::copySign(APFloat(A.getSemantics()), A); 8747 if (B.isNaN()) 8748 B = APFloat::copySign(APFloat(B.getSemantics()), B); 8749 if (C.isNaN()) 8750 C = APFloat::copySign(APFloat(C.getSemantics()), C); 8751 if (D.isNaN()) 8752 D = APFloat::copySign(APFloat(D.getSemantics()), D); 8753 Recalc = true; 8754 } 8755 if (Recalc) { 8756 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 8757 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 8758 } 8759 } 8760 } 8761 } else { 8762 ComplexValue LHS = Result; 8763 Result.getComplexIntReal() = 8764 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 8765 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 8766 Result.getComplexIntImag() = 8767 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 8768 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 8769 } 8770 break; 8771 case BO_Div: 8772 if (Result.isComplexFloat()) { 8773 // This is an implementation of complex division according to the 8774 // constraints laid out in C11 Annex G. The implemantion uses the 8775 // following naming scheme: 8776 // (a + ib) / (c + id) 8777 ComplexValue LHS = Result; 8778 APFloat &A = LHS.getComplexFloatReal(); 8779 APFloat &B = LHS.getComplexFloatImag(); 8780 APFloat &C = RHS.getComplexFloatReal(); 8781 APFloat &D = RHS.getComplexFloatImag(); 8782 APFloat &ResR = Result.getComplexFloatReal(); 8783 APFloat &ResI = Result.getComplexFloatImag(); 8784 if (RHSReal) { 8785 ResR = A / C; 8786 ResI = B / C; 8787 } else { 8788 if (LHSReal) { 8789 // No real optimizations we can do here, stub out with zero. 8790 B = APFloat::getZero(A.getSemantics()); 8791 } 8792 int DenomLogB = 0; 8793 APFloat MaxCD = maxnum(abs(C), abs(D)); 8794 if (MaxCD.isFinite()) { 8795 DenomLogB = ilogb(MaxCD); 8796 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 8797 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 8798 } 8799 APFloat Denom = C * C + D * D; 8800 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 8801 APFloat::rmNearestTiesToEven); 8802 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 8803 APFloat::rmNearestTiesToEven); 8804 if (ResR.isNaN() && ResI.isNaN()) { 8805 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 8806 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 8807 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 8808 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 8809 D.isFinite()) { 8810 A = APFloat::copySign( 8811 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 8812 B = APFloat::copySign( 8813 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 8814 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 8815 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 8816 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 8817 C = APFloat::copySign( 8818 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 8819 D = APFloat::copySign( 8820 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 8821 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 8822 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 8823 } 8824 } 8825 } 8826 } else { 8827 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 8828 return Error(E, diag::note_expr_divide_by_zero); 8829 8830 ComplexValue LHS = Result; 8831 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 8832 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 8833 Result.getComplexIntReal() = 8834 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 8835 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 8836 Result.getComplexIntImag() = 8837 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 8838 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 8839 } 8840 break; 8841 } 8842 8843 return true; 8844 } 8845 8846 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 8847 // Get the operand value into 'Result'. 8848 if (!Visit(E->getSubExpr())) 8849 return false; 8850 8851 switch (E->getOpcode()) { 8852 default: 8853 return Error(E); 8854 case UO_Extension: 8855 return true; 8856 case UO_Plus: 8857 // The result is always just the subexpr. 8858 return true; 8859 case UO_Minus: 8860 if (Result.isComplexFloat()) { 8861 Result.getComplexFloatReal().changeSign(); 8862 Result.getComplexFloatImag().changeSign(); 8863 } 8864 else { 8865 Result.getComplexIntReal() = -Result.getComplexIntReal(); 8866 Result.getComplexIntImag() = -Result.getComplexIntImag(); 8867 } 8868 return true; 8869 case UO_Not: 8870 if (Result.isComplexFloat()) 8871 Result.getComplexFloatImag().changeSign(); 8872 else 8873 Result.getComplexIntImag() = -Result.getComplexIntImag(); 8874 return true; 8875 } 8876 } 8877 8878 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 8879 if (E->getNumInits() == 2) { 8880 if (E->getType()->isComplexType()) { 8881 Result.makeComplexFloat(); 8882 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 8883 return false; 8884 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 8885 return false; 8886 } else { 8887 Result.makeComplexInt(); 8888 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 8889 return false; 8890 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 8891 return false; 8892 } 8893 return true; 8894 } 8895 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 8896 } 8897 8898 //===----------------------------------------------------------------------===// 8899 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 8900 // implicit conversion. 8901 //===----------------------------------------------------------------------===// 8902 8903 namespace { 8904 class AtomicExprEvaluator : 8905 public ExprEvaluatorBase<AtomicExprEvaluator> { 8906 APValue &Result; 8907 public: 8908 AtomicExprEvaluator(EvalInfo &Info, APValue &Result) 8909 : ExprEvaluatorBaseTy(Info), Result(Result) {} 8910 8911 bool Success(const APValue &V, const Expr *E) { 8912 Result = V; 8913 return true; 8914 } 8915 8916 bool ZeroInitialization(const Expr *E) { 8917 ImplicitValueInitExpr VIE( 8918 E->getType()->castAs<AtomicType>()->getValueType()); 8919 return Evaluate(Result, Info, &VIE); 8920 } 8921 8922 bool VisitCastExpr(const CastExpr *E) { 8923 switch (E->getCastKind()) { 8924 default: 8925 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8926 case CK_NonAtomicToAtomic: 8927 return Evaluate(Result, Info, E->getSubExpr()); 8928 } 8929 } 8930 }; 8931 } // end anonymous namespace 8932 8933 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) { 8934 assert(E->isRValue() && E->getType()->isAtomicType()); 8935 return AtomicExprEvaluator(Info, Result).Visit(E); 8936 } 8937 8938 //===----------------------------------------------------------------------===// 8939 // Void expression evaluation, primarily for a cast to void on the LHS of a 8940 // comma operator 8941 //===----------------------------------------------------------------------===// 8942 8943 namespace { 8944 class VoidExprEvaluator 8945 : public ExprEvaluatorBase<VoidExprEvaluator> { 8946 public: 8947 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 8948 8949 bool Success(const APValue &V, const Expr *e) { return true; } 8950 8951 bool VisitCastExpr(const CastExpr *E) { 8952 switch (E->getCastKind()) { 8953 default: 8954 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8955 case CK_ToVoid: 8956 VisitIgnoredValue(E->getSubExpr()); 8957 return true; 8958 } 8959 } 8960 8961 bool VisitCallExpr(const CallExpr *E) { 8962 switch (E->getBuiltinCallee()) { 8963 default: 8964 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8965 case Builtin::BI__assume: 8966 case Builtin::BI__builtin_assume: 8967 // The argument is not evaluated! 8968 return true; 8969 } 8970 } 8971 }; 8972 } // end anonymous namespace 8973 8974 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 8975 assert(E->isRValue() && E->getType()->isVoidType()); 8976 return VoidExprEvaluator(Info).Visit(E); 8977 } 8978 8979 //===----------------------------------------------------------------------===// 8980 // Top level Expr::EvaluateAsRValue method. 8981 //===----------------------------------------------------------------------===// 8982 8983 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 8984 // In C, function designators are not lvalues, but we evaluate them as if they 8985 // are. 8986 QualType T = E->getType(); 8987 if (E->isGLValue() || T->isFunctionType()) { 8988 LValue LV; 8989 if (!EvaluateLValue(E, LV, Info)) 8990 return false; 8991 LV.moveInto(Result); 8992 } else if (T->isVectorType()) { 8993 if (!EvaluateVector(E, Result, Info)) 8994 return false; 8995 } else if (T->isIntegralOrEnumerationType()) { 8996 if (!IntExprEvaluator(Info, Result).Visit(E)) 8997 return false; 8998 } else if (T->hasPointerRepresentation()) { 8999 LValue LV; 9000 if (!EvaluatePointer(E, LV, Info)) 9001 return false; 9002 LV.moveInto(Result); 9003 } else if (T->isRealFloatingType()) { 9004 llvm::APFloat F(0.0); 9005 if (!EvaluateFloat(E, F, Info)) 9006 return false; 9007 Result = APValue(F); 9008 } else if (T->isAnyComplexType()) { 9009 ComplexValue C; 9010 if (!EvaluateComplex(E, C, Info)) 9011 return false; 9012 C.moveInto(Result); 9013 } else if (T->isMemberPointerType()) { 9014 MemberPtr P; 9015 if (!EvaluateMemberPointer(E, P, Info)) 9016 return false; 9017 P.moveInto(Result); 9018 return true; 9019 } else if (T->isArrayType()) { 9020 LValue LV; 9021 LV.set(E, Info.CurrentCall->Index); 9022 APValue &Value = Info.CurrentCall->createTemporary(E, false); 9023 if (!EvaluateArray(E, LV, Value, Info)) 9024 return false; 9025 Result = Value; 9026 } else if (T->isRecordType()) { 9027 LValue LV; 9028 LV.set(E, Info.CurrentCall->Index); 9029 APValue &Value = Info.CurrentCall->createTemporary(E, false); 9030 if (!EvaluateRecord(E, LV, Value, Info)) 9031 return false; 9032 Result = Value; 9033 } else if (T->isVoidType()) { 9034 if (!Info.getLangOpts().CPlusPlus11) 9035 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 9036 << E->getType(); 9037 if (!EvaluateVoid(E, Info)) 9038 return false; 9039 } else if (T->isAtomicType()) { 9040 if (!EvaluateAtomic(E, Result, Info)) 9041 return false; 9042 } else if (Info.getLangOpts().CPlusPlus11) { 9043 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 9044 return false; 9045 } else { 9046 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 9047 return false; 9048 } 9049 9050 return true; 9051 } 9052 9053 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 9054 /// cases, the in-place evaluation is essential, since later initializers for 9055 /// an object can indirectly refer to subobjects which were initialized earlier. 9056 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 9057 const Expr *E, bool AllowNonLiteralTypes) { 9058 assert(!E->isValueDependent()); 9059 9060 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 9061 return false; 9062 9063 if (E->isRValue()) { 9064 // Evaluate arrays and record types in-place, so that later initializers can 9065 // refer to earlier-initialized members of the object. 9066 if (E->getType()->isArrayType()) 9067 return EvaluateArray(E, This, Result, Info); 9068 else if (E->getType()->isRecordType()) 9069 return EvaluateRecord(E, This, Result, Info); 9070 } 9071 9072 // For any other type, in-place evaluation is unimportant. 9073 return Evaluate(Result, Info, E); 9074 } 9075 9076 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 9077 /// lvalue-to-rvalue cast if it is an lvalue. 9078 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 9079 if (E->getType().isNull()) 9080 return false; 9081 9082 if (!CheckLiteralType(Info, E)) 9083 return false; 9084 9085 if (!::Evaluate(Result, Info, E)) 9086 return false; 9087 9088 if (E->isGLValue()) { 9089 LValue LV; 9090 LV.setFrom(Info.Ctx, Result); 9091 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 9092 return false; 9093 } 9094 9095 // Check this core constant expression is a constant expression. 9096 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 9097 } 9098 9099 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 9100 const ASTContext &Ctx, bool &IsConst) { 9101 // Fast-path evaluations of integer literals, since we sometimes see files 9102 // containing vast quantities of these. 9103 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 9104 Result.Val = APValue(APSInt(L->getValue(), 9105 L->getType()->isUnsignedIntegerType())); 9106 IsConst = true; 9107 return true; 9108 } 9109 9110 // This case should be rare, but we need to check it before we check on 9111 // the type below. 9112 if (Exp->getType().isNull()) { 9113 IsConst = false; 9114 return true; 9115 } 9116 9117 // FIXME: Evaluating values of large array and record types can cause 9118 // performance problems. Only do so in C++11 for now. 9119 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 9120 Exp->getType()->isRecordType()) && 9121 !Ctx.getLangOpts().CPlusPlus11) { 9122 IsConst = false; 9123 return true; 9124 } 9125 return false; 9126 } 9127 9128 9129 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 9130 /// any crazy technique (that has nothing to do with language standards) that 9131 /// we want to. If this function returns true, it returns the folded constant 9132 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 9133 /// will be applied to the result. 9134 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { 9135 bool IsConst; 9136 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst)) 9137 return IsConst; 9138 9139 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 9140 return ::EvaluateAsRValue(Info, this, Result.Val); 9141 } 9142 9143 bool Expr::EvaluateAsBooleanCondition(bool &Result, 9144 const ASTContext &Ctx) const { 9145 EvalResult Scratch; 9146 return EvaluateAsRValue(Scratch, Ctx) && 9147 HandleConversionToBool(Scratch.Val, Result); 9148 } 9149 9150 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 9151 Expr::SideEffectsKind SEK) { 9152 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 9153 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 9154 } 9155 9156 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx, 9157 SideEffectsKind AllowSideEffects) const { 9158 if (!getType()->isIntegralOrEnumerationType()) 9159 return false; 9160 9161 EvalResult ExprResult; 9162 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() || 9163 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 9164 return false; 9165 9166 Result = ExprResult.Val.getInt(); 9167 return true; 9168 } 9169 9170 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 9171 SideEffectsKind AllowSideEffects) const { 9172 if (!getType()->isRealFloatingType()) 9173 return false; 9174 9175 EvalResult ExprResult; 9176 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() || 9177 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 9178 return false; 9179 9180 Result = ExprResult.Val.getFloat(); 9181 return true; 9182 } 9183 9184 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 9185 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 9186 9187 LValue LV; 9188 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 9189 !CheckLValueConstantExpression(Info, getExprLoc(), 9190 Ctx.getLValueReferenceType(getType()), LV)) 9191 return false; 9192 9193 LV.moveInto(Result.Val); 9194 return true; 9195 } 9196 9197 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 9198 const VarDecl *VD, 9199 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 9200 // FIXME: Evaluating initializers for large array and record types can cause 9201 // performance problems. Only do so in C++11 for now. 9202 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 9203 !Ctx.getLangOpts().CPlusPlus11) 9204 return false; 9205 9206 Expr::EvalStatus EStatus; 9207 EStatus.Diag = &Notes; 9208 9209 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr() 9210 ? EvalInfo::EM_ConstantExpression 9211 : EvalInfo::EM_ConstantFold); 9212 InitInfo.setEvaluatingDecl(VD, Value); 9213 9214 LValue LVal; 9215 LVal.set(VD); 9216 9217 // C++11 [basic.start.init]p2: 9218 // Variables with static storage duration or thread storage duration shall be 9219 // zero-initialized before any other initialization takes place. 9220 // This behavior is not present in C. 9221 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 9222 !VD->getType()->isReferenceType()) { 9223 ImplicitValueInitExpr VIE(VD->getType()); 9224 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, 9225 /*AllowNonLiteralTypes=*/true)) 9226 return false; 9227 } 9228 9229 if (!EvaluateInPlace(Value, InitInfo, LVal, this, 9230 /*AllowNonLiteralTypes=*/true) || 9231 EStatus.HasSideEffects) 9232 return false; 9233 9234 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 9235 Value); 9236 } 9237 9238 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 9239 /// constant folded, but discard the result. 9240 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 9241 EvalResult Result; 9242 return EvaluateAsRValue(Result, Ctx) && 9243 !hasUnacceptableSideEffect(Result, SEK); 9244 } 9245 9246 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 9247 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 9248 EvalResult EvalResult; 9249 EvalResult.Diag = Diag; 9250 bool Result = EvaluateAsRValue(EvalResult, Ctx); 9251 (void)Result; 9252 assert(Result && "Could not evaluate expression"); 9253 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 9254 9255 return EvalResult.Val.getInt(); 9256 } 9257 9258 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 9259 bool IsConst; 9260 EvalResult EvalResult; 9261 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) { 9262 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow); 9263 (void)::EvaluateAsRValue(Info, this, EvalResult.Val); 9264 } 9265 } 9266 9267 bool Expr::EvalResult::isGlobalLValue() const { 9268 assert(Val.isLValue()); 9269 return IsGlobalLValue(Val.getLValueBase()); 9270 } 9271 9272 9273 /// isIntegerConstantExpr - this recursive routine will test if an expression is 9274 /// an integer constant expression. 9275 9276 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 9277 /// comma, etc 9278 9279 // CheckICE - This function does the fundamental ICE checking: the returned 9280 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 9281 // and a (possibly null) SourceLocation indicating the location of the problem. 9282 // 9283 // Note that to reduce code duplication, this helper does no evaluation 9284 // itself; the caller checks whether the expression is evaluatable, and 9285 // in the rare cases where CheckICE actually cares about the evaluated 9286 // value, it calls into Evalute. 9287 9288 namespace { 9289 9290 enum ICEKind { 9291 /// This expression is an ICE. 9292 IK_ICE, 9293 /// This expression is not an ICE, but if it isn't evaluated, it's 9294 /// a legal subexpression for an ICE. This return value is used to handle 9295 /// the comma operator in C99 mode, and non-constant subexpressions. 9296 IK_ICEIfUnevaluated, 9297 /// This expression is not an ICE, and is not a legal subexpression for one. 9298 IK_NotICE 9299 }; 9300 9301 struct ICEDiag { 9302 ICEKind Kind; 9303 SourceLocation Loc; 9304 9305 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 9306 }; 9307 9308 } 9309 9310 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 9311 9312 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 9313 9314 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 9315 Expr::EvalResult EVResult; 9316 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects || 9317 !EVResult.Val.isInt()) 9318 return ICEDiag(IK_NotICE, E->getLocStart()); 9319 9320 return NoDiag(); 9321 } 9322 9323 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 9324 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 9325 if (!E->getType()->isIntegralOrEnumerationType()) 9326 return ICEDiag(IK_NotICE, E->getLocStart()); 9327 9328 switch (E->getStmtClass()) { 9329 #define ABSTRACT_STMT(Node) 9330 #define STMT(Node, Base) case Expr::Node##Class: 9331 #define EXPR(Node, Base) 9332 #include "clang/AST/StmtNodes.inc" 9333 case Expr::PredefinedExprClass: 9334 case Expr::FloatingLiteralClass: 9335 case Expr::ImaginaryLiteralClass: 9336 case Expr::StringLiteralClass: 9337 case Expr::ArraySubscriptExprClass: 9338 case Expr::OMPArraySectionExprClass: 9339 case Expr::MemberExprClass: 9340 case Expr::CompoundAssignOperatorClass: 9341 case Expr::CompoundLiteralExprClass: 9342 case Expr::ExtVectorElementExprClass: 9343 case Expr::DesignatedInitExprClass: 9344 case Expr::NoInitExprClass: 9345 case Expr::DesignatedInitUpdateExprClass: 9346 case Expr::ImplicitValueInitExprClass: 9347 case Expr::ParenListExprClass: 9348 case Expr::VAArgExprClass: 9349 case Expr::AddrLabelExprClass: 9350 case Expr::StmtExprClass: 9351 case Expr::CXXMemberCallExprClass: 9352 case Expr::CUDAKernelCallExprClass: 9353 case Expr::CXXDynamicCastExprClass: 9354 case Expr::CXXTypeidExprClass: 9355 case Expr::CXXUuidofExprClass: 9356 case Expr::MSPropertyRefExprClass: 9357 case Expr::MSPropertySubscriptExprClass: 9358 case Expr::CXXNullPtrLiteralExprClass: 9359 case Expr::UserDefinedLiteralClass: 9360 case Expr::CXXThisExprClass: 9361 case Expr::CXXThrowExprClass: 9362 case Expr::CXXNewExprClass: 9363 case Expr::CXXDeleteExprClass: 9364 case Expr::CXXPseudoDestructorExprClass: 9365 case Expr::UnresolvedLookupExprClass: 9366 case Expr::TypoExprClass: 9367 case Expr::DependentScopeDeclRefExprClass: 9368 case Expr::CXXConstructExprClass: 9369 case Expr::CXXInheritedCtorInitExprClass: 9370 case Expr::CXXStdInitializerListExprClass: 9371 case Expr::CXXBindTemporaryExprClass: 9372 case Expr::ExprWithCleanupsClass: 9373 case Expr::CXXTemporaryObjectExprClass: 9374 case Expr::CXXUnresolvedConstructExprClass: 9375 case Expr::CXXDependentScopeMemberExprClass: 9376 case Expr::UnresolvedMemberExprClass: 9377 case Expr::ObjCStringLiteralClass: 9378 case Expr::ObjCBoxedExprClass: 9379 case Expr::ObjCArrayLiteralClass: 9380 case Expr::ObjCDictionaryLiteralClass: 9381 case Expr::ObjCEncodeExprClass: 9382 case Expr::ObjCMessageExprClass: 9383 case Expr::ObjCSelectorExprClass: 9384 case Expr::ObjCProtocolExprClass: 9385 case Expr::ObjCIvarRefExprClass: 9386 case Expr::ObjCPropertyRefExprClass: 9387 case Expr::ObjCSubscriptRefExprClass: 9388 case Expr::ObjCIsaExprClass: 9389 case Expr::ObjCAvailabilityCheckExprClass: 9390 case Expr::ShuffleVectorExprClass: 9391 case Expr::ConvertVectorExprClass: 9392 case Expr::BlockExprClass: 9393 case Expr::NoStmtClass: 9394 case Expr::OpaqueValueExprClass: 9395 case Expr::PackExpansionExprClass: 9396 case Expr::SubstNonTypeTemplateParmPackExprClass: 9397 case Expr::FunctionParmPackExprClass: 9398 case Expr::AsTypeExprClass: 9399 case Expr::ObjCIndirectCopyRestoreExprClass: 9400 case Expr::MaterializeTemporaryExprClass: 9401 case Expr::PseudoObjectExprClass: 9402 case Expr::AtomicExprClass: 9403 case Expr::LambdaExprClass: 9404 case Expr::CXXFoldExprClass: 9405 case Expr::CoawaitExprClass: 9406 case Expr::CoyieldExprClass: 9407 return ICEDiag(IK_NotICE, E->getLocStart()); 9408 9409 case Expr::InitListExprClass: { 9410 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 9411 // form "T x = { a };" is equivalent to "T x = a;". 9412 // Unless we're initializing a reference, T is a scalar as it is known to be 9413 // of integral or enumeration type. 9414 if (E->isRValue()) 9415 if (cast<InitListExpr>(E)->getNumInits() == 1) 9416 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 9417 return ICEDiag(IK_NotICE, E->getLocStart()); 9418 } 9419 9420 case Expr::SizeOfPackExprClass: 9421 case Expr::GNUNullExprClass: 9422 // GCC considers the GNU __null value to be an integral constant expression. 9423 return NoDiag(); 9424 9425 case Expr::SubstNonTypeTemplateParmExprClass: 9426 return 9427 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 9428 9429 case Expr::ParenExprClass: 9430 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 9431 case Expr::GenericSelectionExprClass: 9432 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 9433 case Expr::IntegerLiteralClass: 9434 case Expr::CharacterLiteralClass: 9435 case Expr::ObjCBoolLiteralExprClass: 9436 case Expr::CXXBoolLiteralExprClass: 9437 case Expr::CXXScalarValueInitExprClass: 9438 case Expr::TypeTraitExprClass: 9439 case Expr::ArrayTypeTraitExprClass: 9440 case Expr::ExpressionTraitExprClass: 9441 case Expr::CXXNoexceptExprClass: 9442 return NoDiag(); 9443 case Expr::CallExprClass: 9444 case Expr::CXXOperatorCallExprClass: { 9445 // C99 6.6/3 allows function calls within unevaluated subexpressions of 9446 // constant expressions, but they can never be ICEs because an ICE cannot 9447 // contain an operand of (pointer to) function type. 9448 const CallExpr *CE = cast<CallExpr>(E); 9449 if (CE->getBuiltinCallee()) 9450 return CheckEvalInICE(E, Ctx); 9451 return ICEDiag(IK_NotICE, E->getLocStart()); 9452 } 9453 case Expr::DeclRefExprClass: { 9454 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 9455 return NoDiag(); 9456 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl()); 9457 if (Ctx.getLangOpts().CPlusPlus && 9458 D && IsConstNonVolatile(D->getType())) { 9459 // Parameter variables are never constants. Without this check, 9460 // getAnyInitializer() can find a default argument, which leads 9461 // to chaos. 9462 if (isa<ParmVarDecl>(D)) 9463 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 9464 9465 // C++ 7.1.5.1p2 9466 // A variable of non-volatile const-qualified integral or enumeration 9467 // type initialized by an ICE can be used in ICEs. 9468 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 9469 if (!Dcl->getType()->isIntegralOrEnumerationType()) 9470 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 9471 9472 const VarDecl *VD; 9473 // Look for a declaration of this variable that has an initializer, and 9474 // check whether it is an ICE. 9475 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 9476 return NoDiag(); 9477 else 9478 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 9479 } 9480 } 9481 return ICEDiag(IK_NotICE, E->getLocStart()); 9482 } 9483 case Expr::UnaryOperatorClass: { 9484 const UnaryOperator *Exp = cast<UnaryOperator>(E); 9485 switch (Exp->getOpcode()) { 9486 case UO_PostInc: 9487 case UO_PostDec: 9488 case UO_PreInc: 9489 case UO_PreDec: 9490 case UO_AddrOf: 9491 case UO_Deref: 9492 case UO_Coawait: 9493 // C99 6.6/3 allows increment and decrement within unevaluated 9494 // subexpressions of constant expressions, but they can never be ICEs 9495 // because an ICE cannot contain an lvalue operand. 9496 return ICEDiag(IK_NotICE, E->getLocStart()); 9497 case UO_Extension: 9498 case UO_LNot: 9499 case UO_Plus: 9500 case UO_Minus: 9501 case UO_Not: 9502 case UO_Real: 9503 case UO_Imag: 9504 return CheckICE(Exp->getSubExpr(), Ctx); 9505 } 9506 9507 // OffsetOf falls through here. 9508 } 9509 case Expr::OffsetOfExprClass: { 9510 // Note that per C99, offsetof must be an ICE. And AFAIK, using 9511 // EvaluateAsRValue matches the proposed gcc behavior for cases like 9512 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 9513 // compliance: we should warn earlier for offsetof expressions with 9514 // array subscripts that aren't ICEs, and if the array subscripts 9515 // are ICEs, the value of the offsetof must be an integer constant. 9516 return CheckEvalInICE(E, Ctx); 9517 } 9518 case Expr::UnaryExprOrTypeTraitExprClass: { 9519 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 9520 if ((Exp->getKind() == UETT_SizeOf) && 9521 Exp->getTypeOfArgument()->isVariableArrayType()) 9522 return ICEDiag(IK_NotICE, E->getLocStart()); 9523 return NoDiag(); 9524 } 9525 case Expr::BinaryOperatorClass: { 9526 const BinaryOperator *Exp = cast<BinaryOperator>(E); 9527 switch (Exp->getOpcode()) { 9528 case BO_PtrMemD: 9529 case BO_PtrMemI: 9530 case BO_Assign: 9531 case BO_MulAssign: 9532 case BO_DivAssign: 9533 case BO_RemAssign: 9534 case BO_AddAssign: 9535 case BO_SubAssign: 9536 case BO_ShlAssign: 9537 case BO_ShrAssign: 9538 case BO_AndAssign: 9539 case BO_XorAssign: 9540 case BO_OrAssign: 9541 // C99 6.6/3 allows assignments within unevaluated subexpressions of 9542 // constant expressions, but they can never be ICEs because an ICE cannot 9543 // contain an lvalue operand. 9544 return ICEDiag(IK_NotICE, E->getLocStart()); 9545 9546 case BO_Mul: 9547 case BO_Div: 9548 case BO_Rem: 9549 case BO_Add: 9550 case BO_Sub: 9551 case BO_Shl: 9552 case BO_Shr: 9553 case BO_LT: 9554 case BO_GT: 9555 case BO_LE: 9556 case BO_GE: 9557 case BO_EQ: 9558 case BO_NE: 9559 case BO_And: 9560 case BO_Xor: 9561 case BO_Or: 9562 case BO_Comma: { 9563 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 9564 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 9565 if (Exp->getOpcode() == BO_Div || 9566 Exp->getOpcode() == BO_Rem) { 9567 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 9568 // we don't evaluate one. 9569 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 9570 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 9571 if (REval == 0) 9572 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 9573 if (REval.isSigned() && REval.isAllOnesValue()) { 9574 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 9575 if (LEval.isMinSignedValue()) 9576 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 9577 } 9578 } 9579 } 9580 if (Exp->getOpcode() == BO_Comma) { 9581 if (Ctx.getLangOpts().C99) { 9582 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 9583 // if it isn't evaluated. 9584 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 9585 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 9586 } else { 9587 // In both C89 and C++, commas in ICEs are illegal. 9588 return ICEDiag(IK_NotICE, E->getLocStart()); 9589 } 9590 } 9591 return Worst(LHSResult, RHSResult); 9592 } 9593 case BO_LAnd: 9594 case BO_LOr: { 9595 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 9596 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 9597 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 9598 // Rare case where the RHS has a comma "side-effect"; we need 9599 // to actually check the condition to see whether the side 9600 // with the comma is evaluated. 9601 if ((Exp->getOpcode() == BO_LAnd) != 9602 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 9603 return RHSResult; 9604 return NoDiag(); 9605 } 9606 9607 return Worst(LHSResult, RHSResult); 9608 } 9609 } 9610 } 9611 case Expr::ImplicitCastExprClass: 9612 case Expr::CStyleCastExprClass: 9613 case Expr::CXXFunctionalCastExprClass: 9614 case Expr::CXXStaticCastExprClass: 9615 case Expr::CXXReinterpretCastExprClass: 9616 case Expr::CXXConstCastExprClass: 9617 case Expr::ObjCBridgedCastExprClass: { 9618 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 9619 if (isa<ExplicitCastExpr>(E)) { 9620 if (const FloatingLiteral *FL 9621 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 9622 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 9623 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 9624 APSInt IgnoredVal(DestWidth, !DestSigned); 9625 bool Ignored; 9626 // If the value does not fit in the destination type, the behavior is 9627 // undefined, so we are not required to treat it as a constant 9628 // expression. 9629 if (FL->getValue().convertToInteger(IgnoredVal, 9630 llvm::APFloat::rmTowardZero, 9631 &Ignored) & APFloat::opInvalidOp) 9632 return ICEDiag(IK_NotICE, E->getLocStart()); 9633 return NoDiag(); 9634 } 9635 } 9636 switch (cast<CastExpr>(E)->getCastKind()) { 9637 case CK_LValueToRValue: 9638 case CK_AtomicToNonAtomic: 9639 case CK_NonAtomicToAtomic: 9640 case CK_NoOp: 9641 case CK_IntegralToBoolean: 9642 case CK_IntegralCast: 9643 return CheckICE(SubExpr, Ctx); 9644 default: 9645 return ICEDiag(IK_NotICE, E->getLocStart()); 9646 } 9647 } 9648 case Expr::BinaryConditionalOperatorClass: { 9649 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 9650 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 9651 if (CommonResult.Kind == IK_NotICE) return CommonResult; 9652 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 9653 if (FalseResult.Kind == IK_NotICE) return FalseResult; 9654 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 9655 if (FalseResult.Kind == IK_ICEIfUnevaluated && 9656 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 9657 return FalseResult; 9658 } 9659 case Expr::ConditionalOperatorClass: { 9660 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 9661 // If the condition (ignoring parens) is a __builtin_constant_p call, 9662 // then only the true side is actually considered in an integer constant 9663 // expression, and it is fully evaluated. This is an important GNU 9664 // extension. See GCC PR38377 for discussion. 9665 if (const CallExpr *CallCE 9666 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 9667 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 9668 return CheckEvalInICE(E, Ctx); 9669 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 9670 if (CondResult.Kind == IK_NotICE) 9671 return CondResult; 9672 9673 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 9674 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 9675 9676 if (TrueResult.Kind == IK_NotICE) 9677 return TrueResult; 9678 if (FalseResult.Kind == IK_NotICE) 9679 return FalseResult; 9680 if (CondResult.Kind == IK_ICEIfUnevaluated) 9681 return CondResult; 9682 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 9683 return NoDiag(); 9684 // Rare case where the diagnostics depend on which side is evaluated 9685 // Note that if we get here, CondResult is 0, and at least one of 9686 // TrueResult and FalseResult is non-zero. 9687 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 9688 return FalseResult; 9689 return TrueResult; 9690 } 9691 case Expr::CXXDefaultArgExprClass: 9692 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 9693 case Expr::CXXDefaultInitExprClass: 9694 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 9695 case Expr::ChooseExprClass: { 9696 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 9697 } 9698 } 9699 9700 llvm_unreachable("Invalid StmtClass!"); 9701 } 9702 9703 /// Evaluate an expression as a C++11 integral constant expression. 9704 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 9705 const Expr *E, 9706 llvm::APSInt *Value, 9707 SourceLocation *Loc) { 9708 if (!E->getType()->isIntegralOrEnumerationType()) { 9709 if (Loc) *Loc = E->getExprLoc(); 9710 return false; 9711 } 9712 9713 APValue Result; 9714 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 9715 return false; 9716 9717 if (!Result.isInt()) { 9718 if (Loc) *Loc = E->getExprLoc(); 9719 return false; 9720 } 9721 9722 if (Value) *Value = Result.getInt(); 9723 return true; 9724 } 9725 9726 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 9727 SourceLocation *Loc) const { 9728 if (Ctx.getLangOpts().CPlusPlus11) 9729 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 9730 9731 ICEDiag D = CheckICE(this, Ctx); 9732 if (D.Kind != IK_ICE) { 9733 if (Loc) *Loc = D.Loc; 9734 return false; 9735 } 9736 return true; 9737 } 9738 9739 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 9740 SourceLocation *Loc, bool isEvaluated) const { 9741 if (Ctx.getLangOpts().CPlusPlus11) 9742 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 9743 9744 if (!isIntegerConstantExpr(Ctx, Loc)) 9745 return false; 9746 // The only possible side-effects here are due to UB discovered in the 9747 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 9748 // required to treat the expression as an ICE, so we produce the folded 9749 // value. 9750 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects)) 9751 llvm_unreachable("ICE cannot be evaluated!"); 9752 return true; 9753 } 9754 9755 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 9756 return CheckICE(this, Ctx).Kind == IK_ICE; 9757 } 9758 9759 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 9760 SourceLocation *Loc) const { 9761 // We support this checking in C++98 mode in order to diagnose compatibility 9762 // issues. 9763 assert(Ctx.getLangOpts().CPlusPlus); 9764 9765 // Build evaluation settings. 9766 Expr::EvalStatus Status; 9767 SmallVector<PartialDiagnosticAt, 8> Diags; 9768 Status.Diag = &Diags; 9769 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 9770 9771 APValue Scratch; 9772 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 9773 9774 if (!Diags.empty()) { 9775 IsConstExpr = false; 9776 if (Loc) *Loc = Diags[0].first; 9777 } else if (!IsConstExpr) { 9778 // FIXME: This shouldn't happen. 9779 if (Loc) *Loc = getExprLoc(); 9780 } 9781 9782 return IsConstExpr; 9783 } 9784 9785 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 9786 const FunctionDecl *Callee, 9787 ArrayRef<const Expr*> Args) const { 9788 Expr::EvalStatus Status; 9789 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 9790 9791 ArgVector ArgValues(Args.size()); 9792 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 9793 I != E; ++I) { 9794 if ((*I)->isValueDependent() || 9795 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 9796 // If evaluation fails, throw away the argument entirely. 9797 ArgValues[I - Args.begin()] = APValue(); 9798 if (Info.EvalStatus.HasSideEffects) 9799 return false; 9800 } 9801 9802 // Build fake call to Callee. 9803 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr, 9804 ArgValues.data()); 9805 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 9806 } 9807 9808 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 9809 SmallVectorImpl< 9810 PartialDiagnosticAt> &Diags) { 9811 // FIXME: It would be useful to check constexpr function templates, but at the 9812 // moment the constant expression evaluator cannot cope with the non-rigorous 9813 // ASTs which we build for dependent expressions. 9814 if (FD->isDependentContext()) 9815 return true; 9816 9817 Expr::EvalStatus Status; 9818 Status.Diag = &Diags; 9819 9820 EvalInfo Info(FD->getASTContext(), Status, 9821 EvalInfo::EM_PotentialConstantExpression); 9822 9823 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 9824 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 9825 9826 // Fabricate an arbitrary expression on the stack and pretend that it 9827 // is a temporary being used as the 'this' pointer. 9828 LValue This; 9829 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 9830 This.set(&VIE, Info.CurrentCall->Index); 9831 9832 ArrayRef<const Expr*> Args; 9833 9834 APValue Scratch; 9835 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 9836 // Evaluate the call as a constant initializer, to allow the construction 9837 // of objects of non-literal types. 9838 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 9839 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 9840 } else { 9841 SourceLocation Loc = FD->getLocation(); 9842 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 9843 Args, FD->getBody(), Info, Scratch, nullptr); 9844 } 9845 9846 return Diags.empty(); 9847 } 9848 9849 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 9850 const FunctionDecl *FD, 9851 SmallVectorImpl< 9852 PartialDiagnosticAt> &Diags) { 9853 Expr::EvalStatus Status; 9854 Status.Diag = &Diags; 9855 9856 EvalInfo Info(FD->getASTContext(), Status, 9857 EvalInfo::EM_PotentialConstantExpressionUnevaluated); 9858 9859 // Fabricate a call stack frame to give the arguments a plausible cover story. 9860 ArrayRef<const Expr*> Args; 9861 ArgVector ArgValues(0); 9862 bool Success = EvaluateArgs(Args, ArgValues, Info); 9863 (void)Success; 9864 assert(Success && 9865 "Failed to set up arguments for potential constant evaluation"); 9866 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 9867 9868 APValue ResultScratch; 9869 Evaluate(ResultScratch, Info, E); 9870 return Diags.empty(); 9871 } 9872 9873 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 9874 unsigned Type) const { 9875 if (!getType()->isPointerType()) 9876 return false; 9877 9878 Expr::EvalStatus Status; 9879 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 9880 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 9881 } 9882