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