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