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