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