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