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