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