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