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