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