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