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