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