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