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