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