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