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 / C++1y rules only, at the moment), or, if folding failed 27 // too, why the expression could not be folded. 28 // 29 // If we are checking for a potential constant expression, failure to constant 30 // fold a potential constant sub-expression will be indicated by a 'false' 31 // return value (the expression could not be folded) and no diagnostic (the 32 // expression is not necessarily non-constant). 33 // 34 //===----------------------------------------------------------------------===// 35 36 #include "clang/AST/APValue.h" 37 #include "clang/AST/ASTContext.h" 38 #include "clang/AST/ASTDiagnostic.h" 39 #include "clang/AST/ASTLambda.h" 40 #include "clang/AST/CharUnits.h" 41 #include "clang/AST/Expr.h" 42 #include "clang/AST/RecordLayout.h" 43 #include "clang/AST/StmtVisitor.h" 44 #include "clang/AST/TypeLoc.h" 45 #include "clang/Basic/Builtins.h" 46 #include "clang/Basic/TargetInfo.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using llvm::APSInt; 53 using llvm::APFloat; 54 55 static bool IsGlobalLValue(APValue::LValueBase B); 56 57 namespace { 58 struct LValue; 59 struct CallStackFrame; 60 struct EvalInfo; 61 62 static QualType getType(APValue::LValueBase B) { 63 if (!B) return QualType(); 64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 65 // FIXME: It's unclear where we're supposed to take the type from, and 66 // this actually matters for arrays of unknown bound. Eg: 67 // 68 // extern int arr[]; void f() { extern int arr[3]; }; 69 // constexpr int *p = &arr[1]; // valid? 70 // 71 // For now, we take the array bound from the most recent declaration. 72 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 73 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 74 QualType T = Redecl->getType(); 75 if (!T->isIncompleteArrayType()) 76 return T; 77 } 78 return D->getType(); 79 } 80 81 const Expr *Base = B.get<const Expr*>(); 82 83 // For a materialized temporary, the type of the temporary we materialized 84 // may not be the type of the expression. 85 if (const MaterializeTemporaryExpr *MTE = 86 dyn_cast<MaterializeTemporaryExpr>(Base)) { 87 SmallVector<const Expr *, 2> CommaLHSs; 88 SmallVector<SubobjectAdjustment, 2> Adjustments; 89 const Expr *Temp = MTE->GetTemporaryExpr(); 90 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 91 Adjustments); 92 // Keep any cv-qualifiers from the reference if we generated a temporary 93 // for it directly. Otherwise use the type after adjustment. 94 if (!Adjustments.empty()) 95 return Inner->getType(); 96 } 97 98 return Base->getType(); 99 } 100 101 /// Get an LValue path entry, which is known to not be an array index, as a 102 /// field or base class. 103 static 104 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) { 105 APValue::BaseOrMemberType Value; 106 Value.setFromOpaqueValue(E.BaseOrMember); 107 return Value; 108 } 109 110 /// Get an LValue path entry, which is known to not be an array index, as a 111 /// field declaration. 112 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 113 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer()); 114 } 115 /// Get an LValue path entry, which is known to not be an array index, as a 116 /// base class declaration. 117 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 118 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer()); 119 } 120 /// Determine whether this LValue path entry for a base class names a virtual 121 /// base class. 122 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 123 return getAsBaseOrMember(E).getInt(); 124 } 125 126 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 127 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 128 const FunctionDecl *Callee = CE->getDirectCallee(); 129 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 130 } 131 132 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 133 /// This will look through a single cast. 134 /// 135 /// Returns null if we couldn't unwrap a function with alloc_size. 136 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 137 if (!E->getType()->isPointerType()) 138 return nullptr; 139 140 E = E->IgnoreParens(); 141 // If we're doing a variable assignment from e.g. malloc(N), there will 142 // probably be a cast of some kind. Ignore it. 143 if (const auto *Cast = dyn_cast<CastExpr>(E)) 144 E = Cast->getSubExpr()->IgnoreParens(); 145 146 if (const auto *CE = dyn_cast<CallExpr>(E)) 147 return getAllocSizeAttr(CE) ? CE : nullptr; 148 return nullptr; 149 } 150 151 /// Determines whether or not the given Base contains a call to a function 152 /// with the alloc_size attribute. 153 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 154 const auto *E = Base.dyn_cast<const Expr *>(); 155 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 156 } 157 158 /// The bound to claim that an array of unknown bound has. 159 /// The value in MostDerivedArraySize is undefined in this case. So, set it 160 /// to an arbitrary value that's likely to loudly break things if it's used. 161 static const uint64_t AssumedSizeForUnsizedArray = 162 std::numeric_limits<uint64_t>::max() / 2; 163 164 /// Determines if an LValue with the given LValueBase will have an unsized 165 /// array in its designator. 166 /// Find the path length and type of the most-derived subobject in the given 167 /// path, and find the size of the containing array, if any. 168 static unsigned 169 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 170 ArrayRef<APValue::LValuePathEntry> Path, 171 uint64_t &ArraySize, QualType &Type, bool &IsArray, 172 bool &FirstEntryIsUnsizedArray) { 173 // This only accepts LValueBases from APValues, and APValues don't support 174 // arrays that lack size info. 175 assert(!isBaseAnAllocSizeCall(Base) && 176 "Unsized arrays shouldn't appear here"); 177 unsigned MostDerivedLength = 0; 178 Type = getType(Base); 179 180 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 181 if (Type->isArrayType()) { 182 const ArrayType *AT = Ctx.getAsArrayType(Type); 183 Type = AT->getElementType(); 184 MostDerivedLength = I + 1; 185 IsArray = true; 186 187 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 188 ArraySize = CAT->getSize().getZExtValue(); 189 } else { 190 assert(I == 0 && "unexpected unsized array designator"); 191 FirstEntryIsUnsizedArray = true; 192 ArraySize = AssumedSizeForUnsizedArray; 193 } 194 } else if (Type->isAnyComplexType()) { 195 const ComplexType *CT = Type->castAs<ComplexType>(); 196 Type = CT->getElementType(); 197 ArraySize = 2; 198 MostDerivedLength = I + 1; 199 IsArray = true; 200 } else if (const FieldDecl *FD = getAsField(Path[I])) { 201 Type = FD->getType(); 202 ArraySize = 0; 203 MostDerivedLength = I + 1; 204 IsArray = false; 205 } else { 206 // Path[I] describes a base class. 207 ArraySize = 0; 208 IsArray = false; 209 } 210 } 211 return MostDerivedLength; 212 } 213 214 // The order of this enum is important for diagnostics. 215 enum CheckSubobjectKind { 216 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 217 CSK_This, CSK_Real, CSK_Imag 218 }; 219 220 /// A path from a glvalue to a subobject of that glvalue. 221 struct SubobjectDesignator { 222 /// True if the subobject was named in a manner not supported by C++11. Such 223 /// lvalues can still be folded, but they are not core constant expressions 224 /// and we cannot perform lvalue-to-rvalue conversions on them. 225 unsigned Invalid : 1; 226 227 /// Is this a pointer one past the end of an object? 228 unsigned IsOnePastTheEnd : 1; 229 230 /// Indicator of whether the first entry is an unsized array. 231 unsigned FirstEntryIsAnUnsizedArray : 1; 232 233 /// Indicator of whether the most-derived object is an array element. 234 unsigned MostDerivedIsArrayElement : 1; 235 236 /// The length of the path to the most-derived object of which this is a 237 /// subobject. 238 unsigned MostDerivedPathLength : 28; 239 240 /// The size of the array of which the most-derived object is an element. 241 /// This will always be 0 if the most-derived object is not an array 242 /// element. 0 is not an indicator of whether or not the most-derived object 243 /// is an array, however, because 0-length arrays are allowed. 244 /// 245 /// If the current array is an unsized array, the value of this is 246 /// undefined. 247 uint64_t MostDerivedArraySize; 248 249 /// The type of the most derived object referred to by this address. 250 QualType MostDerivedType; 251 252 typedef APValue::LValuePathEntry PathEntry; 253 254 /// The entries on the path from the glvalue to the designated subobject. 255 SmallVector<PathEntry, 8> Entries; 256 257 SubobjectDesignator() : Invalid(true) {} 258 259 explicit SubobjectDesignator(QualType T) 260 : Invalid(false), IsOnePastTheEnd(false), 261 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 262 MostDerivedPathLength(0), MostDerivedArraySize(0), 263 MostDerivedType(T) {} 264 265 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 266 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 267 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 268 MostDerivedPathLength(0), MostDerivedArraySize(0) { 269 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 270 if (!Invalid) { 271 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 272 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 273 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 274 if (V.getLValueBase()) { 275 bool IsArray = false; 276 bool FirstIsUnsizedArray = false; 277 MostDerivedPathLength = findMostDerivedSubobject( 278 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 279 MostDerivedType, IsArray, FirstIsUnsizedArray); 280 MostDerivedIsArrayElement = IsArray; 281 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 282 } 283 } 284 } 285 286 void setInvalid() { 287 Invalid = true; 288 Entries.clear(); 289 } 290 291 /// Determine whether the most derived subobject is an array without a 292 /// known bound. 293 bool isMostDerivedAnUnsizedArray() const { 294 assert(!Invalid && "Calling this makes no sense on invalid designators"); 295 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 296 } 297 298 /// Determine what the most derived array's size is. Results in an assertion 299 /// failure if the most derived array lacks a size. 300 uint64_t getMostDerivedArraySize() const { 301 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 302 return MostDerivedArraySize; 303 } 304 305 /// Determine whether this is a one-past-the-end pointer. 306 bool isOnePastTheEnd() const { 307 assert(!Invalid); 308 if (IsOnePastTheEnd) 309 return true; 310 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 311 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize) 312 return true; 313 return false; 314 } 315 316 /// Check that this refers to a valid subobject. 317 bool isValidSubobject() const { 318 if (Invalid) 319 return false; 320 return !isOnePastTheEnd(); 321 } 322 /// Check that this refers to a valid subobject, and if not, produce a 323 /// relevant diagnostic and set the designator as invalid. 324 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 325 326 /// Update this designator to refer to the first element within this array. 327 void addArrayUnchecked(const ConstantArrayType *CAT) { 328 PathEntry Entry; 329 Entry.ArrayIndex = 0; 330 Entries.push_back(Entry); 331 332 // This is a most-derived object. 333 MostDerivedType = CAT->getElementType(); 334 MostDerivedIsArrayElement = true; 335 MostDerivedArraySize = CAT->getSize().getZExtValue(); 336 MostDerivedPathLength = Entries.size(); 337 } 338 /// Update this designator to refer to the first element within the array of 339 /// elements of type T. This is an array of unknown size. 340 void addUnsizedArrayUnchecked(QualType ElemTy) { 341 PathEntry Entry; 342 Entry.ArrayIndex = 0; 343 Entries.push_back(Entry); 344 345 MostDerivedType = ElemTy; 346 MostDerivedIsArrayElement = true; 347 // The value in MostDerivedArraySize is undefined in this case. So, set it 348 // to an arbitrary value that's likely to loudly break things if it's 349 // used. 350 MostDerivedArraySize = AssumedSizeForUnsizedArray; 351 MostDerivedPathLength = Entries.size(); 352 } 353 /// Update this designator to refer to the given base or member of this 354 /// object. 355 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 356 PathEntry Entry; 357 APValue::BaseOrMemberType Value(D, Virtual); 358 Entry.BaseOrMember = Value.getOpaqueValue(); 359 Entries.push_back(Entry); 360 361 // If this isn't a base class, it's a new most-derived object. 362 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 363 MostDerivedType = FD->getType(); 364 MostDerivedIsArrayElement = false; 365 MostDerivedArraySize = 0; 366 MostDerivedPathLength = Entries.size(); 367 } 368 } 369 /// Update this designator to refer to the given complex component. 370 void addComplexUnchecked(QualType EltTy, bool Imag) { 371 PathEntry Entry; 372 Entry.ArrayIndex = Imag; 373 Entries.push_back(Entry); 374 375 // This is technically a most-derived object, though in practice this 376 // is unlikely to matter. 377 MostDerivedType = EltTy; 378 MostDerivedIsArrayElement = true; 379 MostDerivedArraySize = 2; 380 MostDerivedPathLength = Entries.size(); 381 } 382 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 383 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 384 const APSInt &N); 385 /// Add N to the address of this subobject. 386 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 387 if (Invalid || !N) return; 388 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 389 if (isMostDerivedAnUnsizedArray()) { 390 diagnoseUnsizedArrayPointerArithmetic(Info, E); 391 // Can't verify -- trust that the user is doing the right thing (or if 392 // not, trust that the caller will catch the bad behavior). 393 // FIXME: Should we reject if this overflows, at least? 394 Entries.back().ArrayIndex += TruncatedN; 395 return; 396 } 397 398 // [expr.add]p4: For the purposes of these operators, a pointer to a 399 // nonarray object behaves the same as a pointer to the first element of 400 // an array of length one with the type of the object as its element type. 401 bool IsArray = MostDerivedPathLength == Entries.size() && 402 MostDerivedIsArrayElement; 403 uint64_t ArrayIndex = 404 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; 405 uint64_t ArraySize = 406 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 407 408 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 409 // Calculate the actual index in a wide enough type, so we can include 410 // it in the note. 411 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 412 (llvm::APInt&)N += ArrayIndex; 413 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 414 diagnosePointerArithmetic(Info, E, N); 415 setInvalid(); 416 return; 417 } 418 419 ArrayIndex += TruncatedN; 420 assert(ArrayIndex <= ArraySize && 421 "bounds check succeeded for out-of-bounds index"); 422 423 if (IsArray) 424 Entries.back().ArrayIndex = ArrayIndex; 425 else 426 IsOnePastTheEnd = (ArrayIndex != 0); 427 } 428 }; 429 430 /// A stack frame in the constexpr call stack. 431 struct CallStackFrame { 432 EvalInfo &Info; 433 434 /// Parent - The caller of this stack frame. 435 CallStackFrame *Caller; 436 437 /// Callee - The function which was called. 438 const FunctionDecl *Callee; 439 440 /// This - The binding for the this pointer in this call, if any. 441 const LValue *This; 442 443 /// Arguments - Parameter bindings for this function call, indexed by 444 /// parameters' function scope indices. 445 APValue *Arguments; 446 447 // Note that we intentionally use std::map here so that references to 448 // values are stable. 449 typedef std::map<const void*, APValue> MapTy; 450 typedef MapTy::const_iterator temp_iterator; 451 /// Temporaries - Temporary lvalues materialized within this stack frame. 452 MapTy Temporaries; 453 454 /// CallLoc - The location of the call expression for this call. 455 SourceLocation CallLoc; 456 457 /// Index - The call index of this call. 458 unsigned Index; 459 460 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 461 // on the overall stack usage of deeply-recursing constexpr evaluataions. 462 // (We should cache this map rather than recomputing it repeatedly.) 463 // But let's try this and see how it goes; we can look into caching the map 464 // as a later change. 465 466 /// LambdaCaptureFields - Mapping from captured variables/this to 467 /// corresponding data members in the closure class. 468 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 469 FieldDecl *LambdaThisCaptureField; 470 471 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 472 const FunctionDecl *Callee, const LValue *This, 473 APValue *Arguments); 474 ~CallStackFrame(); 475 476 APValue *getTemporary(const void *Key) { 477 MapTy::iterator I = Temporaries.find(Key); 478 return I == Temporaries.end() ? nullptr : &I->second; 479 } 480 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 481 }; 482 483 /// Temporarily override 'this'. 484 class ThisOverrideRAII { 485 public: 486 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 487 : Frame(Frame), OldThis(Frame.This) { 488 if (Enable) 489 Frame.This = NewThis; 490 } 491 ~ThisOverrideRAII() { 492 Frame.This = OldThis; 493 } 494 private: 495 CallStackFrame &Frame; 496 const LValue *OldThis; 497 }; 498 499 /// A partial diagnostic which we might know in advance that we are not going 500 /// to emit. 501 class OptionalDiagnostic { 502 PartialDiagnostic *Diag; 503 504 public: 505 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr) 506 : Diag(Diag) {} 507 508 template<typename T> 509 OptionalDiagnostic &operator<<(const T &v) { 510 if (Diag) 511 *Diag << v; 512 return *this; 513 } 514 515 OptionalDiagnostic &operator<<(const APSInt &I) { 516 if (Diag) { 517 SmallVector<char, 32> Buffer; 518 I.toString(Buffer); 519 *Diag << StringRef(Buffer.data(), Buffer.size()); 520 } 521 return *this; 522 } 523 524 OptionalDiagnostic &operator<<(const APFloat &F) { 525 if (Diag) { 526 // FIXME: Force the precision of the source value down so we don't 527 // print digits which are usually useless (we don't really care here if 528 // we truncate a digit by accident in edge cases). Ideally, 529 // APFloat::toString would automatically print the shortest 530 // representation which rounds to the correct value, but it's a bit 531 // tricky to implement. 532 unsigned precision = 533 llvm::APFloat::semanticsPrecision(F.getSemantics()); 534 precision = (precision * 59 + 195) / 196; 535 SmallVector<char, 32> Buffer; 536 F.toString(Buffer, precision); 537 *Diag << StringRef(Buffer.data(), Buffer.size()); 538 } 539 return *this; 540 } 541 }; 542 543 /// A cleanup, and a flag indicating whether it is lifetime-extended. 544 class Cleanup { 545 llvm::PointerIntPair<APValue*, 1, bool> Value; 546 547 public: 548 Cleanup(APValue *Val, bool IsLifetimeExtended) 549 : Value(Val, IsLifetimeExtended) {} 550 551 bool isLifetimeExtended() const { return Value.getInt(); } 552 void endLifetime() { 553 *Value.getPointer() = APValue(); 554 } 555 }; 556 557 /// EvalInfo - This is a private struct used by the evaluator to capture 558 /// information about a subexpression as it is folded. It retains information 559 /// about the AST context, but also maintains information about the folded 560 /// expression. 561 /// 562 /// If an expression could be evaluated, it is still possible it is not a C 563 /// "integer constant expression" or constant expression. If not, this struct 564 /// captures information about how and why not. 565 /// 566 /// One bit of information passed *into* the request for constant folding 567 /// indicates whether the subexpression is "evaluated" or not according to C 568 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 569 /// evaluate the expression regardless of what the RHS is, but C only allows 570 /// certain things in certain situations. 571 struct EvalInfo { 572 ASTContext &Ctx; 573 574 /// EvalStatus - Contains information about the evaluation. 575 Expr::EvalStatus &EvalStatus; 576 577 /// CurrentCall - The top of the constexpr call stack. 578 CallStackFrame *CurrentCall; 579 580 /// CallStackDepth - The number of calls in the call stack right now. 581 unsigned CallStackDepth; 582 583 /// NextCallIndex - The next call index to assign. 584 unsigned NextCallIndex; 585 586 /// StepsLeft - The remaining number of evaluation steps we're permitted 587 /// to perform. This is essentially a limit for the number of statements 588 /// we will evaluate. 589 unsigned StepsLeft; 590 591 /// BottomFrame - The frame in which evaluation started. This must be 592 /// initialized after CurrentCall and CallStackDepth. 593 CallStackFrame BottomFrame; 594 595 /// A stack of values whose lifetimes end at the end of some surrounding 596 /// evaluation frame. 597 llvm::SmallVector<Cleanup, 16> CleanupStack; 598 599 /// EvaluatingDecl - This is the declaration whose initializer is being 600 /// evaluated, if any. 601 APValue::LValueBase EvaluatingDecl; 602 603 /// EvaluatingDeclValue - This is the value being constructed for the 604 /// declaration whose initializer is being evaluated, if any. 605 APValue *EvaluatingDeclValue; 606 607 /// EvaluatingObject - Pair of the AST node that an lvalue represents and 608 /// the call index that that lvalue was allocated in. 609 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject; 610 611 /// EvaluatingConstructors - Set of objects that are currently being 612 /// constructed. 613 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors; 614 615 struct EvaluatingConstructorRAII { 616 EvalInfo &EI; 617 EvaluatingObject Object; 618 bool DidInsert; 619 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object) 620 : EI(EI), Object(Object) { 621 DidInsert = EI.EvaluatingConstructors.insert(Object).second; 622 } 623 ~EvaluatingConstructorRAII() { 624 if (DidInsert) EI.EvaluatingConstructors.erase(Object); 625 } 626 }; 627 628 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) { 629 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex)); 630 } 631 632 /// The current array initialization index, if we're performing array 633 /// initialization. 634 uint64_t ArrayInitIndex = -1; 635 636 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 637 /// notes attached to it will also be stored, otherwise they will not be. 638 bool HasActiveDiagnostic; 639 640 /// \brief Have we emitted a diagnostic explaining why we couldn't constant 641 /// fold (not just why it's not strictly a constant expression)? 642 bool HasFoldFailureDiagnostic; 643 644 /// \brief Whether or not we're currently speculatively evaluating. 645 bool IsSpeculativelyEvaluating; 646 647 enum EvaluationMode { 648 /// Evaluate as a constant expression. Stop if we find that the expression 649 /// is not a constant expression. 650 EM_ConstantExpression, 651 652 /// Evaluate as a potential constant expression. Keep going if we hit a 653 /// construct that we can't evaluate yet (because we don't yet know the 654 /// value of something) but stop if we hit something that could never be 655 /// a constant expression. 656 EM_PotentialConstantExpression, 657 658 /// Fold the expression to a constant. Stop if we hit a side-effect that 659 /// we can't model. 660 EM_ConstantFold, 661 662 /// Evaluate the expression looking for integer overflow and similar 663 /// issues. Don't worry about side-effects, and try to visit all 664 /// subexpressions. 665 EM_EvaluateForOverflow, 666 667 /// Evaluate in any way we know how. Don't worry about side-effects that 668 /// can't be modeled. 669 EM_IgnoreSideEffects, 670 671 /// Evaluate as a constant expression. Stop if we find that the expression 672 /// is not a constant expression. Some expressions can be retried in the 673 /// optimizer if we don't constant fold them here, but in an unevaluated 674 /// context we try to fold them immediately since the optimizer never 675 /// gets a chance to look at it. 676 EM_ConstantExpressionUnevaluated, 677 678 /// Evaluate as a potential constant expression. Keep going if we hit a 679 /// construct that we can't evaluate yet (because we don't yet know the 680 /// value of something) but stop if we hit something that could never be 681 /// a constant expression. Some expressions can be retried in the 682 /// optimizer if we don't constant fold them here, but in an unevaluated 683 /// context we try to fold them immediately since the optimizer never 684 /// gets a chance to look at it. 685 EM_PotentialConstantExpressionUnevaluated, 686 687 /// Evaluate as a constant expression. In certain scenarios, if: 688 /// - we find a MemberExpr with a base that can't be evaluated, or 689 /// - we find a variable initialized with a call to a function that has 690 /// the alloc_size attribute on it 691 /// then we may consider evaluation to have succeeded. 692 /// 693 /// In either case, the LValue returned shall have an invalid base; in the 694 /// former, the base will be the invalid MemberExpr, in the latter, the 695 /// base will be either the alloc_size CallExpr or a CastExpr wrapping 696 /// said CallExpr. 697 EM_OffsetFold, 698 } EvalMode; 699 700 /// Are we checking whether the expression is a potential constant 701 /// expression? 702 bool checkingPotentialConstantExpression() const { 703 return EvalMode == EM_PotentialConstantExpression || 704 EvalMode == EM_PotentialConstantExpressionUnevaluated; 705 } 706 707 /// Are we checking an expression for overflow? 708 // FIXME: We should check for any kind of undefined or suspicious behavior 709 // in such constructs, not just overflow. 710 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; } 711 712 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 713 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 714 CallStackDepth(0), NextCallIndex(1), 715 StepsLeft(getLangOpts().ConstexprStepLimit), 716 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 717 EvaluatingDecl((const ValueDecl *)nullptr), 718 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 719 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false), 720 EvalMode(Mode) {} 721 722 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 723 EvaluatingDecl = Base; 724 EvaluatingDeclValue = &Value; 725 EvaluatingConstructors.insert({Base, 0}); 726 } 727 728 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 729 730 bool CheckCallLimit(SourceLocation Loc) { 731 // Don't perform any constexpr calls (other than the call we're checking) 732 // when checking a potential constant expression. 733 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 734 return false; 735 if (NextCallIndex == 0) { 736 // NextCallIndex has wrapped around. 737 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 738 return false; 739 } 740 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 741 return true; 742 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 743 << getLangOpts().ConstexprCallDepth; 744 return false; 745 } 746 747 CallStackFrame *getCallFrame(unsigned CallIndex) { 748 assert(CallIndex && "no call index in getCallFrame"); 749 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 750 // be null in this loop. 751 CallStackFrame *Frame = CurrentCall; 752 while (Frame->Index > CallIndex) 753 Frame = Frame->Caller; 754 return (Frame->Index == CallIndex) ? Frame : nullptr; 755 } 756 757 bool nextStep(const Stmt *S) { 758 if (!StepsLeft) { 759 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded); 760 return false; 761 } 762 --StepsLeft; 763 return true; 764 } 765 766 private: 767 /// Add a diagnostic to the diagnostics list. 768 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 769 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 770 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 771 return EvalStatus.Diag->back().second; 772 } 773 774 /// Add notes containing a call stack to the current point of evaluation. 775 void addCallStack(unsigned Limit); 776 777 private: 778 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, 779 unsigned ExtraNotes, bool IsCCEDiag) { 780 781 if (EvalStatus.Diag) { 782 // If we have a prior diagnostic, it will be noting that the expression 783 // isn't a constant expression. This diagnostic is more important, 784 // unless we require this evaluation to produce a constant expression. 785 // 786 // FIXME: We might want to show both diagnostics to the user in 787 // EM_ConstantFold mode. 788 if (!EvalStatus.Diag->empty()) { 789 switch (EvalMode) { 790 case EM_ConstantFold: 791 case EM_IgnoreSideEffects: 792 case EM_EvaluateForOverflow: 793 if (!HasFoldFailureDiagnostic) 794 break; 795 // We've already failed to fold something. Keep that diagnostic. 796 LLVM_FALLTHROUGH; 797 case EM_ConstantExpression: 798 case EM_PotentialConstantExpression: 799 case EM_ConstantExpressionUnevaluated: 800 case EM_PotentialConstantExpressionUnevaluated: 801 case EM_OffsetFold: 802 HasActiveDiagnostic = false; 803 return OptionalDiagnostic(); 804 } 805 } 806 807 unsigned CallStackNotes = CallStackDepth - 1; 808 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 809 if (Limit) 810 CallStackNotes = std::min(CallStackNotes, Limit + 1); 811 if (checkingPotentialConstantExpression()) 812 CallStackNotes = 0; 813 814 HasActiveDiagnostic = true; 815 HasFoldFailureDiagnostic = !IsCCEDiag; 816 EvalStatus.Diag->clear(); 817 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 818 addDiag(Loc, DiagId); 819 if (!checkingPotentialConstantExpression()) 820 addCallStack(Limit); 821 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 822 } 823 HasActiveDiagnostic = false; 824 return OptionalDiagnostic(); 825 } 826 public: 827 // Diagnose that the evaluation could not be folded (FF => FoldFailure) 828 OptionalDiagnostic 829 FFDiag(SourceLocation Loc, 830 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, 831 unsigned ExtraNotes = 0) { 832 return Diag(Loc, DiagId, ExtraNotes, false); 833 } 834 835 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId 836 = diag::note_invalid_subexpr_in_const_expr, 837 unsigned ExtraNotes = 0) { 838 if (EvalStatus.Diag) 839 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false); 840 HasActiveDiagnostic = false; 841 return OptionalDiagnostic(); 842 } 843 844 /// Diagnose that the evaluation does not produce a C++11 core constant 845 /// expression. 846 /// 847 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or 848 /// EM_PotentialConstantExpression mode and we produce one of these. 849 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 850 = diag::note_invalid_subexpr_in_const_expr, 851 unsigned ExtraNotes = 0) { 852 // Don't override a previous diagnostic. Don't bother collecting 853 // diagnostics if we're evaluating for overflow. 854 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 855 HasActiveDiagnostic = false; 856 return OptionalDiagnostic(); 857 } 858 return Diag(Loc, DiagId, ExtraNotes, true); 859 } 860 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId 861 = diag::note_invalid_subexpr_in_const_expr, 862 unsigned ExtraNotes = 0) { 863 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes); 864 } 865 /// Add a note to a prior diagnostic. 866 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 867 if (!HasActiveDiagnostic) 868 return OptionalDiagnostic(); 869 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 870 } 871 872 /// Add a stack of notes to a prior diagnostic. 873 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 874 if (HasActiveDiagnostic) { 875 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 876 Diags.begin(), Diags.end()); 877 } 878 } 879 880 /// Should we continue evaluation after encountering a side-effect that we 881 /// couldn't model? 882 bool keepEvaluatingAfterSideEffect() { 883 switch (EvalMode) { 884 case EM_PotentialConstantExpression: 885 case EM_PotentialConstantExpressionUnevaluated: 886 case EM_EvaluateForOverflow: 887 case EM_IgnoreSideEffects: 888 return true; 889 890 case EM_ConstantExpression: 891 case EM_ConstantExpressionUnevaluated: 892 case EM_ConstantFold: 893 case EM_OffsetFold: 894 return false; 895 } 896 llvm_unreachable("Missed EvalMode case"); 897 } 898 899 /// Note that we have had a side-effect, and determine whether we should 900 /// keep evaluating. 901 bool noteSideEffect() { 902 EvalStatus.HasSideEffects = true; 903 return keepEvaluatingAfterSideEffect(); 904 } 905 906 /// Should we continue evaluation after encountering undefined behavior? 907 bool keepEvaluatingAfterUndefinedBehavior() { 908 switch (EvalMode) { 909 case EM_EvaluateForOverflow: 910 case EM_IgnoreSideEffects: 911 case EM_ConstantFold: 912 case EM_OffsetFold: 913 return true; 914 915 case EM_PotentialConstantExpression: 916 case EM_PotentialConstantExpressionUnevaluated: 917 case EM_ConstantExpression: 918 case EM_ConstantExpressionUnevaluated: 919 return false; 920 } 921 llvm_unreachable("Missed EvalMode case"); 922 } 923 924 /// Note that we hit something that was technically undefined behavior, but 925 /// that we can evaluate past it (such as signed overflow or floating-point 926 /// division by zero.) 927 bool noteUndefinedBehavior() { 928 EvalStatus.HasUndefinedBehavior = true; 929 return keepEvaluatingAfterUndefinedBehavior(); 930 } 931 932 /// Should we continue evaluation as much as possible after encountering a 933 /// construct which can't be reduced to a value? 934 bool keepEvaluatingAfterFailure() { 935 if (!StepsLeft) 936 return false; 937 938 switch (EvalMode) { 939 case EM_PotentialConstantExpression: 940 case EM_PotentialConstantExpressionUnevaluated: 941 case EM_EvaluateForOverflow: 942 return true; 943 944 case EM_ConstantExpression: 945 case EM_ConstantExpressionUnevaluated: 946 case EM_ConstantFold: 947 case EM_IgnoreSideEffects: 948 case EM_OffsetFold: 949 return false; 950 } 951 llvm_unreachable("Missed EvalMode case"); 952 } 953 954 /// Notes that we failed to evaluate an expression that other expressions 955 /// directly depend on, and determine if we should keep evaluating. This 956 /// should only be called if we actually intend to keep evaluating. 957 /// 958 /// Call noteSideEffect() instead if we may be able to ignore the value that 959 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 960 /// 961 /// (Foo(), 1) // use noteSideEffect 962 /// (Foo() || true) // use noteSideEffect 963 /// Foo() + 1 // use noteFailure 964 LLVM_NODISCARD bool noteFailure() { 965 // Failure when evaluating some expression often means there is some 966 // subexpression whose evaluation was skipped. Therefore, (because we 967 // don't track whether we skipped an expression when unwinding after an 968 // evaluation failure) every evaluation failure that bubbles up from a 969 // subexpression implies that a side-effect has potentially happened. We 970 // skip setting the HasSideEffects flag to true until we decide to 971 // continue evaluating after that point, which happens here. 972 bool KeepGoing = keepEvaluatingAfterFailure(); 973 EvalStatus.HasSideEffects |= KeepGoing; 974 return KeepGoing; 975 } 976 977 class ArrayInitLoopIndex { 978 EvalInfo &Info; 979 uint64_t OuterIndex; 980 981 public: 982 ArrayInitLoopIndex(EvalInfo &Info) 983 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 984 Info.ArrayInitIndex = 0; 985 } 986 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 987 988 operator uint64_t&() { return Info.ArrayInitIndex; } 989 }; 990 }; 991 992 /// Object used to treat all foldable expressions as constant expressions. 993 struct FoldConstant { 994 EvalInfo &Info; 995 bool Enabled; 996 bool HadNoPriorDiags; 997 EvalInfo::EvaluationMode OldMode; 998 999 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1000 : Info(Info), 1001 Enabled(Enabled), 1002 HadNoPriorDiags(Info.EvalStatus.Diag && 1003 Info.EvalStatus.Diag->empty() && 1004 !Info.EvalStatus.HasSideEffects), 1005 OldMode(Info.EvalMode) { 1006 if (Enabled && 1007 (Info.EvalMode == EvalInfo::EM_ConstantExpression || 1008 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated)) 1009 Info.EvalMode = EvalInfo::EM_ConstantFold; 1010 } 1011 void keepDiagnostics() { Enabled = false; } 1012 ~FoldConstant() { 1013 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1014 !Info.EvalStatus.HasSideEffects) 1015 Info.EvalStatus.Diag->clear(); 1016 Info.EvalMode = OldMode; 1017 } 1018 }; 1019 1020 /// RAII object used to treat the current evaluation as the correct pointer 1021 /// offset fold for the current EvalMode 1022 struct FoldOffsetRAII { 1023 EvalInfo &Info; 1024 EvalInfo::EvaluationMode OldMode; 1025 explicit FoldOffsetRAII(EvalInfo &Info) 1026 : Info(Info), OldMode(Info.EvalMode) { 1027 if (!Info.checkingPotentialConstantExpression()) 1028 Info.EvalMode = EvalInfo::EM_OffsetFold; 1029 } 1030 1031 ~FoldOffsetRAII() { Info.EvalMode = OldMode; } 1032 }; 1033 1034 /// RAII object used to optionally suppress diagnostics and side-effects from 1035 /// a speculative evaluation. 1036 class SpeculativeEvaluationRAII { 1037 EvalInfo *Info = nullptr; 1038 Expr::EvalStatus OldStatus; 1039 bool OldIsSpeculativelyEvaluating; 1040 1041 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1042 Info = Other.Info; 1043 OldStatus = Other.OldStatus; 1044 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating; 1045 Other.Info = nullptr; 1046 } 1047 1048 void maybeRestoreState() { 1049 if (!Info) 1050 return; 1051 1052 Info->EvalStatus = OldStatus; 1053 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating; 1054 } 1055 1056 public: 1057 SpeculativeEvaluationRAII() = default; 1058 1059 SpeculativeEvaluationRAII( 1060 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1061 : Info(&Info), OldStatus(Info.EvalStatus), 1062 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) { 1063 Info.EvalStatus.Diag = NewDiag; 1064 Info.IsSpeculativelyEvaluating = true; 1065 } 1066 1067 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1068 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1069 moveFromAndCancel(std::move(Other)); 1070 } 1071 1072 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1073 maybeRestoreState(); 1074 moveFromAndCancel(std::move(Other)); 1075 return *this; 1076 } 1077 1078 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1079 }; 1080 1081 /// RAII object wrapping a full-expression or block scope, and handling 1082 /// the ending of the lifetime of temporaries created within it. 1083 template<bool IsFullExpression> 1084 class ScopeRAII { 1085 EvalInfo &Info; 1086 unsigned OldStackSize; 1087 public: 1088 ScopeRAII(EvalInfo &Info) 1089 : Info(Info), OldStackSize(Info.CleanupStack.size()) {} 1090 ~ScopeRAII() { 1091 // Body moved to a static method to encourage the compiler to inline away 1092 // instances of this class. 1093 cleanup(Info, OldStackSize); 1094 } 1095 private: 1096 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 1097 unsigned NewEnd = OldStackSize; 1098 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 1099 I != N; ++I) { 1100 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 1101 // Full-expression cleanup of a lifetime-extended temporary: nothing 1102 // to do, just move this cleanup to the right place in the stack. 1103 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 1104 ++NewEnd; 1105 } else { 1106 // End the lifetime of the object. 1107 Info.CleanupStack[I].endLifetime(); 1108 } 1109 } 1110 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 1111 Info.CleanupStack.end()); 1112 } 1113 }; 1114 typedef ScopeRAII<false> BlockScopeRAII; 1115 typedef ScopeRAII<true> FullExpressionRAII; 1116 } 1117 1118 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1119 CheckSubobjectKind CSK) { 1120 if (Invalid) 1121 return false; 1122 if (isOnePastTheEnd()) { 1123 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1124 << CSK; 1125 setInvalid(); 1126 return false; 1127 } 1128 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1129 // must actually be at least one array element; even a VLA cannot have a 1130 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1131 return true; 1132 } 1133 1134 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1135 const Expr *E) { 1136 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1137 // Do not set the designator as invalid: we can represent this situation, 1138 // and correct handling of __builtin_object_size requires us to do so. 1139 } 1140 1141 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1142 const Expr *E, 1143 const APSInt &N) { 1144 // If we're complaining, we must be able to statically determine the size of 1145 // the most derived array. 1146 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1147 Info.CCEDiag(E, diag::note_constexpr_array_index) 1148 << N << /*array*/ 0 1149 << static_cast<unsigned>(getMostDerivedArraySize()); 1150 else 1151 Info.CCEDiag(E, diag::note_constexpr_array_index) 1152 << N << /*non-array*/ 1; 1153 setInvalid(); 1154 } 1155 1156 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1157 const FunctionDecl *Callee, const LValue *This, 1158 APValue *Arguments) 1159 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1160 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1161 Info.CurrentCall = this; 1162 ++Info.CallStackDepth; 1163 } 1164 1165 CallStackFrame::~CallStackFrame() { 1166 assert(Info.CurrentCall == this && "calls retired out of order"); 1167 --Info.CallStackDepth; 1168 Info.CurrentCall = Caller; 1169 } 1170 1171 APValue &CallStackFrame::createTemporary(const void *Key, 1172 bool IsLifetimeExtended) { 1173 APValue &Result = Temporaries[Key]; 1174 assert(Result.isUninit() && "temporary created multiple times"); 1175 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 1176 return Result; 1177 } 1178 1179 static void describeCall(CallStackFrame *Frame, raw_ostream &Out); 1180 1181 void EvalInfo::addCallStack(unsigned Limit) { 1182 // Determine which calls to skip, if any. 1183 unsigned ActiveCalls = CallStackDepth - 1; 1184 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 1185 if (Limit && Limit < ActiveCalls) { 1186 SkipStart = Limit / 2 + Limit % 2; 1187 SkipEnd = ActiveCalls - Limit / 2; 1188 } 1189 1190 // Walk the call stack and add the diagnostics. 1191 unsigned CallIdx = 0; 1192 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 1193 Frame = Frame->Caller, ++CallIdx) { 1194 // Skip this call? 1195 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 1196 if (CallIdx == SkipStart) { 1197 // Note that we're skipping calls. 1198 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 1199 << unsigned(ActiveCalls - Limit); 1200 } 1201 continue; 1202 } 1203 1204 // Use a different note for an inheriting constructor, because from the 1205 // user's perspective it's not really a function at all. 1206 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) { 1207 if (CD->isInheritingConstructor()) { 1208 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here) 1209 << CD->getParent(); 1210 continue; 1211 } 1212 } 1213 1214 SmallVector<char, 128> Buffer; 1215 llvm::raw_svector_ostream Out(Buffer); 1216 describeCall(Frame, Out); 1217 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 1218 } 1219 } 1220 1221 namespace { 1222 struct ComplexValue { 1223 private: 1224 bool IsInt; 1225 1226 public: 1227 APSInt IntReal, IntImag; 1228 APFloat FloatReal, FloatImag; 1229 1230 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1231 1232 void makeComplexFloat() { IsInt = false; } 1233 bool isComplexFloat() const { return !IsInt; } 1234 APFloat &getComplexFloatReal() { return FloatReal; } 1235 APFloat &getComplexFloatImag() { return FloatImag; } 1236 1237 void makeComplexInt() { IsInt = true; } 1238 bool isComplexInt() const { return IsInt; } 1239 APSInt &getComplexIntReal() { return IntReal; } 1240 APSInt &getComplexIntImag() { return IntImag; } 1241 1242 void moveInto(APValue &v) const { 1243 if (isComplexFloat()) 1244 v = APValue(FloatReal, FloatImag); 1245 else 1246 v = APValue(IntReal, IntImag); 1247 } 1248 void setFrom(const APValue &v) { 1249 assert(v.isComplexFloat() || v.isComplexInt()); 1250 if (v.isComplexFloat()) { 1251 makeComplexFloat(); 1252 FloatReal = v.getComplexFloatReal(); 1253 FloatImag = v.getComplexFloatImag(); 1254 } else { 1255 makeComplexInt(); 1256 IntReal = v.getComplexIntReal(); 1257 IntImag = v.getComplexIntImag(); 1258 } 1259 } 1260 }; 1261 1262 struct LValue { 1263 APValue::LValueBase Base; 1264 CharUnits Offset; 1265 unsigned InvalidBase : 1; 1266 unsigned CallIndex : 31; 1267 SubobjectDesignator Designator; 1268 bool IsNullPtr; 1269 1270 const APValue::LValueBase getLValueBase() const { return Base; } 1271 CharUnits &getLValueOffset() { return Offset; } 1272 const CharUnits &getLValueOffset() const { return Offset; } 1273 unsigned getLValueCallIndex() const { return CallIndex; } 1274 SubobjectDesignator &getLValueDesignator() { return Designator; } 1275 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1276 bool isNullPointer() const { return IsNullPtr;} 1277 1278 void moveInto(APValue &V) const { 1279 if (Designator.Invalid) 1280 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex, 1281 IsNullPtr); 1282 else { 1283 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1284 V = APValue(Base, Offset, Designator.Entries, 1285 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr); 1286 } 1287 } 1288 void setFrom(ASTContext &Ctx, const APValue &V) { 1289 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1290 Base = V.getLValueBase(); 1291 Offset = V.getLValueOffset(); 1292 InvalidBase = false; 1293 CallIndex = V.getLValueCallIndex(); 1294 Designator = SubobjectDesignator(Ctx, V); 1295 IsNullPtr = V.isNullPointer(); 1296 } 1297 1298 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) { 1299 #ifndef NDEBUG 1300 // We only allow a few types of invalid bases. Enforce that here. 1301 if (BInvalid) { 1302 const auto *E = B.get<const Expr *>(); 1303 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1304 "Unexpected type of invalid base"); 1305 } 1306 #endif 1307 1308 Base = B; 1309 Offset = CharUnits::fromQuantity(0); 1310 InvalidBase = BInvalid; 1311 CallIndex = I; 1312 Designator = SubobjectDesignator(getType(B)); 1313 IsNullPtr = false; 1314 } 1315 1316 void setNull(QualType PointerTy, uint64_t TargetVal) { 1317 Base = (Expr *)nullptr; 1318 Offset = CharUnits::fromQuantity(TargetVal); 1319 InvalidBase = false; 1320 CallIndex = 0; 1321 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1322 IsNullPtr = true; 1323 } 1324 1325 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1326 set(B, I, true); 1327 } 1328 1329 // Check that this LValue is not based on a null pointer. If it is, produce 1330 // a diagnostic and mark the designator as invalid. 1331 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1332 CheckSubobjectKind CSK) { 1333 if (Designator.Invalid) 1334 return false; 1335 if (IsNullPtr) { 1336 Info.CCEDiag(E, diag::note_constexpr_null_subobject) 1337 << CSK; 1338 Designator.setInvalid(); 1339 return false; 1340 } 1341 return true; 1342 } 1343 1344 // Check this LValue refers to an object. If not, set the designator to be 1345 // invalid and emit a diagnostic. 1346 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1347 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1348 Designator.checkSubobject(Info, E, CSK); 1349 } 1350 1351 void addDecl(EvalInfo &Info, const Expr *E, 1352 const Decl *D, bool Virtual = false) { 1353 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1354 Designator.addDeclUnchecked(D, Virtual); 1355 } 1356 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1357 if (!Designator.Entries.empty()) { 1358 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1359 Designator.setInvalid(); 1360 return; 1361 } 1362 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1363 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1364 Designator.FirstEntryIsAnUnsizedArray = true; 1365 Designator.addUnsizedArrayUnchecked(ElemTy); 1366 } 1367 } 1368 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1369 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1370 Designator.addArrayUnchecked(CAT); 1371 } 1372 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1373 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1374 Designator.addComplexUnchecked(EltTy, Imag); 1375 } 1376 void clearIsNullPointer() { 1377 IsNullPtr = false; 1378 } 1379 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1380 const APSInt &Index, CharUnits ElementSize) { 1381 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1382 // but we're not required to diagnose it and it's valid in C++.) 1383 if (!Index) 1384 return; 1385 1386 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1387 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1388 // offsets. 1389 uint64_t Offset64 = Offset.getQuantity(); 1390 uint64_t ElemSize64 = ElementSize.getQuantity(); 1391 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1392 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1393 1394 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1395 Designator.adjustIndex(Info, E, Index); 1396 clearIsNullPointer(); 1397 } 1398 void adjustOffset(CharUnits N) { 1399 Offset += N; 1400 if (N.getQuantity()) 1401 clearIsNullPointer(); 1402 } 1403 }; 1404 1405 struct MemberPtr { 1406 MemberPtr() {} 1407 explicit MemberPtr(const ValueDecl *Decl) : 1408 DeclAndIsDerivedMember(Decl, false), Path() {} 1409 1410 /// The member or (direct or indirect) field referred to by this member 1411 /// pointer, or 0 if this is a null member pointer. 1412 const ValueDecl *getDecl() const { 1413 return DeclAndIsDerivedMember.getPointer(); 1414 } 1415 /// Is this actually a member of some type derived from the relevant class? 1416 bool isDerivedMember() const { 1417 return DeclAndIsDerivedMember.getInt(); 1418 } 1419 /// Get the class which the declaration actually lives in. 1420 const CXXRecordDecl *getContainingRecord() const { 1421 return cast<CXXRecordDecl>( 1422 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1423 } 1424 1425 void moveInto(APValue &V) const { 1426 V = APValue(getDecl(), isDerivedMember(), Path); 1427 } 1428 void setFrom(const APValue &V) { 1429 assert(V.isMemberPointer()); 1430 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1431 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1432 Path.clear(); 1433 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1434 Path.insert(Path.end(), P.begin(), P.end()); 1435 } 1436 1437 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1438 /// whether the member is a member of some class derived from the class type 1439 /// of the member pointer. 1440 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1441 /// Path - The path of base/derived classes from the member declaration's 1442 /// class (exclusive) to the class type of the member pointer (inclusive). 1443 SmallVector<const CXXRecordDecl*, 4> Path; 1444 1445 /// Perform a cast towards the class of the Decl (either up or down the 1446 /// hierarchy). 1447 bool castBack(const CXXRecordDecl *Class) { 1448 assert(!Path.empty()); 1449 const CXXRecordDecl *Expected; 1450 if (Path.size() >= 2) 1451 Expected = Path[Path.size() - 2]; 1452 else 1453 Expected = getContainingRecord(); 1454 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1455 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1456 // if B does not contain the original member and is not a base or 1457 // derived class of the class containing the original member, the result 1458 // of the cast is undefined. 1459 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1460 // (D::*). We consider that to be a language defect. 1461 return false; 1462 } 1463 Path.pop_back(); 1464 return true; 1465 } 1466 /// Perform a base-to-derived member pointer cast. 1467 bool castToDerived(const CXXRecordDecl *Derived) { 1468 if (!getDecl()) 1469 return true; 1470 if (!isDerivedMember()) { 1471 Path.push_back(Derived); 1472 return true; 1473 } 1474 if (!castBack(Derived)) 1475 return false; 1476 if (Path.empty()) 1477 DeclAndIsDerivedMember.setInt(false); 1478 return true; 1479 } 1480 /// Perform a derived-to-base member pointer cast. 1481 bool castToBase(const CXXRecordDecl *Base) { 1482 if (!getDecl()) 1483 return true; 1484 if (Path.empty()) 1485 DeclAndIsDerivedMember.setInt(true); 1486 if (isDerivedMember()) { 1487 Path.push_back(Base); 1488 return true; 1489 } 1490 return castBack(Base); 1491 } 1492 }; 1493 1494 /// Compare two member pointers, which are assumed to be of the same type. 1495 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1496 if (!LHS.getDecl() || !RHS.getDecl()) 1497 return !LHS.getDecl() && !RHS.getDecl(); 1498 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1499 return false; 1500 return LHS.Path == RHS.Path; 1501 } 1502 } 1503 1504 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1505 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1506 const LValue &This, const Expr *E, 1507 bool AllowNonLiteralTypes = false); 1508 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1509 bool InvalidBaseOK = false); 1510 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1511 bool InvalidBaseOK = false); 1512 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1513 EvalInfo &Info); 1514 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1515 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1516 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1517 EvalInfo &Info); 1518 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1519 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1520 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1521 EvalInfo &Info); 1522 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1523 1524 //===----------------------------------------------------------------------===// 1525 // Misc utilities 1526 //===----------------------------------------------------------------------===// 1527 1528 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1529 /// preserving its value (by extending by up to one bit as needed). 1530 static void negateAsSigned(APSInt &Int) { 1531 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1532 Int = Int.extend(Int.getBitWidth() + 1); 1533 Int.setIsSigned(true); 1534 } 1535 Int = -Int; 1536 } 1537 1538 /// Produce a string describing the given constexpr call. 1539 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) { 1540 unsigned ArgIndex = 0; 1541 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 1542 !isa<CXXConstructorDecl>(Frame->Callee) && 1543 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 1544 1545 if (!IsMemberCall) 1546 Out << *Frame->Callee << '('; 1547 1548 if (Frame->This && IsMemberCall) { 1549 APValue Val; 1550 Frame->This->moveInto(Val); 1551 Val.printPretty(Out, Frame->Info.Ctx, 1552 Frame->This->Designator.MostDerivedType); 1553 // FIXME: Add parens around Val if needed. 1554 Out << "->" << *Frame->Callee << '('; 1555 IsMemberCall = false; 1556 } 1557 1558 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 1559 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 1560 if (ArgIndex > (unsigned)IsMemberCall) 1561 Out << ", "; 1562 1563 const ParmVarDecl *Param = *I; 1564 const APValue &Arg = Frame->Arguments[ArgIndex]; 1565 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 1566 1567 if (ArgIndex == 0 && IsMemberCall) 1568 Out << "->" << *Frame->Callee << '('; 1569 } 1570 1571 Out << ')'; 1572 } 1573 1574 /// Evaluate an expression to see if it had side-effects, and discard its 1575 /// result. 1576 /// \return \c true if the caller should keep evaluating. 1577 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1578 APValue Scratch; 1579 if (!Evaluate(Scratch, Info, E)) 1580 // We don't need the value, but we might have skipped a side effect here. 1581 return Info.noteSideEffect(); 1582 return true; 1583 } 1584 1585 /// Should this call expression be treated as a string literal? 1586 static bool IsStringLiteralCall(const CallExpr *E) { 1587 unsigned Builtin = E->getBuiltinCallee(); 1588 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1589 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1590 } 1591 1592 static bool IsGlobalLValue(APValue::LValueBase B) { 1593 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1594 // constant expression of pointer type that evaluates to... 1595 1596 // ... a null pointer value, or a prvalue core constant expression of type 1597 // std::nullptr_t. 1598 if (!B) return true; 1599 1600 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1601 // ... the address of an object with static storage duration, 1602 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1603 return VD->hasGlobalStorage(); 1604 // ... the address of a function, 1605 return isa<FunctionDecl>(D); 1606 } 1607 1608 const Expr *E = B.get<const Expr*>(); 1609 switch (E->getStmtClass()) { 1610 default: 1611 return false; 1612 case Expr::CompoundLiteralExprClass: { 1613 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1614 return CLE->isFileScope() && CLE->isLValue(); 1615 } 1616 case Expr::MaterializeTemporaryExprClass: 1617 // A materialized temporary might have been lifetime-extended to static 1618 // storage duration. 1619 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1620 // A string literal has static storage duration. 1621 case Expr::StringLiteralClass: 1622 case Expr::PredefinedExprClass: 1623 case Expr::ObjCStringLiteralClass: 1624 case Expr::ObjCEncodeExprClass: 1625 case Expr::CXXTypeidExprClass: 1626 case Expr::CXXUuidofExprClass: 1627 return true; 1628 case Expr::CallExprClass: 1629 return IsStringLiteralCall(cast<CallExpr>(E)); 1630 // For GCC compatibility, &&label has static storage duration. 1631 case Expr::AddrLabelExprClass: 1632 return true; 1633 // A Block literal expression may be used as the initialization value for 1634 // Block variables at global or local static scope. 1635 case Expr::BlockExprClass: 1636 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1637 case Expr::ImplicitValueInitExprClass: 1638 // FIXME: 1639 // We can never form an lvalue with an implicit value initialization as its 1640 // base through expression evaluation, so these only appear in one case: the 1641 // implicit variable declaration we invent when checking whether a constexpr 1642 // constructor can produce a constant expression. We must assume that such 1643 // an expression might be a global lvalue. 1644 return true; 1645 } 1646 } 1647 1648 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1649 assert(Base && "no location for a null lvalue"); 1650 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1651 if (VD) 1652 Info.Note(VD->getLocation(), diag::note_declared_at); 1653 else 1654 Info.Note(Base.get<const Expr*>()->getExprLoc(), 1655 diag::note_constexpr_temporary_here); 1656 } 1657 1658 /// Check that this reference or pointer core constant expression is a valid 1659 /// value for an address or reference constant expression. Return true if we 1660 /// can fold this expression, whether or not it's a constant expression. 1661 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1662 QualType Type, const LValue &LVal) { 1663 bool IsReferenceType = Type->isReferenceType(); 1664 1665 APValue::LValueBase Base = LVal.getLValueBase(); 1666 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1667 1668 // Check that the object is a global. Note that the fake 'this' object we 1669 // manufacture when checking potential constant expressions is conservatively 1670 // assumed to be global here. 1671 if (!IsGlobalLValue(Base)) { 1672 if (Info.getLangOpts().CPlusPlus11) { 1673 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1674 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1675 << IsReferenceType << !Designator.Entries.empty() 1676 << !!VD << VD; 1677 NoteLValueLocation(Info, Base); 1678 } else { 1679 Info.FFDiag(Loc); 1680 } 1681 // Don't allow references to temporaries to escape. 1682 return false; 1683 } 1684 assert((Info.checkingPotentialConstantExpression() || 1685 LVal.getLValueCallIndex() == 0) && 1686 "have call index for global lvalue"); 1687 1688 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1689 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1690 // Check if this is a thread-local variable. 1691 if (Var->getTLSKind()) 1692 return false; 1693 1694 // A dllimport variable never acts like a constant. 1695 if (Var->hasAttr<DLLImportAttr>()) 1696 return false; 1697 } 1698 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1699 // __declspec(dllimport) must be handled very carefully: 1700 // We must never initialize an expression with the thunk in C++. 1701 // Doing otherwise would allow the same id-expression to yield 1702 // different addresses for the same function in different translation 1703 // units. However, this means that we must dynamically initialize the 1704 // expression with the contents of the import address table at runtime. 1705 // 1706 // The C language has no notion of ODR; furthermore, it has no notion of 1707 // dynamic initialization. This means that we are permitted to 1708 // perform initialization with the address of the thunk. 1709 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>()) 1710 return false; 1711 } 1712 } 1713 1714 // Allow address constant expressions to be past-the-end pointers. This is 1715 // an extension: the standard requires them to point to an object. 1716 if (!IsReferenceType) 1717 return true; 1718 1719 // A reference constant expression must refer to an object. 1720 if (!Base) { 1721 // FIXME: diagnostic 1722 Info.CCEDiag(Loc); 1723 return true; 1724 } 1725 1726 // Does this refer one past the end of some object? 1727 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1728 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1729 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1730 << !Designator.Entries.empty() << !!VD << VD; 1731 NoteLValueLocation(Info, Base); 1732 } 1733 1734 return true; 1735 } 1736 1737 /// Member pointers are constant expressions unless they point to a 1738 /// non-virtual dllimport member function. 1739 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 1740 SourceLocation Loc, 1741 QualType Type, 1742 const APValue &Value) { 1743 const ValueDecl *Member = Value.getMemberPointerDecl(); 1744 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 1745 if (!FD) 1746 return true; 1747 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>(); 1748 } 1749 1750 /// Check that this core constant expression is of literal type, and if not, 1751 /// produce an appropriate diagnostic. 1752 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 1753 const LValue *This = nullptr) { 1754 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 1755 return true; 1756 1757 // C++1y: A constant initializer for an object o [...] may also invoke 1758 // constexpr constructors for o and its subobjects even if those objects 1759 // are of non-literal class types. 1760 // 1761 // C++11 missed this detail for aggregates, so classes like this: 1762 // struct foo_t { union { int i; volatile int j; } u; }; 1763 // are not (obviously) initializable like so: 1764 // __attribute__((__require_constant_initialization__)) 1765 // static const foo_t x = {{0}}; 1766 // because "i" is a subobject with non-literal initialization (due to the 1767 // volatile member of the union). See: 1768 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 1769 // Therefore, we use the C++1y behavior. 1770 if (This && Info.EvaluatingDecl == This->getLValueBase()) 1771 return true; 1772 1773 // Prvalue constant expressions must be of literal types. 1774 if (Info.getLangOpts().CPlusPlus11) 1775 Info.FFDiag(E, diag::note_constexpr_nonliteral) 1776 << E->getType(); 1777 else 1778 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1779 return false; 1780 } 1781 1782 /// Check that this core constant expression value is a valid value for a 1783 /// constant expression. If not, report an appropriate diagnostic. Does not 1784 /// check that the expression is of literal type. 1785 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, 1786 QualType Type, const APValue &Value) { 1787 if (Value.isUninit()) { 1788 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 1789 << true << Type; 1790 return false; 1791 } 1792 1793 // We allow _Atomic(T) to be initialized from anything that T can be 1794 // initialized from. 1795 if (const AtomicType *AT = Type->getAs<AtomicType>()) 1796 Type = AT->getValueType(); 1797 1798 // Core issue 1454: For a literal constant expression of array or class type, 1799 // each subobject of its value shall have been initialized by a constant 1800 // expression. 1801 if (Value.isArray()) { 1802 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 1803 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 1804 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 1805 Value.getArrayInitializedElt(I))) 1806 return false; 1807 } 1808 if (!Value.hasArrayFiller()) 1809 return true; 1810 return CheckConstantExpression(Info, DiagLoc, EltTy, 1811 Value.getArrayFiller()); 1812 } 1813 if (Value.isUnion() && Value.getUnionField()) { 1814 return CheckConstantExpression(Info, DiagLoc, 1815 Value.getUnionField()->getType(), 1816 Value.getUnionValue()); 1817 } 1818 if (Value.isStruct()) { 1819 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 1820 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 1821 unsigned BaseIndex = 0; 1822 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 1823 End = CD->bases_end(); I != End; ++I, ++BaseIndex) { 1824 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1825 Value.getStructBase(BaseIndex))) 1826 return false; 1827 } 1828 } 1829 for (const auto *I : RD->fields()) { 1830 if (I->isUnnamedBitfield()) 1831 continue; 1832 1833 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1834 Value.getStructField(I->getFieldIndex()))) 1835 return false; 1836 } 1837 } 1838 1839 if (Value.isLValue()) { 1840 LValue LVal; 1841 LVal.setFrom(Info.Ctx, Value); 1842 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal); 1843 } 1844 1845 if (Value.isMemberPointer()) 1846 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value); 1847 1848 // Everything else is fine. 1849 return true; 1850 } 1851 1852 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1853 return LVal.Base.dyn_cast<const ValueDecl*>(); 1854 } 1855 1856 static bool IsLiteralLValue(const LValue &Value) { 1857 if (Value.CallIndex) 1858 return false; 1859 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1860 return E && !isa<MaterializeTemporaryExpr>(E); 1861 } 1862 1863 static bool IsWeakLValue(const LValue &Value) { 1864 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1865 return Decl && Decl->isWeak(); 1866 } 1867 1868 static bool isZeroSized(const LValue &Value) { 1869 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1870 if (Decl && isa<VarDecl>(Decl)) { 1871 QualType Ty = Decl->getType(); 1872 if (Ty->isArrayType()) 1873 return Ty->isIncompleteType() || 1874 Decl->getASTContext().getTypeSize(Ty) == 0; 1875 } 1876 return false; 1877 } 1878 1879 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 1880 // A null base expression indicates a null pointer. These are always 1881 // evaluatable, and they are false unless the offset is zero. 1882 if (!Value.getLValueBase()) { 1883 Result = !Value.getLValueOffset().isZero(); 1884 return true; 1885 } 1886 1887 // We have a non-null base. These are generally known to be true, but if it's 1888 // a weak declaration it can be null at runtime. 1889 Result = true; 1890 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 1891 return !Decl || !Decl->isWeak(); 1892 } 1893 1894 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 1895 switch (Val.getKind()) { 1896 case APValue::Uninitialized: 1897 return false; 1898 case APValue::Int: 1899 Result = Val.getInt().getBoolValue(); 1900 return true; 1901 case APValue::Float: 1902 Result = !Val.getFloat().isZero(); 1903 return true; 1904 case APValue::ComplexInt: 1905 Result = Val.getComplexIntReal().getBoolValue() || 1906 Val.getComplexIntImag().getBoolValue(); 1907 return true; 1908 case APValue::ComplexFloat: 1909 Result = !Val.getComplexFloatReal().isZero() || 1910 !Val.getComplexFloatImag().isZero(); 1911 return true; 1912 case APValue::LValue: 1913 return EvalPointerValueAsBool(Val, Result); 1914 case APValue::MemberPointer: 1915 Result = Val.getMemberPointerDecl(); 1916 return true; 1917 case APValue::Vector: 1918 case APValue::Array: 1919 case APValue::Struct: 1920 case APValue::Union: 1921 case APValue::AddrLabelDiff: 1922 return false; 1923 } 1924 1925 llvm_unreachable("unknown APValue kind"); 1926 } 1927 1928 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 1929 EvalInfo &Info) { 1930 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 1931 APValue Val; 1932 if (!Evaluate(Val, Info, E)) 1933 return false; 1934 return HandleConversionToBool(Val, Result); 1935 } 1936 1937 template<typename T> 1938 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 1939 const T &SrcValue, QualType DestType) { 1940 Info.CCEDiag(E, diag::note_constexpr_overflow) 1941 << SrcValue << DestType; 1942 return Info.noteUndefinedBehavior(); 1943 } 1944 1945 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 1946 QualType SrcType, const APFloat &Value, 1947 QualType DestType, APSInt &Result) { 1948 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 1949 // Determine whether we are converting to unsigned or signed. 1950 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 1951 1952 Result = APSInt(DestWidth, !DestSigned); 1953 bool ignored; 1954 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 1955 & APFloat::opInvalidOp) 1956 return HandleOverflow(Info, E, Value, DestType); 1957 return true; 1958 } 1959 1960 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 1961 QualType SrcType, QualType DestType, 1962 APFloat &Result) { 1963 APFloat Value = Result; 1964 bool ignored; 1965 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 1966 APFloat::rmNearestTiesToEven, &ignored) 1967 & APFloat::opOverflow) 1968 return HandleOverflow(Info, E, Value, DestType); 1969 return true; 1970 } 1971 1972 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 1973 QualType DestType, QualType SrcType, 1974 const APSInt &Value) { 1975 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 1976 APSInt Result = Value; 1977 // Figure out if this is a truncate, extend or noop cast. 1978 // If the input is signed, do a sign extend, noop, or truncate. 1979 Result = Result.extOrTrunc(DestWidth); 1980 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 1981 return Result; 1982 } 1983 1984 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 1985 QualType SrcType, const APSInt &Value, 1986 QualType DestType, APFloat &Result) { 1987 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 1988 if (Result.convertFromAPInt(Value, Value.isSigned(), 1989 APFloat::rmNearestTiesToEven) 1990 & APFloat::opOverflow) 1991 return HandleOverflow(Info, E, Value, DestType); 1992 return true; 1993 } 1994 1995 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 1996 APValue &Value, const FieldDecl *FD) { 1997 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 1998 1999 if (!Value.isInt()) { 2000 // Trying to store a pointer-cast-to-integer into a bitfield. 2001 // FIXME: In this case, we should provide the diagnostic for casting 2002 // a pointer to an integer. 2003 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2004 Info.FFDiag(E); 2005 return false; 2006 } 2007 2008 APSInt &Int = Value.getInt(); 2009 unsigned OldBitWidth = Int.getBitWidth(); 2010 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2011 if (NewBitWidth < OldBitWidth) 2012 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2013 return true; 2014 } 2015 2016 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2017 llvm::APInt &Res) { 2018 APValue SVal; 2019 if (!Evaluate(SVal, Info, E)) 2020 return false; 2021 if (SVal.isInt()) { 2022 Res = SVal.getInt(); 2023 return true; 2024 } 2025 if (SVal.isFloat()) { 2026 Res = SVal.getFloat().bitcastToAPInt(); 2027 return true; 2028 } 2029 if (SVal.isVector()) { 2030 QualType VecTy = E->getType(); 2031 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2032 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2033 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2034 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2035 Res = llvm::APInt::getNullValue(VecSize); 2036 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2037 APValue &Elt = SVal.getVectorElt(i); 2038 llvm::APInt EltAsInt; 2039 if (Elt.isInt()) { 2040 EltAsInt = Elt.getInt(); 2041 } else if (Elt.isFloat()) { 2042 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2043 } else { 2044 // Don't try to handle vectors of anything other than int or float 2045 // (not sure if it's possible to hit this case). 2046 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2047 return false; 2048 } 2049 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2050 if (BigEndian) 2051 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2052 else 2053 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2054 } 2055 return true; 2056 } 2057 // Give up if the input isn't an int, float, or vector. For example, we 2058 // reject "(v4i16)(intptr_t)&a". 2059 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2060 return false; 2061 } 2062 2063 /// Perform the given integer operation, which is known to need at most BitWidth 2064 /// bits, and check for overflow in the original type (if that type was not an 2065 /// unsigned type). 2066 template<typename Operation> 2067 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2068 const APSInt &LHS, const APSInt &RHS, 2069 unsigned BitWidth, Operation Op, 2070 APSInt &Result) { 2071 if (LHS.isUnsigned()) { 2072 Result = Op(LHS, RHS); 2073 return true; 2074 } 2075 2076 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2077 Result = Value.trunc(LHS.getBitWidth()); 2078 if (Result.extend(BitWidth) != Value) { 2079 if (Info.checkingForOverflow()) 2080 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2081 diag::warn_integer_constant_overflow) 2082 << Result.toString(10) << E->getType(); 2083 else 2084 return HandleOverflow(Info, E, Value, E->getType()); 2085 } 2086 return true; 2087 } 2088 2089 /// Perform the given binary integer operation. 2090 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2091 BinaryOperatorKind Opcode, APSInt RHS, 2092 APSInt &Result) { 2093 switch (Opcode) { 2094 default: 2095 Info.FFDiag(E); 2096 return false; 2097 case BO_Mul: 2098 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2099 std::multiplies<APSInt>(), Result); 2100 case BO_Add: 2101 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2102 std::plus<APSInt>(), Result); 2103 case BO_Sub: 2104 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2105 std::minus<APSInt>(), Result); 2106 case BO_And: Result = LHS & RHS; return true; 2107 case BO_Xor: Result = LHS ^ RHS; return true; 2108 case BO_Or: Result = LHS | RHS; return true; 2109 case BO_Div: 2110 case BO_Rem: 2111 if (RHS == 0) { 2112 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2113 return false; 2114 } 2115 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2116 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2117 // this operation and gives the two's complement result. 2118 if (RHS.isNegative() && RHS.isAllOnesValue() && 2119 LHS.isSigned() && LHS.isMinSignedValue()) 2120 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2121 E->getType()); 2122 return true; 2123 case BO_Shl: { 2124 if (Info.getLangOpts().OpenCL) 2125 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2126 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2127 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2128 RHS.isUnsigned()); 2129 else if (RHS.isSigned() && RHS.isNegative()) { 2130 // During constant-folding, a negative shift is an opposite shift. Such 2131 // a shift is not a constant expression. 2132 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2133 RHS = -RHS; 2134 goto shift_right; 2135 } 2136 shift_left: 2137 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2138 // the shifted type. 2139 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2140 if (SA != RHS) { 2141 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2142 << RHS << E->getType() << LHS.getBitWidth(); 2143 } else if (LHS.isSigned()) { 2144 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2145 // operand, and must not overflow the corresponding unsigned type. 2146 if (LHS.isNegative()) 2147 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2148 else if (LHS.countLeadingZeros() < SA) 2149 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2150 } 2151 Result = LHS << SA; 2152 return true; 2153 } 2154 case BO_Shr: { 2155 if (Info.getLangOpts().OpenCL) 2156 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2157 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2158 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2159 RHS.isUnsigned()); 2160 else if (RHS.isSigned() && RHS.isNegative()) { 2161 // During constant-folding, a negative shift is an opposite shift. Such a 2162 // shift is not a constant expression. 2163 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2164 RHS = -RHS; 2165 goto shift_left; 2166 } 2167 shift_right: 2168 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2169 // shifted type. 2170 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2171 if (SA != RHS) 2172 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2173 << RHS << E->getType() << LHS.getBitWidth(); 2174 Result = LHS >> SA; 2175 return true; 2176 } 2177 2178 case BO_LT: Result = LHS < RHS; return true; 2179 case BO_GT: Result = LHS > RHS; return true; 2180 case BO_LE: Result = LHS <= RHS; return true; 2181 case BO_GE: Result = LHS >= RHS; return true; 2182 case BO_EQ: Result = LHS == RHS; return true; 2183 case BO_NE: Result = LHS != RHS; return true; 2184 } 2185 } 2186 2187 /// Perform the given binary floating-point operation, in-place, on LHS. 2188 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2189 APFloat &LHS, BinaryOperatorKind Opcode, 2190 const APFloat &RHS) { 2191 switch (Opcode) { 2192 default: 2193 Info.FFDiag(E); 2194 return false; 2195 case BO_Mul: 2196 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2197 break; 2198 case BO_Add: 2199 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2200 break; 2201 case BO_Sub: 2202 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2203 break; 2204 case BO_Div: 2205 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2206 break; 2207 } 2208 2209 if (LHS.isInfinity() || LHS.isNaN()) { 2210 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2211 return Info.noteUndefinedBehavior(); 2212 } 2213 return true; 2214 } 2215 2216 /// Cast an lvalue referring to a base subobject to a derived class, by 2217 /// truncating the lvalue's path to the given length. 2218 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2219 const RecordDecl *TruncatedType, 2220 unsigned TruncatedElements) { 2221 SubobjectDesignator &D = Result.Designator; 2222 2223 // Check we actually point to a derived class object. 2224 if (TruncatedElements == D.Entries.size()) 2225 return true; 2226 assert(TruncatedElements >= D.MostDerivedPathLength && 2227 "not casting to a derived class"); 2228 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2229 return false; 2230 2231 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2232 const RecordDecl *RD = TruncatedType; 2233 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2234 if (RD->isInvalidDecl()) return false; 2235 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2236 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2237 if (isVirtualBaseClass(D.Entries[I])) 2238 Result.Offset -= Layout.getVBaseClassOffset(Base); 2239 else 2240 Result.Offset -= Layout.getBaseClassOffset(Base); 2241 RD = Base; 2242 } 2243 D.Entries.resize(TruncatedElements); 2244 return true; 2245 } 2246 2247 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2248 const CXXRecordDecl *Derived, 2249 const CXXRecordDecl *Base, 2250 const ASTRecordLayout *RL = nullptr) { 2251 if (!RL) { 2252 if (Derived->isInvalidDecl()) return false; 2253 RL = &Info.Ctx.getASTRecordLayout(Derived); 2254 } 2255 2256 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2257 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2258 return true; 2259 } 2260 2261 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2262 const CXXRecordDecl *DerivedDecl, 2263 const CXXBaseSpecifier *Base) { 2264 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2265 2266 if (!Base->isVirtual()) 2267 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2268 2269 SubobjectDesignator &D = Obj.Designator; 2270 if (D.Invalid) 2271 return false; 2272 2273 // Extract most-derived object and corresponding type. 2274 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2275 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2276 return false; 2277 2278 // Find the virtual base class. 2279 if (DerivedDecl->isInvalidDecl()) return false; 2280 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2281 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2282 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2283 return true; 2284 } 2285 2286 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2287 QualType Type, LValue &Result) { 2288 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2289 PathE = E->path_end(); 2290 PathI != PathE; ++PathI) { 2291 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2292 *PathI)) 2293 return false; 2294 Type = (*PathI)->getType(); 2295 } 2296 return true; 2297 } 2298 2299 /// Update LVal to refer to the given field, which must be a member of the type 2300 /// currently described by LVal. 2301 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2302 const FieldDecl *FD, 2303 const ASTRecordLayout *RL = nullptr) { 2304 if (!RL) { 2305 if (FD->getParent()->isInvalidDecl()) return false; 2306 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2307 } 2308 2309 unsigned I = FD->getFieldIndex(); 2310 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2311 LVal.addDecl(Info, E, FD); 2312 return true; 2313 } 2314 2315 /// Update LVal to refer to the given indirect field. 2316 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2317 LValue &LVal, 2318 const IndirectFieldDecl *IFD) { 2319 for (const auto *C : IFD->chain()) 2320 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2321 return false; 2322 return true; 2323 } 2324 2325 /// Get the size of the given type in char units. 2326 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2327 QualType Type, CharUnits &Size) { 2328 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2329 // extension. 2330 if (Type->isVoidType() || Type->isFunctionType()) { 2331 Size = CharUnits::One(); 2332 return true; 2333 } 2334 2335 if (Type->isDependentType()) { 2336 Info.FFDiag(Loc); 2337 return false; 2338 } 2339 2340 if (!Type->isConstantSizeType()) { 2341 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2342 // FIXME: Better diagnostic. 2343 Info.FFDiag(Loc); 2344 return false; 2345 } 2346 2347 Size = Info.Ctx.getTypeSizeInChars(Type); 2348 return true; 2349 } 2350 2351 /// Update a pointer value to model pointer arithmetic. 2352 /// \param Info - Information about the ongoing evaluation. 2353 /// \param E - The expression being evaluated, for diagnostic purposes. 2354 /// \param LVal - The pointer value to be updated. 2355 /// \param EltTy - The pointee type represented by LVal. 2356 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2357 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2358 LValue &LVal, QualType EltTy, 2359 APSInt Adjustment) { 2360 CharUnits SizeOfPointee; 2361 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2362 return false; 2363 2364 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2365 return true; 2366 } 2367 2368 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2369 LValue &LVal, QualType EltTy, 2370 int64_t Adjustment) { 2371 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2372 APSInt::get(Adjustment)); 2373 } 2374 2375 /// Update an lvalue to refer to a component of a complex number. 2376 /// \param Info - Information about the ongoing evaluation. 2377 /// \param LVal - The lvalue to be updated. 2378 /// \param EltTy - The complex number's component type. 2379 /// \param Imag - False for the real component, true for the imaginary. 2380 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2381 LValue &LVal, QualType EltTy, 2382 bool Imag) { 2383 if (Imag) { 2384 CharUnits SizeOfComponent; 2385 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2386 return false; 2387 LVal.Offset += SizeOfComponent; 2388 } 2389 LVal.addComplex(Info, E, EltTy, Imag); 2390 return true; 2391 } 2392 2393 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 2394 QualType Type, const LValue &LVal, 2395 APValue &RVal); 2396 2397 /// Try to evaluate the initializer for a variable declaration. 2398 /// 2399 /// \param Info Information about the ongoing evaluation. 2400 /// \param E An expression to be used when printing diagnostics. 2401 /// \param VD The variable whose initializer should be obtained. 2402 /// \param Frame The frame in which the variable was created. Must be null 2403 /// if this variable is not local to the evaluation. 2404 /// \param Result Filled in with a pointer to the value of the variable. 2405 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2406 const VarDecl *VD, CallStackFrame *Frame, 2407 APValue *&Result) { 2408 2409 // If this is a parameter to an active constexpr function call, perform 2410 // argument substitution. 2411 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2412 // Assume arguments of a potential constant expression are unknown 2413 // constant expressions. 2414 if (Info.checkingPotentialConstantExpression()) 2415 return false; 2416 if (!Frame || !Frame->Arguments) { 2417 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2418 return false; 2419 } 2420 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2421 return true; 2422 } 2423 2424 // If this is a local variable, dig out its value. 2425 if (Frame) { 2426 Result = Frame->getTemporary(VD); 2427 if (!Result) { 2428 // Assume variables referenced within a lambda's call operator that were 2429 // not declared within the call operator are captures and during checking 2430 // of a potential constant expression, assume they are unknown constant 2431 // expressions. 2432 assert(isLambdaCallOperator(Frame->Callee) && 2433 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2434 "missing value for local variable"); 2435 if (Info.checkingPotentialConstantExpression()) 2436 return false; 2437 // FIXME: implement capture evaluation during constant expr evaluation. 2438 Info.FFDiag(E->getLocStart(), 2439 diag::note_unimplemented_constexpr_lambda_feature_ast) 2440 << "captures not currently allowed"; 2441 return false; 2442 } 2443 return true; 2444 } 2445 2446 // Dig out the initializer, and use the declaration which it's attached to. 2447 const Expr *Init = VD->getAnyInitializer(VD); 2448 if (!Init || Init->isValueDependent()) { 2449 // If we're checking a potential constant expression, the variable could be 2450 // initialized later. 2451 if (!Info.checkingPotentialConstantExpression()) 2452 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2453 return false; 2454 } 2455 2456 // If we're currently evaluating the initializer of this declaration, use that 2457 // in-flight value. 2458 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2459 Result = Info.EvaluatingDeclValue; 2460 return true; 2461 } 2462 2463 // Never evaluate the initializer of a weak variable. We can't be sure that 2464 // this is the definition which will be used. 2465 if (VD->isWeak()) { 2466 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2467 return false; 2468 } 2469 2470 // Check that we can fold the initializer. In C++, we will have already done 2471 // this in the cases where it matters for conformance. 2472 SmallVector<PartialDiagnosticAt, 8> Notes; 2473 if (!VD->evaluateValue(Notes)) { 2474 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2475 Notes.size() + 1) << VD; 2476 Info.Note(VD->getLocation(), diag::note_declared_at); 2477 Info.addNotes(Notes); 2478 return false; 2479 } else if (!VD->checkInitIsICE()) { 2480 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2481 Notes.size() + 1) << VD; 2482 Info.Note(VD->getLocation(), diag::note_declared_at); 2483 Info.addNotes(Notes); 2484 } 2485 2486 Result = VD->getEvaluatedValue(); 2487 return true; 2488 } 2489 2490 static bool IsConstNonVolatile(QualType T) { 2491 Qualifiers Quals = T.getQualifiers(); 2492 return Quals.hasConst() && !Quals.hasVolatile(); 2493 } 2494 2495 /// Get the base index of the given base class within an APValue representing 2496 /// the given derived class. 2497 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2498 const CXXRecordDecl *Base) { 2499 Base = Base->getCanonicalDecl(); 2500 unsigned Index = 0; 2501 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2502 E = Derived->bases_end(); I != E; ++I, ++Index) { 2503 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2504 return Index; 2505 } 2506 2507 llvm_unreachable("base class missing from derived class's bases list"); 2508 } 2509 2510 /// Extract the value of a character from a string literal. 2511 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2512 uint64_t Index) { 2513 // FIXME: Support MakeStringConstant 2514 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2515 std::string Str; 2516 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2517 assert(Index <= Str.size() && "Index too large"); 2518 return APSInt::getUnsigned(Str.c_str()[Index]); 2519 } 2520 2521 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2522 Lit = PE->getFunctionName(); 2523 const StringLiteral *S = cast<StringLiteral>(Lit); 2524 const ConstantArrayType *CAT = 2525 Info.Ctx.getAsConstantArrayType(S->getType()); 2526 assert(CAT && "string literal isn't an array"); 2527 QualType CharType = CAT->getElementType(); 2528 assert(CharType->isIntegerType() && "unexpected character type"); 2529 2530 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2531 CharType->isUnsignedIntegerType()); 2532 if (Index < S->getLength()) 2533 Value = S->getCodeUnit(Index); 2534 return Value; 2535 } 2536 2537 // Expand a string literal into an array of characters. 2538 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit, 2539 APValue &Result) { 2540 const StringLiteral *S = cast<StringLiteral>(Lit); 2541 const ConstantArrayType *CAT = 2542 Info.Ctx.getAsConstantArrayType(S->getType()); 2543 assert(CAT && "string literal isn't an array"); 2544 QualType CharType = CAT->getElementType(); 2545 assert(CharType->isIntegerType() && "unexpected character type"); 2546 2547 unsigned Elts = CAT->getSize().getZExtValue(); 2548 Result = APValue(APValue::UninitArray(), 2549 std::min(S->getLength(), Elts), Elts); 2550 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2551 CharType->isUnsignedIntegerType()); 2552 if (Result.hasArrayFiller()) 2553 Result.getArrayFiller() = APValue(Value); 2554 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2555 Value = S->getCodeUnit(I); 2556 Result.getArrayInitializedElt(I) = APValue(Value); 2557 } 2558 } 2559 2560 // Expand an array so that it has more than Index filled elements. 2561 static void expandArray(APValue &Array, unsigned Index) { 2562 unsigned Size = Array.getArraySize(); 2563 assert(Index < Size); 2564 2565 // Always at least double the number of elements for which we store a value. 2566 unsigned OldElts = Array.getArrayInitializedElts(); 2567 unsigned NewElts = std::max(Index+1, OldElts * 2); 2568 NewElts = std::min(Size, std::max(NewElts, 8u)); 2569 2570 // Copy the data across. 2571 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2572 for (unsigned I = 0; I != OldElts; ++I) 2573 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2574 for (unsigned I = OldElts; I != NewElts; ++I) 2575 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2576 if (NewValue.hasArrayFiller()) 2577 NewValue.getArrayFiller() = Array.getArrayFiller(); 2578 Array.swap(NewValue); 2579 } 2580 2581 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2582 /// conversion. If it's of class type, we may assume that the copy operation 2583 /// is trivial. Note that this is never true for a union type with fields 2584 /// (because the copy always "reads" the active member) and always true for 2585 /// a non-class type. 2586 static bool isReadByLvalueToRvalueConversion(QualType T) { 2587 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2588 if (!RD || (RD->isUnion() && !RD->field_empty())) 2589 return true; 2590 if (RD->isEmpty()) 2591 return false; 2592 2593 for (auto *Field : RD->fields()) 2594 if (isReadByLvalueToRvalueConversion(Field->getType())) 2595 return true; 2596 2597 for (auto &BaseSpec : RD->bases()) 2598 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2599 return true; 2600 2601 return false; 2602 } 2603 2604 /// Diagnose an attempt to read from any unreadable field within the specified 2605 /// type, which might be a class type. 2606 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2607 QualType T) { 2608 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2609 if (!RD) 2610 return false; 2611 2612 if (!RD->hasMutableFields()) 2613 return false; 2614 2615 for (auto *Field : RD->fields()) { 2616 // If we're actually going to read this field in some way, then it can't 2617 // be mutable. If we're in a union, then assigning to a mutable field 2618 // (even an empty one) can change the active member, so that's not OK. 2619 // FIXME: Add core issue number for the union case. 2620 if (Field->isMutable() && 2621 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2622 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2623 Info.Note(Field->getLocation(), diag::note_declared_at); 2624 return true; 2625 } 2626 2627 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2628 return true; 2629 } 2630 2631 for (auto &BaseSpec : RD->bases()) 2632 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2633 return true; 2634 2635 // All mutable fields were empty, and thus not actually read. 2636 return false; 2637 } 2638 2639 /// Kinds of access we can perform on an object, for diagnostics. 2640 enum AccessKinds { 2641 AK_Read, 2642 AK_Assign, 2643 AK_Increment, 2644 AK_Decrement 2645 }; 2646 2647 namespace { 2648 /// A handle to a complete object (an object that is not a subobject of 2649 /// another object). 2650 struct CompleteObject { 2651 /// The value of the complete object. 2652 APValue *Value; 2653 /// The type of the complete object. 2654 QualType Type; 2655 2656 CompleteObject() : Value(nullptr) {} 2657 CompleteObject(APValue *Value, QualType Type) 2658 : Value(Value), Type(Type) { 2659 assert(Value && "missing value for complete object"); 2660 } 2661 2662 explicit operator bool() const { return Value; } 2663 }; 2664 } // end anonymous namespace 2665 2666 /// Find the designated sub-object of an rvalue. 2667 template<typename SubobjectHandler> 2668 typename SubobjectHandler::result_type 2669 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2670 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2671 if (Sub.Invalid) 2672 // A diagnostic will have already been produced. 2673 return handler.failed(); 2674 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 2675 if (Info.getLangOpts().CPlusPlus11) 2676 Info.FFDiag(E, Sub.isOnePastTheEnd() 2677 ? diag::note_constexpr_access_past_end 2678 : diag::note_constexpr_access_unsized_array) 2679 << handler.AccessKind; 2680 else 2681 Info.FFDiag(E); 2682 return handler.failed(); 2683 } 2684 2685 APValue *O = Obj.Value; 2686 QualType ObjType = Obj.Type; 2687 const FieldDecl *LastField = nullptr; 2688 2689 // Walk the designator's path to find the subobject. 2690 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 2691 if (O->isUninit()) { 2692 if (!Info.checkingPotentialConstantExpression()) 2693 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind; 2694 return handler.failed(); 2695 } 2696 2697 if (I == N) { 2698 // If we are reading an object of class type, there may still be more 2699 // things we need to check: if there are any mutable subobjects, we 2700 // cannot perform this read. (This only happens when performing a trivial 2701 // copy or assignment.) 2702 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 2703 diagnoseUnreadableFields(Info, E, ObjType)) 2704 return handler.failed(); 2705 2706 if (!handler.found(*O, ObjType)) 2707 return false; 2708 2709 // If we modified a bit-field, truncate it to the right width. 2710 if (handler.AccessKind != AK_Read && 2711 LastField && LastField->isBitField() && 2712 !truncateBitfieldValue(Info, E, *O, LastField)) 2713 return false; 2714 2715 return true; 2716 } 2717 2718 LastField = nullptr; 2719 if (ObjType->isArrayType()) { 2720 // Next subobject is an array element. 2721 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 2722 assert(CAT && "vla in literal type?"); 2723 uint64_t Index = Sub.Entries[I].ArrayIndex; 2724 if (CAT->getSize().ule(Index)) { 2725 // Note, it should not be possible to form a pointer with a valid 2726 // designator which points more than one past the end of the array. 2727 if (Info.getLangOpts().CPlusPlus11) 2728 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2729 << handler.AccessKind; 2730 else 2731 Info.FFDiag(E); 2732 return handler.failed(); 2733 } 2734 2735 ObjType = CAT->getElementType(); 2736 2737 // An array object is represented as either an Array APValue or as an 2738 // LValue which refers to a string literal. 2739 if (O->isLValue()) { 2740 assert(I == N - 1 && "extracting subobject of character?"); 2741 assert(!O->hasLValuePath() || O->getLValuePath().empty()); 2742 if (handler.AccessKind != AK_Read) 2743 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(), 2744 *O); 2745 else 2746 return handler.foundString(*O, ObjType, Index); 2747 } 2748 2749 if (O->getArrayInitializedElts() > Index) 2750 O = &O->getArrayInitializedElt(Index); 2751 else if (handler.AccessKind != AK_Read) { 2752 expandArray(*O, Index); 2753 O = &O->getArrayInitializedElt(Index); 2754 } else 2755 O = &O->getArrayFiller(); 2756 } else if (ObjType->isAnyComplexType()) { 2757 // Next subobject is a complex number. 2758 uint64_t Index = Sub.Entries[I].ArrayIndex; 2759 if (Index > 1) { 2760 if (Info.getLangOpts().CPlusPlus11) 2761 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2762 << handler.AccessKind; 2763 else 2764 Info.FFDiag(E); 2765 return handler.failed(); 2766 } 2767 2768 bool WasConstQualified = ObjType.isConstQualified(); 2769 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2770 if (WasConstQualified) 2771 ObjType.addConst(); 2772 2773 assert(I == N - 1 && "extracting subobject of scalar?"); 2774 if (O->isComplexInt()) { 2775 return handler.found(Index ? O->getComplexIntImag() 2776 : O->getComplexIntReal(), ObjType); 2777 } else { 2778 assert(O->isComplexFloat()); 2779 return handler.found(Index ? O->getComplexFloatImag() 2780 : O->getComplexFloatReal(), ObjType); 2781 } 2782 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 2783 if (Field->isMutable() && handler.AccessKind == AK_Read) { 2784 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 2785 << Field; 2786 Info.Note(Field->getLocation(), diag::note_declared_at); 2787 return handler.failed(); 2788 } 2789 2790 // Next subobject is a class, struct or union field. 2791 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 2792 if (RD->isUnion()) { 2793 const FieldDecl *UnionField = O->getUnionField(); 2794 if (!UnionField || 2795 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 2796 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 2797 << handler.AccessKind << Field << !UnionField << UnionField; 2798 return handler.failed(); 2799 } 2800 O = &O->getUnionValue(); 2801 } else 2802 O = &O->getStructField(Field->getFieldIndex()); 2803 2804 bool WasConstQualified = ObjType.isConstQualified(); 2805 ObjType = Field->getType(); 2806 if (WasConstQualified && !Field->isMutable()) 2807 ObjType.addConst(); 2808 2809 if (ObjType.isVolatileQualified()) { 2810 if (Info.getLangOpts().CPlusPlus) { 2811 // FIXME: Include a description of the path to the volatile subobject. 2812 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2813 << handler.AccessKind << 2 << Field; 2814 Info.Note(Field->getLocation(), diag::note_declared_at); 2815 } else { 2816 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2817 } 2818 return handler.failed(); 2819 } 2820 2821 LastField = Field; 2822 } else { 2823 // Next subobject is a base class. 2824 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 2825 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 2826 O = &O->getStructBase(getBaseIndex(Derived, Base)); 2827 2828 bool WasConstQualified = ObjType.isConstQualified(); 2829 ObjType = Info.Ctx.getRecordType(Base); 2830 if (WasConstQualified) 2831 ObjType.addConst(); 2832 } 2833 } 2834 } 2835 2836 namespace { 2837 struct ExtractSubobjectHandler { 2838 EvalInfo &Info; 2839 APValue &Result; 2840 2841 static const AccessKinds AccessKind = AK_Read; 2842 2843 typedef bool result_type; 2844 bool failed() { return false; } 2845 bool found(APValue &Subobj, QualType SubobjType) { 2846 Result = Subobj; 2847 return true; 2848 } 2849 bool found(APSInt &Value, QualType SubobjType) { 2850 Result = APValue(Value); 2851 return true; 2852 } 2853 bool found(APFloat &Value, QualType SubobjType) { 2854 Result = APValue(Value); 2855 return true; 2856 } 2857 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2858 Result = APValue(extractStringLiteralCharacter( 2859 Info, Subobj.getLValueBase().get<const Expr *>(), Character)); 2860 return true; 2861 } 2862 }; 2863 } // end anonymous namespace 2864 2865 const AccessKinds ExtractSubobjectHandler::AccessKind; 2866 2867 /// Extract the designated sub-object of an rvalue. 2868 static bool extractSubobject(EvalInfo &Info, const Expr *E, 2869 const CompleteObject &Obj, 2870 const SubobjectDesignator &Sub, 2871 APValue &Result) { 2872 ExtractSubobjectHandler Handler = { Info, Result }; 2873 return findSubobject(Info, E, Obj, Sub, Handler); 2874 } 2875 2876 namespace { 2877 struct ModifySubobjectHandler { 2878 EvalInfo &Info; 2879 APValue &NewVal; 2880 const Expr *E; 2881 2882 typedef bool result_type; 2883 static const AccessKinds AccessKind = AK_Assign; 2884 2885 bool checkConst(QualType QT) { 2886 // Assigning to a const object has undefined behavior. 2887 if (QT.isConstQualified()) { 2888 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 2889 return false; 2890 } 2891 return true; 2892 } 2893 2894 bool failed() { return false; } 2895 bool found(APValue &Subobj, QualType SubobjType) { 2896 if (!checkConst(SubobjType)) 2897 return false; 2898 // We've been given ownership of NewVal, so just swap it in. 2899 Subobj.swap(NewVal); 2900 return true; 2901 } 2902 bool found(APSInt &Value, QualType SubobjType) { 2903 if (!checkConst(SubobjType)) 2904 return false; 2905 if (!NewVal.isInt()) { 2906 // Maybe trying to write a cast pointer value into a complex? 2907 Info.FFDiag(E); 2908 return false; 2909 } 2910 Value = NewVal.getInt(); 2911 return true; 2912 } 2913 bool found(APFloat &Value, QualType SubobjType) { 2914 if (!checkConst(SubobjType)) 2915 return false; 2916 Value = NewVal.getFloat(); 2917 return true; 2918 } 2919 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2920 llvm_unreachable("shouldn't encounter string elements with ExpandArrays"); 2921 } 2922 }; 2923 } // end anonymous namespace 2924 2925 const AccessKinds ModifySubobjectHandler::AccessKind; 2926 2927 /// Update the designated sub-object of an rvalue to the given value. 2928 static bool modifySubobject(EvalInfo &Info, const Expr *E, 2929 const CompleteObject &Obj, 2930 const SubobjectDesignator &Sub, 2931 APValue &NewVal) { 2932 ModifySubobjectHandler Handler = { Info, NewVal, E }; 2933 return findSubobject(Info, E, Obj, Sub, Handler); 2934 } 2935 2936 /// Find the position where two subobject designators diverge, or equivalently 2937 /// the length of the common initial subsequence. 2938 static unsigned FindDesignatorMismatch(QualType ObjType, 2939 const SubobjectDesignator &A, 2940 const SubobjectDesignator &B, 2941 bool &WasArrayIndex) { 2942 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 2943 for (/**/; I != N; ++I) { 2944 if (!ObjType.isNull() && 2945 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 2946 // Next subobject is an array element. 2947 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) { 2948 WasArrayIndex = true; 2949 return I; 2950 } 2951 if (ObjType->isAnyComplexType()) 2952 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2953 else 2954 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 2955 } else { 2956 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) { 2957 WasArrayIndex = false; 2958 return I; 2959 } 2960 if (const FieldDecl *FD = getAsField(A.Entries[I])) 2961 // Next subobject is a field. 2962 ObjType = FD->getType(); 2963 else 2964 // Next subobject is a base class. 2965 ObjType = QualType(); 2966 } 2967 } 2968 WasArrayIndex = false; 2969 return I; 2970 } 2971 2972 /// Determine whether the given subobject designators refer to elements of the 2973 /// same array object. 2974 static bool AreElementsOfSameArray(QualType ObjType, 2975 const SubobjectDesignator &A, 2976 const SubobjectDesignator &B) { 2977 if (A.Entries.size() != B.Entries.size()) 2978 return false; 2979 2980 bool IsArray = A.MostDerivedIsArrayElement; 2981 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 2982 // A is a subobject of the array element. 2983 return false; 2984 2985 // If A (and B) designates an array element, the last entry will be the array 2986 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 2987 // of length 1' case, and the entire path must match. 2988 bool WasArrayIndex; 2989 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 2990 return CommonLength >= A.Entries.size() - IsArray; 2991 } 2992 2993 /// Find the complete object to which an LValue refers. 2994 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 2995 AccessKinds AK, const LValue &LVal, 2996 QualType LValType) { 2997 if (!LVal.Base) { 2998 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 2999 return CompleteObject(); 3000 } 3001 3002 CallStackFrame *Frame = nullptr; 3003 if (LVal.CallIndex) { 3004 Frame = Info.getCallFrame(LVal.CallIndex); 3005 if (!Frame) { 3006 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3007 << AK << LVal.Base.is<const ValueDecl*>(); 3008 NoteLValueLocation(Info, LVal.Base); 3009 return CompleteObject(); 3010 } 3011 } 3012 3013 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3014 // is not a constant expression (even if the object is non-volatile). We also 3015 // apply this rule to C++98, in order to conform to the expected 'volatile' 3016 // semantics. 3017 if (LValType.isVolatileQualified()) { 3018 if (Info.getLangOpts().CPlusPlus) 3019 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3020 << AK << LValType; 3021 else 3022 Info.FFDiag(E); 3023 return CompleteObject(); 3024 } 3025 3026 // Compute value storage location and type of base object. 3027 APValue *BaseVal = nullptr; 3028 QualType BaseType = getType(LVal.Base); 3029 3030 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3031 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3032 // In C++11, constexpr, non-volatile variables initialized with constant 3033 // expressions are constant expressions too. Inside constexpr functions, 3034 // parameters are constant expressions even if they're non-const. 3035 // In C++1y, objects local to a constant expression (those with a Frame) are 3036 // both readable and writable inside constant expressions. 3037 // In C, such things can also be folded, although they are not ICEs. 3038 const VarDecl *VD = dyn_cast<VarDecl>(D); 3039 if (VD) { 3040 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3041 VD = VDef; 3042 } 3043 if (!VD || VD->isInvalidDecl()) { 3044 Info.FFDiag(E); 3045 return CompleteObject(); 3046 } 3047 3048 // Accesses of volatile-qualified objects are not allowed. 3049 if (BaseType.isVolatileQualified()) { 3050 if (Info.getLangOpts().CPlusPlus) { 3051 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3052 << AK << 1 << VD; 3053 Info.Note(VD->getLocation(), diag::note_declared_at); 3054 } else { 3055 Info.FFDiag(E); 3056 } 3057 return CompleteObject(); 3058 } 3059 3060 // Unless we're looking at a local variable or argument in a constexpr call, 3061 // the variable we're reading must be const. 3062 if (!Frame) { 3063 if (Info.getLangOpts().CPlusPlus14 && 3064 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) { 3065 // OK, we can read and modify an object if we're in the process of 3066 // evaluating its initializer, because its lifetime began in this 3067 // evaluation. 3068 } else if (AK != AK_Read) { 3069 // All the remaining cases only permit reading. 3070 Info.FFDiag(E, diag::note_constexpr_modify_global); 3071 return CompleteObject(); 3072 } else if (VD->isConstexpr()) { 3073 // OK, we can read this variable. 3074 } else if (BaseType->isIntegralOrEnumerationType()) { 3075 // In OpenCL if a variable is in constant address space it is a const value. 3076 if (!(BaseType.isConstQualified() || 3077 (Info.getLangOpts().OpenCL && 3078 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3079 if (Info.getLangOpts().CPlusPlus) { 3080 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3081 Info.Note(VD->getLocation(), diag::note_declared_at); 3082 } else { 3083 Info.FFDiag(E); 3084 } 3085 return CompleteObject(); 3086 } 3087 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3088 // We support folding of const floating-point types, in order to make 3089 // static const data members of such types (supported as an extension) 3090 // more useful. 3091 if (Info.getLangOpts().CPlusPlus11) { 3092 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3093 Info.Note(VD->getLocation(), diag::note_declared_at); 3094 } else { 3095 Info.CCEDiag(E); 3096 } 3097 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3098 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3099 // Keep evaluating to see what we can do. 3100 } else { 3101 // FIXME: Allow folding of values of any literal type in all languages. 3102 if (Info.checkingPotentialConstantExpression() && 3103 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3104 // The definition of this variable could be constexpr. We can't 3105 // access it right now, but may be able to in future. 3106 } else if (Info.getLangOpts().CPlusPlus11) { 3107 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3108 Info.Note(VD->getLocation(), diag::note_declared_at); 3109 } else { 3110 Info.FFDiag(E); 3111 } 3112 return CompleteObject(); 3113 } 3114 } 3115 3116 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal)) 3117 return CompleteObject(); 3118 } else { 3119 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3120 3121 if (!Frame) { 3122 if (const MaterializeTemporaryExpr *MTE = 3123 dyn_cast<MaterializeTemporaryExpr>(Base)) { 3124 assert(MTE->getStorageDuration() == SD_Static && 3125 "should have a frame for a non-global materialized temporary"); 3126 3127 // Per C++1y [expr.const]p2: 3128 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3129 // - a [...] glvalue of integral or enumeration type that refers to 3130 // a non-volatile const object [...] 3131 // [...] 3132 // - a [...] glvalue of literal type that refers to a non-volatile 3133 // object whose lifetime began within the evaluation of e. 3134 // 3135 // C++11 misses the 'began within the evaluation of e' check and 3136 // instead allows all temporaries, including things like: 3137 // int &&r = 1; 3138 // int x = ++r; 3139 // constexpr int k = r; 3140 // Therefore we use the C++1y rules in C++11 too. 3141 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3142 const ValueDecl *ED = MTE->getExtendingDecl(); 3143 if (!(BaseType.isConstQualified() && 3144 BaseType->isIntegralOrEnumerationType()) && 3145 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 3146 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3147 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3148 return CompleteObject(); 3149 } 3150 3151 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3152 assert(BaseVal && "got reference to unevaluated temporary"); 3153 } else { 3154 Info.FFDiag(E); 3155 return CompleteObject(); 3156 } 3157 } else { 3158 BaseVal = Frame->getTemporary(Base); 3159 assert(BaseVal && "missing value for temporary"); 3160 } 3161 3162 // Volatile temporary objects cannot be accessed in constant expressions. 3163 if (BaseType.isVolatileQualified()) { 3164 if (Info.getLangOpts().CPlusPlus) { 3165 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3166 << AK << 0; 3167 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here); 3168 } else { 3169 Info.FFDiag(E); 3170 } 3171 return CompleteObject(); 3172 } 3173 } 3174 3175 // During the construction of an object, it is not yet 'const'. 3176 // FIXME: This doesn't do quite the right thing for const subobjects of the 3177 // object under construction. 3178 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) { 3179 BaseType = Info.Ctx.getCanonicalType(BaseType); 3180 BaseType.removeLocalConst(); 3181 } 3182 3183 // In C++1y, we can't safely access any mutable state when we might be 3184 // evaluating after an unmodeled side effect. 3185 // 3186 // FIXME: Not all local state is mutable. Allow local constant subobjects 3187 // to be read here (but take care with 'mutable' fields). 3188 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3189 Info.EvalStatus.HasSideEffects) || 3190 (AK != AK_Read && Info.IsSpeculativelyEvaluating)) 3191 return CompleteObject(); 3192 3193 return CompleteObject(BaseVal, BaseType); 3194 } 3195 3196 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This 3197 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3198 /// glvalue referred to by an entity of reference type. 3199 /// 3200 /// \param Info - Information about the ongoing evaluation. 3201 /// \param Conv - The expression for which we are performing the conversion. 3202 /// Used for diagnostics. 3203 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3204 /// case of a non-class type). 3205 /// \param LVal - The glvalue on which we are attempting to perform this action. 3206 /// \param RVal - The produced value will be placed here. 3207 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 3208 QualType Type, 3209 const LValue &LVal, APValue &RVal) { 3210 if (LVal.Designator.Invalid) 3211 return false; 3212 3213 // Check for special cases where there is no existing APValue to look at. 3214 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3215 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) { 3216 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3217 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3218 // initializer until now for such expressions. Such an expression can't be 3219 // an ICE in C, so this only matters for fold. 3220 if (Type.isVolatileQualified()) { 3221 Info.FFDiag(Conv); 3222 return false; 3223 } 3224 APValue Lit; 3225 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3226 return false; 3227 CompleteObject LitObj(&Lit, Base->getType()); 3228 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 3229 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3230 // We represent a string literal array as an lvalue pointing at the 3231 // corresponding expression, rather than building an array of chars. 3232 // FIXME: Support ObjCEncodeExpr, MakeStringConstant 3233 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0); 3234 CompleteObject StrObj(&Str, Base->getType()); 3235 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal); 3236 } 3237 } 3238 3239 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 3240 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 3241 } 3242 3243 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3244 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3245 QualType LValType, APValue &Val) { 3246 if (LVal.Designator.Invalid) 3247 return false; 3248 3249 if (!Info.getLangOpts().CPlusPlus14) { 3250 Info.FFDiag(E); 3251 return false; 3252 } 3253 3254 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3255 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3256 } 3257 3258 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 3259 return T->isSignedIntegerType() && 3260 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 3261 } 3262 3263 namespace { 3264 struct CompoundAssignSubobjectHandler { 3265 EvalInfo &Info; 3266 const Expr *E; 3267 QualType PromotedLHSType; 3268 BinaryOperatorKind Opcode; 3269 const APValue &RHS; 3270 3271 static const AccessKinds AccessKind = AK_Assign; 3272 3273 typedef bool result_type; 3274 3275 bool checkConst(QualType QT) { 3276 // Assigning to a const object has undefined behavior. 3277 if (QT.isConstQualified()) { 3278 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3279 return false; 3280 } 3281 return true; 3282 } 3283 3284 bool failed() { return false; } 3285 bool found(APValue &Subobj, QualType SubobjType) { 3286 switch (Subobj.getKind()) { 3287 case APValue::Int: 3288 return found(Subobj.getInt(), SubobjType); 3289 case APValue::Float: 3290 return found(Subobj.getFloat(), SubobjType); 3291 case APValue::ComplexInt: 3292 case APValue::ComplexFloat: 3293 // FIXME: Implement complex compound assignment. 3294 Info.FFDiag(E); 3295 return false; 3296 case APValue::LValue: 3297 return foundPointer(Subobj, SubobjType); 3298 default: 3299 // FIXME: can this happen? 3300 Info.FFDiag(E); 3301 return false; 3302 } 3303 } 3304 bool found(APSInt &Value, QualType SubobjType) { 3305 if (!checkConst(SubobjType)) 3306 return false; 3307 3308 if (!SubobjType->isIntegerType() || !RHS.isInt()) { 3309 // We don't support compound assignment on integer-cast-to-pointer 3310 // values. 3311 Info.FFDiag(E); 3312 return false; 3313 } 3314 3315 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType, 3316 SubobjType, Value); 3317 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3318 return false; 3319 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3320 return true; 3321 } 3322 bool found(APFloat &Value, QualType SubobjType) { 3323 return checkConst(SubobjType) && 3324 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3325 Value) && 3326 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3327 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3328 } 3329 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3330 if (!checkConst(SubobjType)) 3331 return false; 3332 3333 QualType PointeeType; 3334 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3335 PointeeType = PT->getPointeeType(); 3336 3337 if (PointeeType.isNull() || !RHS.isInt() || 3338 (Opcode != BO_Add && Opcode != BO_Sub)) { 3339 Info.FFDiag(E); 3340 return false; 3341 } 3342 3343 APSInt Offset = RHS.getInt(); 3344 if (Opcode == BO_Sub) 3345 negateAsSigned(Offset); 3346 3347 LValue LVal; 3348 LVal.setFrom(Info.Ctx, Subobj); 3349 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3350 return false; 3351 LVal.moveInto(Subobj); 3352 return true; 3353 } 3354 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3355 llvm_unreachable("shouldn't encounter string elements here"); 3356 } 3357 }; 3358 } // end anonymous namespace 3359 3360 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3361 3362 /// Perform a compound assignment of LVal <op>= RVal. 3363 static bool handleCompoundAssignment( 3364 EvalInfo &Info, const Expr *E, 3365 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3366 BinaryOperatorKind Opcode, const APValue &RVal) { 3367 if (LVal.Designator.Invalid) 3368 return false; 3369 3370 if (!Info.getLangOpts().CPlusPlus14) { 3371 Info.FFDiag(E); 3372 return false; 3373 } 3374 3375 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3376 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3377 RVal }; 3378 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3379 } 3380 3381 namespace { 3382 struct IncDecSubobjectHandler { 3383 EvalInfo &Info; 3384 const Expr *E; 3385 AccessKinds AccessKind; 3386 APValue *Old; 3387 3388 typedef bool result_type; 3389 3390 bool checkConst(QualType QT) { 3391 // Assigning to a const object has undefined behavior. 3392 if (QT.isConstQualified()) { 3393 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3394 return false; 3395 } 3396 return true; 3397 } 3398 3399 bool failed() { return false; } 3400 bool found(APValue &Subobj, QualType SubobjType) { 3401 // Stash the old value. Also clear Old, so we don't clobber it later 3402 // if we're post-incrementing a complex. 3403 if (Old) { 3404 *Old = Subobj; 3405 Old = nullptr; 3406 } 3407 3408 switch (Subobj.getKind()) { 3409 case APValue::Int: 3410 return found(Subobj.getInt(), SubobjType); 3411 case APValue::Float: 3412 return found(Subobj.getFloat(), SubobjType); 3413 case APValue::ComplexInt: 3414 return found(Subobj.getComplexIntReal(), 3415 SubobjType->castAs<ComplexType>()->getElementType() 3416 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3417 case APValue::ComplexFloat: 3418 return found(Subobj.getComplexFloatReal(), 3419 SubobjType->castAs<ComplexType>()->getElementType() 3420 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3421 case APValue::LValue: 3422 return foundPointer(Subobj, SubobjType); 3423 default: 3424 // FIXME: can this happen? 3425 Info.FFDiag(E); 3426 return false; 3427 } 3428 } 3429 bool found(APSInt &Value, QualType SubobjType) { 3430 if (!checkConst(SubobjType)) 3431 return false; 3432 3433 if (!SubobjType->isIntegerType()) { 3434 // We don't support increment / decrement on integer-cast-to-pointer 3435 // values. 3436 Info.FFDiag(E); 3437 return false; 3438 } 3439 3440 if (Old) *Old = APValue(Value); 3441 3442 // bool arithmetic promotes to int, and the conversion back to bool 3443 // doesn't reduce mod 2^n, so special-case it. 3444 if (SubobjType->isBooleanType()) { 3445 if (AccessKind == AK_Increment) 3446 Value = 1; 3447 else 3448 Value = !Value; 3449 return true; 3450 } 3451 3452 bool WasNegative = Value.isNegative(); 3453 if (AccessKind == AK_Increment) { 3454 ++Value; 3455 3456 if (!WasNegative && Value.isNegative() && 3457 isOverflowingIntegerType(Info.Ctx, SubobjType)) { 3458 APSInt ActualValue(Value, /*IsUnsigned*/true); 3459 return HandleOverflow(Info, E, ActualValue, SubobjType); 3460 } 3461 } else { 3462 --Value; 3463 3464 if (WasNegative && !Value.isNegative() && 3465 isOverflowingIntegerType(Info.Ctx, SubobjType)) { 3466 unsigned BitWidth = Value.getBitWidth(); 3467 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3468 ActualValue.setBit(BitWidth); 3469 return HandleOverflow(Info, E, ActualValue, SubobjType); 3470 } 3471 } 3472 return true; 3473 } 3474 bool found(APFloat &Value, QualType SubobjType) { 3475 if (!checkConst(SubobjType)) 3476 return false; 3477 3478 if (Old) *Old = APValue(Value); 3479 3480 APFloat One(Value.getSemantics(), 1); 3481 if (AccessKind == AK_Increment) 3482 Value.add(One, APFloat::rmNearestTiesToEven); 3483 else 3484 Value.subtract(One, APFloat::rmNearestTiesToEven); 3485 return true; 3486 } 3487 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3488 if (!checkConst(SubobjType)) 3489 return false; 3490 3491 QualType PointeeType; 3492 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3493 PointeeType = PT->getPointeeType(); 3494 else { 3495 Info.FFDiag(E); 3496 return false; 3497 } 3498 3499 LValue LVal; 3500 LVal.setFrom(Info.Ctx, Subobj); 3501 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3502 AccessKind == AK_Increment ? 1 : -1)) 3503 return false; 3504 LVal.moveInto(Subobj); 3505 return true; 3506 } 3507 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3508 llvm_unreachable("shouldn't encounter string elements here"); 3509 } 3510 }; 3511 } // end anonymous namespace 3512 3513 /// Perform an increment or decrement on LVal. 3514 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3515 QualType LValType, bool IsIncrement, APValue *Old) { 3516 if (LVal.Designator.Invalid) 3517 return false; 3518 3519 if (!Info.getLangOpts().CPlusPlus14) { 3520 Info.FFDiag(E); 3521 return false; 3522 } 3523 3524 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3525 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3526 IncDecSubobjectHandler Handler = { Info, E, AK, Old }; 3527 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3528 } 3529 3530 /// Build an lvalue for the object argument of a member function call. 3531 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3532 LValue &This) { 3533 if (Object->getType()->isPointerType()) 3534 return EvaluatePointer(Object, This, Info); 3535 3536 if (Object->isGLValue()) 3537 return EvaluateLValue(Object, This, Info); 3538 3539 if (Object->getType()->isLiteralType(Info.Ctx)) 3540 return EvaluateTemporary(Object, This, Info); 3541 3542 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3543 return false; 3544 } 3545 3546 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3547 /// lvalue referring to the result. 3548 /// 3549 /// \param Info - Information about the ongoing evaluation. 3550 /// \param LV - An lvalue referring to the base of the member pointer. 3551 /// \param RHS - The member pointer expression. 3552 /// \param IncludeMember - Specifies whether the member itself is included in 3553 /// the resulting LValue subobject designator. This is not possible when 3554 /// creating a bound member function. 3555 /// \return The field or method declaration to which the member pointer refers, 3556 /// or 0 if evaluation fails. 3557 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3558 QualType LVType, 3559 LValue &LV, 3560 const Expr *RHS, 3561 bool IncludeMember = true) { 3562 MemberPtr MemPtr; 3563 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3564 return nullptr; 3565 3566 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3567 // member value, the behavior is undefined. 3568 if (!MemPtr.getDecl()) { 3569 // FIXME: Specific diagnostic. 3570 Info.FFDiag(RHS); 3571 return nullptr; 3572 } 3573 3574 if (MemPtr.isDerivedMember()) { 3575 // This is a member of some derived class. Truncate LV appropriately. 3576 // The end of the derived-to-base path for the base object must match the 3577 // derived-to-base path for the member pointer. 3578 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3579 LV.Designator.Entries.size()) { 3580 Info.FFDiag(RHS); 3581 return nullptr; 3582 } 3583 unsigned PathLengthToMember = 3584 LV.Designator.Entries.size() - MemPtr.Path.size(); 3585 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3586 const CXXRecordDecl *LVDecl = getAsBaseClass( 3587 LV.Designator.Entries[PathLengthToMember + I]); 3588 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3589 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3590 Info.FFDiag(RHS); 3591 return nullptr; 3592 } 3593 } 3594 3595 // Truncate the lvalue to the appropriate derived class. 3596 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3597 PathLengthToMember)) 3598 return nullptr; 3599 } else if (!MemPtr.Path.empty()) { 3600 // Extend the LValue path with the member pointer's path. 3601 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3602 MemPtr.Path.size() + IncludeMember); 3603 3604 // Walk down to the appropriate base class. 3605 if (const PointerType *PT = LVType->getAs<PointerType>()) 3606 LVType = PT->getPointeeType(); 3607 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3608 assert(RD && "member pointer access on non-class-type expression"); 3609 // The first class in the path is that of the lvalue. 3610 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3611 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3612 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3613 return nullptr; 3614 RD = Base; 3615 } 3616 // Finally cast to the class containing the member. 3617 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3618 MemPtr.getContainingRecord())) 3619 return nullptr; 3620 } 3621 3622 // Add the member. Note that we cannot build bound member functions here. 3623 if (IncludeMember) { 3624 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3625 if (!HandleLValueMember(Info, RHS, LV, FD)) 3626 return nullptr; 3627 } else if (const IndirectFieldDecl *IFD = 3628 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3629 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3630 return nullptr; 3631 } else { 3632 llvm_unreachable("can't construct reference to bound member function"); 3633 } 3634 } 3635 3636 return MemPtr.getDecl(); 3637 } 3638 3639 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3640 const BinaryOperator *BO, 3641 LValue &LV, 3642 bool IncludeMember = true) { 3643 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3644 3645 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3646 if (Info.noteFailure()) { 3647 MemberPtr MemPtr; 3648 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3649 } 3650 return nullptr; 3651 } 3652 3653 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3654 BO->getRHS(), IncludeMember); 3655 } 3656 3657 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3658 /// the provided lvalue, which currently refers to the base object. 3659 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3660 LValue &Result) { 3661 SubobjectDesignator &D = Result.Designator; 3662 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3663 return false; 3664 3665 QualType TargetQT = E->getType(); 3666 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 3667 TargetQT = PT->getPointeeType(); 3668 3669 // Check this cast lands within the final derived-to-base subobject path. 3670 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 3671 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3672 << D.MostDerivedType << TargetQT; 3673 return false; 3674 } 3675 3676 // Check the type of the final cast. We don't need to check the path, 3677 // since a cast can only be formed if the path is unique. 3678 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 3679 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 3680 const CXXRecordDecl *FinalType; 3681 if (NewEntriesSize == D.MostDerivedPathLength) 3682 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 3683 else 3684 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 3685 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 3686 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3687 << D.MostDerivedType << TargetQT; 3688 return false; 3689 } 3690 3691 // Truncate the lvalue to the appropriate derived class. 3692 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 3693 } 3694 3695 namespace { 3696 enum EvalStmtResult { 3697 /// Evaluation failed. 3698 ESR_Failed, 3699 /// Hit a 'return' statement. 3700 ESR_Returned, 3701 /// Evaluation succeeded. 3702 ESR_Succeeded, 3703 /// Hit a 'continue' statement. 3704 ESR_Continue, 3705 /// Hit a 'break' statement. 3706 ESR_Break, 3707 /// Still scanning for 'case' or 'default' statement. 3708 ESR_CaseNotFound 3709 }; 3710 } 3711 3712 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 3713 // We don't need to evaluate the initializer for a static local. 3714 if (!VD->hasLocalStorage()) 3715 return true; 3716 3717 LValue Result; 3718 Result.set(VD, Info.CurrentCall->Index); 3719 APValue &Val = Info.CurrentCall->createTemporary(VD, true); 3720 3721 const Expr *InitE = VD->getInit(); 3722 if (!InitE) { 3723 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized) 3724 << false << VD->getType(); 3725 Val = APValue(); 3726 return false; 3727 } 3728 3729 if (InitE->isValueDependent()) 3730 return false; 3731 3732 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 3733 // Wipe out any partially-computed value, to allow tracking that this 3734 // evaluation failed. 3735 Val = APValue(); 3736 return false; 3737 } 3738 3739 return true; 3740 } 3741 3742 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 3743 bool OK = true; 3744 3745 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 3746 OK &= EvaluateVarDecl(Info, VD); 3747 3748 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 3749 for (auto *BD : DD->bindings()) 3750 if (auto *VD = BD->getHoldingVar()) 3751 OK &= EvaluateDecl(Info, VD); 3752 3753 return OK; 3754 } 3755 3756 3757 /// Evaluate a condition (either a variable declaration or an expression). 3758 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 3759 const Expr *Cond, bool &Result) { 3760 FullExpressionRAII Scope(Info); 3761 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 3762 return false; 3763 return EvaluateAsBooleanCondition(Cond, Result, Info); 3764 } 3765 3766 namespace { 3767 /// \brief A location where the result (returned value) of evaluating a 3768 /// statement should be stored. 3769 struct StmtResult { 3770 /// The APValue that should be filled in with the returned value. 3771 APValue &Value; 3772 /// The location containing the result, if any (used to support RVO). 3773 const LValue *Slot; 3774 }; 3775 } 3776 3777 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3778 const Stmt *S, 3779 const SwitchCase *SC = nullptr); 3780 3781 /// Evaluate the body of a loop, and translate the result as appropriate. 3782 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 3783 const Stmt *Body, 3784 const SwitchCase *Case = nullptr) { 3785 BlockScopeRAII Scope(Info); 3786 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 3787 case ESR_Break: 3788 return ESR_Succeeded; 3789 case ESR_Succeeded: 3790 case ESR_Continue: 3791 return ESR_Continue; 3792 case ESR_Failed: 3793 case ESR_Returned: 3794 case ESR_CaseNotFound: 3795 return ESR; 3796 } 3797 llvm_unreachable("Invalid EvalStmtResult!"); 3798 } 3799 3800 /// Evaluate a switch statement. 3801 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 3802 const SwitchStmt *SS) { 3803 BlockScopeRAII Scope(Info); 3804 3805 // Evaluate the switch condition. 3806 APSInt Value; 3807 { 3808 FullExpressionRAII Scope(Info); 3809 if (const Stmt *Init = SS->getInit()) { 3810 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3811 if (ESR != ESR_Succeeded) 3812 return ESR; 3813 } 3814 if (SS->getConditionVariable() && 3815 !EvaluateDecl(Info, SS->getConditionVariable())) 3816 return ESR_Failed; 3817 if (!EvaluateInteger(SS->getCond(), Value, Info)) 3818 return ESR_Failed; 3819 } 3820 3821 // Find the switch case corresponding to the value of the condition. 3822 // FIXME: Cache this lookup. 3823 const SwitchCase *Found = nullptr; 3824 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 3825 SC = SC->getNextSwitchCase()) { 3826 if (isa<DefaultStmt>(SC)) { 3827 Found = SC; 3828 continue; 3829 } 3830 3831 const CaseStmt *CS = cast<CaseStmt>(SC); 3832 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 3833 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 3834 : LHS; 3835 if (LHS <= Value && Value <= RHS) { 3836 Found = SC; 3837 break; 3838 } 3839 } 3840 3841 if (!Found) 3842 return ESR_Succeeded; 3843 3844 // Search the switch body for the switch case and evaluate it from there. 3845 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 3846 case ESR_Break: 3847 return ESR_Succeeded; 3848 case ESR_Succeeded: 3849 case ESR_Continue: 3850 case ESR_Failed: 3851 case ESR_Returned: 3852 return ESR; 3853 case ESR_CaseNotFound: 3854 // This can only happen if the switch case is nested within a statement 3855 // expression. We have no intention of supporting that. 3856 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported); 3857 return ESR_Failed; 3858 } 3859 llvm_unreachable("Invalid EvalStmtResult!"); 3860 } 3861 3862 // Evaluate a statement. 3863 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3864 const Stmt *S, const SwitchCase *Case) { 3865 if (!Info.nextStep(S)) 3866 return ESR_Failed; 3867 3868 // If we're hunting down a 'case' or 'default' label, recurse through 3869 // substatements until we hit the label. 3870 if (Case) { 3871 // FIXME: We don't start the lifetime of objects whose initialization we 3872 // jump over. However, such objects must be of class type with a trivial 3873 // default constructor that initialize all subobjects, so must be empty, 3874 // so this almost never matters. 3875 switch (S->getStmtClass()) { 3876 case Stmt::CompoundStmtClass: 3877 // FIXME: Precompute which substatement of a compound statement we 3878 // would jump to, and go straight there rather than performing a 3879 // linear scan each time. 3880 case Stmt::LabelStmtClass: 3881 case Stmt::AttributedStmtClass: 3882 case Stmt::DoStmtClass: 3883 break; 3884 3885 case Stmt::CaseStmtClass: 3886 case Stmt::DefaultStmtClass: 3887 if (Case == S) 3888 Case = nullptr; 3889 break; 3890 3891 case Stmt::IfStmtClass: { 3892 // FIXME: Precompute which side of an 'if' we would jump to, and go 3893 // straight there rather than scanning both sides. 3894 const IfStmt *IS = cast<IfStmt>(S); 3895 3896 // Wrap the evaluation in a block scope, in case it's a DeclStmt 3897 // preceded by our switch label. 3898 BlockScopeRAII Scope(Info); 3899 3900 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 3901 if (ESR != ESR_CaseNotFound || !IS->getElse()) 3902 return ESR; 3903 return EvaluateStmt(Result, Info, IS->getElse(), Case); 3904 } 3905 3906 case Stmt::WhileStmtClass: { 3907 EvalStmtResult ESR = 3908 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 3909 if (ESR != ESR_Continue) 3910 return ESR; 3911 break; 3912 } 3913 3914 case Stmt::ForStmtClass: { 3915 const ForStmt *FS = cast<ForStmt>(S); 3916 EvalStmtResult ESR = 3917 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 3918 if (ESR != ESR_Continue) 3919 return ESR; 3920 if (FS->getInc()) { 3921 FullExpressionRAII IncScope(Info); 3922 if (!EvaluateIgnoredValue(Info, FS->getInc())) 3923 return ESR_Failed; 3924 } 3925 break; 3926 } 3927 3928 case Stmt::DeclStmtClass: 3929 // FIXME: If the variable has initialization that can't be jumped over, 3930 // bail out of any immediately-surrounding compound-statement too. 3931 default: 3932 return ESR_CaseNotFound; 3933 } 3934 } 3935 3936 switch (S->getStmtClass()) { 3937 default: 3938 if (const Expr *E = dyn_cast<Expr>(S)) { 3939 // Don't bother evaluating beyond an expression-statement which couldn't 3940 // be evaluated. 3941 FullExpressionRAII Scope(Info); 3942 if (!EvaluateIgnoredValue(Info, E)) 3943 return ESR_Failed; 3944 return ESR_Succeeded; 3945 } 3946 3947 Info.FFDiag(S->getLocStart()); 3948 return ESR_Failed; 3949 3950 case Stmt::NullStmtClass: 3951 return ESR_Succeeded; 3952 3953 case Stmt::DeclStmtClass: { 3954 const DeclStmt *DS = cast<DeclStmt>(S); 3955 for (const auto *DclIt : DS->decls()) { 3956 // Each declaration initialization is its own full-expression. 3957 // FIXME: This isn't quite right; if we're performing aggregate 3958 // initialization, each braced subexpression is its own full-expression. 3959 FullExpressionRAII Scope(Info); 3960 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 3961 return ESR_Failed; 3962 } 3963 return ESR_Succeeded; 3964 } 3965 3966 case Stmt::ReturnStmtClass: { 3967 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 3968 FullExpressionRAII Scope(Info); 3969 if (RetExpr && 3970 !(Result.Slot 3971 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 3972 : Evaluate(Result.Value, Info, RetExpr))) 3973 return ESR_Failed; 3974 return ESR_Returned; 3975 } 3976 3977 case Stmt::CompoundStmtClass: { 3978 BlockScopeRAII Scope(Info); 3979 3980 const CompoundStmt *CS = cast<CompoundStmt>(S); 3981 for (const auto *BI : CS->body()) { 3982 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 3983 if (ESR == ESR_Succeeded) 3984 Case = nullptr; 3985 else if (ESR != ESR_CaseNotFound) 3986 return ESR; 3987 } 3988 return Case ? ESR_CaseNotFound : ESR_Succeeded; 3989 } 3990 3991 case Stmt::IfStmtClass: { 3992 const IfStmt *IS = cast<IfStmt>(S); 3993 3994 // Evaluate the condition, as either a var decl or as an expression. 3995 BlockScopeRAII Scope(Info); 3996 if (const Stmt *Init = IS->getInit()) { 3997 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3998 if (ESR != ESR_Succeeded) 3999 return ESR; 4000 } 4001 bool Cond; 4002 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4003 return ESR_Failed; 4004 4005 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4006 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4007 if (ESR != ESR_Succeeded) 4008 return ESR; 4009 } 4010 return ESR_Succeeded; 4011 } 4012 4013 case Stmt::WhileStmtClass: { 4014 const WhileStmt *WS = cast<WhileStmt>(S); 4015 while (true) { 4016 BlockScopeRAII Scope(Info); 4017 bool Continue; 4018 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4019 Continue)) 4020 return ESR_Failed; 4021 if (!Continue) 4022 break; 4023 4024 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4025 if (ESR != ESR_Continue) 4026 return ESR; 4027 } 4028 return ESR_Succeeded; 4029 } 4030 4031 case Stmt::DoStmtClass: { 4032 const DoStmt *DS = cast<DoStmt>(S); 4033 bool Continue; 4034 do { 4035 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4036 if (ESR != ESR_Continue) 4037 return ESR; 4038 Case = nullptr; 4039 4040 FullExpressionRAII CondScope(Info); 4041 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 4042 return ESR_Failed; 4043 } while (Continue); 4044 return ESR_Succeeded; 4045 } 4046 4047 case Stmt::ForStmtClass: { 4048 const ForStmt *FS = cast<ForStmt>(S); 4049 BlockScopeRAII Scope(Info); 4050 if (FS->getInit()) { 4051 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4052 if (ESR != ESR_Succeeded) 4053 return ESR; 4054 } 4055 while (true) { 4056 BlockScopeRAII Scope(Info); 4057 bool Continue = true; 4058 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4059 FS->getCond(), Continue)) 4060 return ESR_Failed; 4061 if (!Continue) 4062 break; 4063 4064 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4065 if (ESR != ESR_Continue) 4066 return ESR; 4067 4068 if (FS->getInc()) { 4069 FullExpressionRAII IncScope(Info); 4070 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4071 return ESR_Failed; 4072 } 4073 } 4074 return ESR_Succeeded; 4075 } 4076 4077 case Stmt::CXXForRangeStmtClass: { 4078 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4079 BlockScopeRAII Scope(Info); 4080 4081 // Initialize the __range variable. 4082 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4083 if (ESR != ESR_Succeeded) 4084 return ESR; 4085 4086 // Create the __begin and __end iterators. 4087 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4088 if (ESR != ESR_Succeeded) 4089 return ESR; 4090 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4091 if (ESR != ESR_Succeeded) 4092 return ESR; 4093 4094 while (true) { 4095 // Condition: __begin != __end. 4096 { 4097 bool Continue = true; 4098 FullExpressionRAII CondExpr(Info); 4099 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4100 return ESR_Failed; 4101 if (!Continue) 4102 break; 4103 } 4104 4105 // User's variable declaration, initialized by *__begin. 4106 BlockScopeRAII InnerScope(Info); 4107 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4108 if (ESR != ESR_Succeeded) 4109 return ESR; 4110 4111 // Loop body. 4112 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4113 if (ESR != ESR_Continue) 4114 return ESR; 4115 4116 // Increment: ++__begin 4117 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4118 return ESR_Failed; 4119 } 4120 4121 return ESR_Succeeded; 4122 } 4123 4124 case Stmt::SwitchStmtClass: 4125 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4126 4127 case Stmt::ContinueStmtClass: 4128 return ESR_Continue; 4129 4130 case Stmt::BreakStmtClass: 4131 return ESR_Break; 4132 4133 case Stmt::LabelStmtClass: 4134 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4135 4136 case Stmt::AttributedStmtClass: 4137 // As a general principle, C++11 attributes can be ignored without 4138 // any semantic impact. 4139 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4140 Case); 4141 4142 case Stmt::CaseStmtClass: 4143 case Stmt::DefaultStmtClass: 4144 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4145 } 4146 } 4147 4148 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4149 /// default constructor. If so, we'll fold it whether or not it's marked as 4150 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4151 /// so we need special handling. 4152 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4153 const CXXConstructorDecl *CD, 4154 bool IsValueInitialization) { 4155 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4156 return false; 4157 4158 // Value-initialization does not call a trivial default constructor, so such a 4159 // call is a core constant expression whether or not the constructor is 4160 // constexpr. 4161 if (!CD->isConstexpr() && !IsValueInitialization) { 4162 if (Info.getLangOpts().CPlusPlus11) { 4163 // FIXME: If DiagDecl is an implicitly-declared special member function, 4164 // we should be much more explicit about why it's not constexpr. 4165 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4166 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4167 Info.Note(CD->getLocation(), diag::note_declared_at); 4168 } else { 4169 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4170 } 4171 } 4172 return true; 4173 } 4174 4175 /// CheckConstexprFunction - Check that a function can be called in a constant 4176 /// expression. 4177 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4178 const FunctionDecl *Declaration, 4179 const FunctionDecl *Definition, 4180 const Stmt *Body) { 4181 // Potential constant expressions can contain calls to declared, but not yet 4182 // defined, constexpr functions. 4183 if (Info.checkingPotentialConstantExpression() && !Definition && 4184 Declaration->isConstexpr()) 4185 return false; 4186 4187 // Bail out with no diagnostic if the function declaration itself is invalid. 4188 // We will have produced a relevant diagnostic while parsing it. 4189 if (Declaration->isInvalidDecl()) 4190 return false; 4191 4192 // Can we evaluate this function call? 4193 if (Definition && Definition->isConstexpr() && 4194 !Definition->isInvalidDecl() && Body) 4195 return true; 4196 4197 if (Info.getLangOpts().CPlusPlus11) { 4198 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4199 4200 // If this function is not constexpr because it is an inherited 4201 // non-constexpr constructor, diagnose that directly. 4202 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4203 if (CD && CD->isInheritingConstructor()) { 4204 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4205 if (!Inherited->isConstexpr()) 4206 DiagDecl = CD = Inherited; 4207 } 4208 4209 // FIXME: If DiagDecl is an implicitly-declared special member function 4210 // or an inheriting constructor, we should be much more explicit about why 4211 // it's not constexpr. 4212 if (CD && CD->isInheritingConstructor()) 4213 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4214 << CD->getInheritedConstructor().getConstructor()->getParent(); 4215 else 4216 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4217 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4218 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4219 } else { 4220 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4221 } 4222 return false; 4223 } 4224 4225 /// Determine if a class has any fields that might need to be copied by a 4226 /// trivial copy or move operation. 4227 static bool hasFields(const CXXRecordDecl *RD) { 4228 if (!RD || RD->isEmpty()) 4229 return false; 4230 for (auto *FD : RD->fields()) { 4231 if (FD->isUnnamedBitfield()) 4232 continue; 4233 return true; 4234 } 4235 for (auto &Base : RD->bases()) 4236 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 4237 return true; 4238 return false; 4239 } 4240 4241 namespace { 4242 typedef SmallVector<APValue, 8> ArgVector; 4243 } 4244 4245 /// EvaluateArgs - Evaluate the arguments to a function call. 4246 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 4247 EvalInfo &Info) { 4248 bool Success = true; 4249 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 4250 I != E; ++I) { 4251 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 4252 // If we're checking for a potential constant expression, evaluate all 4253 // initializers even if some of them fail. 4254 if (!Info.noteFailure()) 4255 return false; 4256 Success = false; 4257 } 4258 } 4259 return Success; 4260 } 4261 4262 /// Evaluate a function call. 4263 static bool HandleFunctionCall(SourceLocation CallLoc, 4264 const FunctionDecl *Callee, const LValue *This, 4265 ArrayRef<const Expr*> Args, const Stmt *Body, 4266 EvalInfo &Info, APValue &Result, 4267 const LValue *ResultSlot) { 4268 ArgVector ArgValues(Args.size()); 4269 if (!EvaluateArgs(Args, ArgValues, Info)) 4270 return false; 4271 4272 if (!Info.CheckCallLimit(CallLoc)) 4273 return false; 4274 4275 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 4276 4277 // For a trivial copy or move assignment, perform an APValue copy. This is 4278 // essential for unions, where the operations performed by the assignment 4279 // operator cannot be represented as statements. 4280 // 4281 // Skip this for non-union classes with no fields; in that case, the defaulted 4282 // copy/move does not actually read the object. 4283 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 4284 if (MD && MD->isDefaulted() && 4285 (MD->getParent()->isUnion() || 4286 (MD->isTrivial() && hasFields(MD->getParent())))) { 4287 assert(This && 4288 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 4289 LValue RHS; 4290 RHS.setFrom(Info.Ctx, ArgValues[0]); 4291 APValue RHSValue; 4292 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 4293 RHS, RHSValue)) 4294 return false; 4295 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx), 4296 RHSValue)) 4297 return false; 4298 This->moveInto(Result); 4299 return true; 4300 } else if (MD && isLambdaCallOperator(MD)) { 4301 // We're in a lambda; determine the lambda capture field maps. 4302 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 4303 Frame.LambdaThisCaptureField); 4304 } 4305 4306 StmtResult Ret = {Result, ResultSlot}; 4307 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 4308 if (ESR == ESR_Succeeded) { 4309 if (Callee->getReturnType()->isVoidType()) 4310 return true; 4311 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return); 4312 } 4313 return ESR == ESR_Returned; 4314 } 4315 4316 /// Evaluate a constructor call. 4317 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4318 APValue *ArgValues, 4319 const CXXConstructorDecl *Definition, 4320 EvalInfo &Info, APValue &Result) { 4321 SourceLocation CallLoc = E->getExprLoc(); 4322 if (!Info.CheckCallLimit(CallLoc)) 4323 return false; 4324 4325 const CXXRecordDecl *RD = Definition->getParent(); 4326 if (RD->getNumVBases()) { 4327 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 4328 return false; 4329 } 4330 4331 EvalInfo::EvaluatingConstructorRAII EvalObj( 4332 Info, {This.getLValueBase(), This.CallIndex}); 4333 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 4334 4335 // FIXME: Creating an APValue just to hold a nonexistent return value is 4336 // wasteful. 4337 APValue RetVal; 4338 StmtResult Ret = {RetVal, nullptr}; 4339 4340 // If it's a delegating constructor, delegate. 4341 if (Definition->isDelegatingConstructor()) { 4342 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 4343 { 4344 FullExpressionRAII InitScope(Info); 4345 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 4346 return false; 4347 } 4348 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4349 } 4350 4351 // For a trivial copy or move constructor, perform an APValue copy. This is 4352 // essential for unions (or classes with anonymous union members), where the 4353 // operations performed by the constructor cannot be represented by 4354 // ctor-initializers. 4355 // 4356 // Skip this for empty non-union classes; we should not perform an 4357 // lvalue-to-rvalue conversion on them because their copy constructor does not 4358 // actually read them. 4359 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 4360 (Definition->getParent()->isUnion() || 4361 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 4362 LValue RHS; 4363 RHS.setFrom(Info.Ctx, ArgValues[0]); 4364 return handleLValueToRValueConversion( 4365 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 4366 RHS, Result); 4367 } 4368 4369 // Reserve space for the struct members. 4370 if (!RD->isUnion() && Result.isUninit()) 4371 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4372 std::distance(RD->field_begin(), RD->field_end())); 4373 4374 if (RD->isInvalidDecl()) return false; 4375 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 4376 4377 // A scope for temporaries lifetime-extended by reference members. 4378 BlockScopeRAII LifetimeExtendedScope(Info); 4379 4380 bool Success = true; 4381 unsigned BasesSeen = 0; 4382 #ifndef NDEBUG 4383 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 4384 #endif 4385 for (const auto *I : Definition->inits()) { 4386 LValue Subobject = This; 4387 APValue *Value = &Result; 4388 4389 // Determine the subobject to initialize. 4390 FieldDecl *FD = nullptr; 4391 if (I->isBaseInitializer()) { 4392 QualType BaseType(I->getBaseClass(), 0); 4393 #ifndef NDEBUG 4394 // Non-virtual base classes are initialized in the order in the class 4395 // definition. We have already checked for virtual base classes. 4396 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 4397 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 4398 "base class initializers not in expected order"); 4399 ++BaseIt; 4400 #endif 4401 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 4402 BaseType->getAsCXXRecordDecl(), &Layout)) 4403 return false; 4404 Value = &Result.getStructBase(BasesSeen++); 4405 } else if ((FD = I->getMember())) { 4406 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 4407 return false; 4408 if (RD->isUnion()) { 4409 Result = APValue(FD); 4410 Value = &Result.getUnionValue(); 4411 } else { 4412 Value = &Result.getStructField(FD->getFieldIndex()); 4413 } 4414 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 4415 // Walk the indirect field decl's chain to find the object to initialize, 4416 // and make sure we've initialized every step along it. 4417 for (auto *C : IFD->chain()) { 4418 FD = cast<FieldDecl>(C); 4419 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 4420 // Switch the union field if it differs. This happens if we had 4421 // preceding zero-initialization, and we're now initializing a union 4422 // subobject other than the first. 4423 // FIXME: In this case, the values of the other subobjects are 4424 // specified, since zero-initialization sets all padding bits to zero. 4425 if (Value->isUninit() || 4426 (Value->isUnion() && Value->getUnionField() != FD)) { 4427 if (CD->isUnion()) 4428 *Value = APValue(FD); 4429 else 4430 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 4431 std::distance(CD->field_begin(), CD->field_end())); 4432 } 4433 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 4434 return false; 4435 if (CD->isUnion()) 4436 Value = &Value->getUnionValue(); 4437 else 4438 Value = &Value->getStructField(FD->getFieldIndex()); 4439 } 4440 } else { 4441 llvm_unreachable("unknown base initializer kind"); 4442 } 4443 4444 FullExpressionRAII InitScope(Info); 4445 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) || 4446 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(), 4447 *Value, FD))) { 4448 // If we're checking for a potential constant expression, evaluate all 4449 // initializers even if some of them fail. 4450 if (!Info.noteFailure()) 4451 return false; 4452 Success = false; 4453 } 4454 } 4455 4456 return Success && 4457 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4458 } 4459 4460 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4461 ArrayRef<const Expr*> Args, 4462 const CXXConstructorDecl *Definition, 4463 EvalInfo &Info, APValue &Result) { 4464 ArgVector ArgValues(Args.size()); 4465 if (!EvaluateArgs(Args, ArgValues, Info)) 4466 return false; 4467 4468 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 4469 Info, Result); 4470 } 4471 4472 //===----------------------------------------------------------------------===// 4473 // Generic Evaluation 4474 //===----------------------------------------------------------------------===// 4475 namespace { 4476 4477 template <class Derived> 4478 class ExprEvaluatorBase 4479 : public ConstStmtVisitor<Derived, bool> { 4480 private: 4481 Derived &getDerived() { return static_cast<Derived&>(*this); } 4482 bool DerivedSuccess(const APValue &V, const Expr *E) { 4483 return getDerived().Success(V, E); 4484 } 4485 bool DerivedZeroInitialization(const Expr *E) { 4486 return getDerived().ZeroInitialization(E); 4487 } 4488 4489 // Check whether a conditional operator with a non-constant condition is a 4490 // potential constant expression. If neither arm is a potential constant 4491 // expression, then the conditional operator is not either. 4492 template<typename ConditionalOperator> 4493 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 4494 assert(Info.checkingPotentialConstantExpression()); 4495 4496 // Speculatively evaluate both arms. 4497 SmallVector<PartialDiagnosticAt, 8> Diag; 4498 { 4499 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4500 StmtVisitorTy::Visit(E->getFalseExpr()); 4501 if (Diag.empty()) 4502 return; 4503 } 4504 4505 { 4506 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4507 Diag.clear(); 4508 StmtVisitorTy::Visit(E->getTrueExpr()); 4509 if (Diag.empty()) 4510 return; 4511 } 4512 4513 Error(E, diag::note_constexpr_conditional_never_const); 4514 } 4515 4516 4517 template<typename ConditionalOperator> 4518 bool HandleConditionalOperator(const ConditionalOperator *E) { 4519 bool BoolResult; 4520 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 4521 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 4522 CheckPotentialConstantConditional(E); 4523 return false; 4524 } 4525 if (Info.noteFailure()) { 4526 StmtVisitorTy::Visit(E->getTrueExpr()); 4527 StmtVisitorTy::Visit(E->getFalseExpr()); 4528 } 4529 return false; 4530 } 4531 4532 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 4533 return StmtVisitorTy::Visit(EvalExpr); 4534 } 4535 4536 protected: 4537 EvalInfo &Info; 4538 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 4539 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 4540 4541 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 4542 return Info.CCEDiag(E, D); 4543 } 4544 4545 bool ZeroInitialization(const Expr *E) { return Error(E); } 4546 4547 public: 4548 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 4549 4550 EvalInfo &getEvalInfo() { return Info; } 4551 4552 /// Report an evaluation error. This should only be called when an error is 4553 /// first discovered. When propagating an error, just return false. 4554 bool Error(const Expr *E, diag::kind D) { 4555 Info.FFDiag(E, D); 4556 return false; 4557 } 4558 bool Error(const Expr *E) { 4559 return Error(E, diag::note_invalid_subexpr_in_const_expr); 4560 } 4561 4562 bool VisitStmt(const Stmt *) { 4563 llvm_unreachable("Expression evaluator should not be called on stmts"); 4564 } 4565 bool VisitExpr(const Expr *E) { 4566 return Error(E); 4567 } 4568 4569 bool VisitParenExpr(const ParenExpr *E) 4570 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4571 bool VisitUnaryExtension(const UnaryOperator *E) 4572 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4573 bool VisitUnaryPlus(const UnaryOperator *E) 4574 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4575 bool VisitChooseExpr(const ChooseExpr *E) 4576 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 4577 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 4578 { return StmtVisitorTy::Visit(E->getResultExpr()); } 4579 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 4580 { return StmtVisitorTy::Visit(E->getReplacement()); } 4581 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) 4582 { return StmtVisitorTy::Visit(E->getExpr()); } 4583 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 4584 // The initializer may not have been parsed yet, or might be erroneous. 4585 if (!E->getExpr()) 4586 return Error(E); 4587 return StmtVisitorTy::Visit(E->getExpr()); 4588 } 4589 // We cannot create any objects for which cleanups are required, so there is 4590 // nothing to do here; all cleanups must come from unevaluated subexpressions. 4591 bool VisitExprWithCleanups(const ExprWithCleanups *E) 4592 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4593 4594 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 4595 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 4596 return static_cast<Derived*>(this)->VisitCastExpr(E); 4597 } 4598 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 4599 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 4600 return static_cast<Derived*>(this)->VisitCastExpr(E); 4601 } 4602 4603 bool VisitBinaryOperator(const BinaryOperator *E) { 4604 switch (E->getOpcode()) { 4605 default: 4606 return Error(E); 4607 4608 case BO_Comma: 4609 VisitIgnoredValue(E->getLHS()); 4610 return StmtVisitorTy::Visit(E->getRHS()); 4611 4612 case BO_PtrMemD: 4613 case BO_PtrMemI: { 4614 LValue Obj; 4615 if (!HandleMemberPointerAccess(Info, E, Obj)) 4616 return false; 4617 APValue Result; 4618 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 4619 return false; 4620 return DerivedSuccess(Result, E); 4621 } 4622 } 4623 } 4624 4625 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 4626 // Evaluate and cache the common expression. We treat it as a temporary, 4627 // even though it's not quite the same thing. 4628 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 4629 Info, E->getCommon())) 4630 return false; 4631 4632 return HandleConditionalOperator(E); 4633 } 4634 4635 bool VisitConditionalOperator(const ConditionalOperator *E) { 4636 bool IsBcpCall = false; 4637 // If the condition (ignoring parens) is a __builtin_constant_p call, 4638 // the result is a constant expression if it can be folded without 4639 // side-effects. This is an important GNU extension. See GCC PR38377 4640 // for discussion. 4641 if (const CallExpr *CallCE = 4642 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 4643 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 4644 IsBcpCall = true; 4645 4646 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 4647 // constant expression; we can't check whether it's potentially foldable. 4648 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 4649 return false; 4650 4651 FoldConstant Fold(Info, IsBcpCall); 4652 if (!HandleConditionalOperator(E)) { 4653 Fold.keepDiagnostics(); 4654 return false; 4655 } 4656 4657 return true; 4658 } 4659 4660 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 4661 if (APValue *Value = Info.CurrentCall->getTemporary(E)) 4662 return DerivedSuccess(*Value, E); 4663 4664 const Expr *Source = E->getSourceExpr(); 4665 if (!Source) 4666 return Error(E); 4667 if (Source == E) { // sanity checking. 4668 assert(0 && "OpaqueValueExpr recursively refers to itself"); 4669 return Error(E); 4670 } 4671 return StmtVisitorTy::Visit(Source); 4672 } 4673 4674 bool VisitCallExpr(const CallExpr *E) { 4675 APValue Result; 4676 if (!handleCallExpr(E, Result, nullptr)) 4677 return false; 4678 return DerivedSuccess(Result, E); 4679 } 4680 4681 bool handleCallExpr(const CallExpr *E, APValue &Result, 4682 const LValue *ResultSlot) { 4683 const Expr *Callee = E->getCallee()->IgnoreParens(); 4684 QualType CalleeType = Callee->getType(); 4685 4686 const FunctionDecl *FD = nullptr; 4687 LValue *This = nullptr, ThisVal; 4688 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 4689 bool HasQualifier = false; 4690 4691 // Extract function decl and 'this' pointer from the callee. 4692 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 4693 const ValueDecl *Member = nullptr; 4694 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 4695 // Explicit bound member calls, such as x.f() or p->g(); 4696 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 4697 return false; 4698 Member = ME->getMemberDecl(); 4699 This = &ThisVal; 4700 HasQualifier = ME->hasQualifier(); 4701 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 4702 // Indirect bound member calls ('.*' or '->*'). 4703 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false); 4704 if (!Member) return false; 4705 This = &ThisVal; 4706 } else 4707 return Error(Callee); 4708 4709 FD = dyn_cast<FunctionDecl>(Member); 4710 if (!FD) 4711 return Error(Callee); 4712 } else if (CalleeType->isFunctionPointerType()) { 4713 LValue Call; 4714 if (!EvaluatePointer(Callee, Call, Info)) 4715 return false; 4716 4717 if (!Call.getLValueOffset().isZero()) 4718 return Error(Callee); 4719 FD = dyn_cast_or_null<FunctionDecl>( 4720 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 4721 if (!FD) 4722 return Error(Callee); 4723 // Don't call function pointers which have been cast to some other type. 4724 // Per DR (no number yet), the caller and callee can differ in noexcept. 4725 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 4726 CalleeType->getPointeeType(), FD->getType())) { 4727 return Error(E); 4728 } 4729 4730 // Overloaded operator calls to member functions are represented as normal 4731 // calls with '*this' as the first argument. 4732 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 4733 if (MD && !MD->isStatic()) { 4734 // FIXME: When selecting an implicit conversion for an overloaded 4735 // operator delete, we sometimes try to evaluate calls to conversion 4736 // operators without a 'this' parameter! 4737 if (Args.empty()) 4738 return Error(E); 4739 4740 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 4741 return false; 4742 This = &ThisVal; 4743 Args = Args.slice(1); 4744 } else if (MD && MD->isLambdaStaticInvoker()) { 4745 // Map the static invoker for the lambda back to the call operator. 4746 // Conveniently, we don't have to slice out the 'this' argument (as is 4747 // being done for the non-static case), since a static member function 4748 // doesn't have an implicit argument passed in. 4749 const CXXRecordDecl *ClosureClass = MD->getParent(); 4750 assert( 4751 ClosureClass->captures_begin() == ClosureClass->captures_end() && 4752 "Number of captures must be zero for conversion to function-ptr"); 4753 4754 const CXXMethodDecl *LambdaCallOp = 4755 ClosureClass->getLambdaCallOperator(); 4756 4757 // Set 'FD', the function that will be called below, to the call 4758 // operator. If the closure object represents a generic lambda, find 4759 // the corresponding specialization of the call operator. 4760 4761 if (ClosureClass->isGenericLambda()) { 4762 assert(MD->isFunctionTemplateSpecialization() && 4763 "A generic lambda's static-invoker function must be a " 4764 "template specialization"); 4765 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 4766 FunctionTemplateDecl *CallOpTemplate = 4767 LambdaCallOp->getDescribedFunctionTemplate(); 4768 void *InsertPos = nullptr; 4769 FunctionDecl *CorrespondingCallOpSpecialization = 4770 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 4771 assert(CorrespondingCallOpSpecialization && 4772 "We must always have a function call operator specialization " 4773 "that corresponds to our static invoker specialization"); 4774 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 4775 } else 4776 FD = LambdaCallOp; 4777 } 4778 4779 4780 } else 4781 return Error(E); 4782 4783 if (This && !This->checkSubobject(Info, E, CSK_This)) 4784 return false; 4785 4786 // DR1358 allows virtual constexpr functions in some cases. Don't allow 4787 // calls to such functions in constant expressions. 4788 if (This && !HasQualifier && 4789 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual()) 4790 return Error(E, diag::note_constexpr_virtual_call); 4791 4792 const FunctionDecl *Definition = nullptr; 4793 Stmt *Body = FD->getBody(Definition); 4794 4795 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 4796 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 4797 Result, ResultSlot)) 4798 return false; 4799 4800 return true; 4801 } 4802 4803 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 4804 return StmtVisitorTy::Visit(E->getInitializer()); 4805 } 4806 bool VisitInitListExpr(const InitListExpr *E) { 4807 if (E->getNumInits() == 0) 4808 return DerivedZeroInitialization(E); 4809 if (E->getNumInits() == 1) 4810 return StmtVisitorTy::Visit(E->getInit(0)); 4811 return Error(E); 4812 } 4813 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 4814 return DerivedZeroInitialization(E); 4815 } 4816 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 4817 return DerivedZeroInitialization(E); 4818 } 4819 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 4820 return DerivedZeroInitialization(E); 4821 } 4822 4823 /// A member expression where the object is a prvalue is itself a prvalue. 4824 bool VisitMemberExpr(const MemberExpr *E) { 4825 assert(!E->isArrow() && "missing call to bound member function?"); 4826 4827 APValue Val; 4828 if (!Evaluate(Val, Info, E->getBase())) 4829 return false; 4830 4831 QualType BaseTy = E->getBase()->getType(); 4832 4833 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 4834 if (!FD) return Error(E); 4835 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 4836 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 4837 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 4838 4839 CompleteObject Obj(&Val, BaseTy); 4840 SubobjectDesignator Designator(BaseTy); 4841 Designator.addDeclUnchecked(FD); 4842 4843 APValue Result; 4844 return extractSubobject(Info, E, Obj, Designator, Result) && 4845 DerivedSuccess(Result, E); 4846 } 4847 4848 bool VisitCastExpr(const CastExpr *E) { 4849 switch (E->getCastKind()) { 4850 default: 4851 break; 4852 4853 case CK_AtomicToNonAtomic: { 4854 APValue AtomicVal; 4855 // This does not need to be done in place even for class/array types: 4856 // atomic-to-non-atomic conversion implies copying the object 4857 // representation. 4858 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 4859 return false; 4860 return DerivedSuccess(AtomicVal, E); 4861 } 4862 4863 case CK_NoOp: 4864 case CK_UserDefinedConversion: 4865 return StmtVisitorTy::Visit(E->getSubExpr()); 4866 4867 case CK_LValueToRValue: { 4868 LValue LVal; 4869 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 4870 return false; 4871 APValue RVal; 4872 // Note, we use the subexpression's type in order to retain cv-qualifiers. 4873 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 4874 LVal, RVal)) 4875 return false; 4876 return DerivedSuccess(RVal, E); 4877 } 4878 } 4879 4880 return Error(E); 4881 } 4882 4883 bool VisitUnaryPostInc(const UnaryOperator *UO) { 4884 return VisitUnaryPostIncDec(UO); 4885 } 4886 bool VisitUnaryPostDec(const UnaryOperator *UO) { 4887 return VisitUnaryPostIncDec(UO); 4888 } 4889 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 4890 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 4891 return Error(UO); 4892 4893 LValue LVal; 4894 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 4895 return false; 4896 APValue RVal; 4897 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 4898 UO->isIncrementOp(), &RVal)) 4899 return false; 4900 return DerivedSuccess(RVal, UO); 4901 } 4902 4903 bool VisitStmtExpr(const StmtExpr *E) { 4904 // We will have checked the full-expressions inside the statement expression 4905 // when they were completed, and don't need to check them again now. 4906 if (Info.checkingForOverflow()) 4907 return Error(E); 4908 4909 BlockScopeRAII Scope(Info); 4910 const CompoundStmt *CS = E->getSubStmt(); 4911 if (CS->body_empty()) 4912 return true; 4913 4914 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 4915 BE = CS->body_end(); 4916 /**/; ++BI) { 4917 if (BI + 1 == BE) { 4918 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 4919 if (!FinalExpr) { 4920 Info.FFDiag((*BI)->getLocStart(), 4921 diag::note_constexpr_stmt_expr_unsupported); 4922 return false; 4923 } 4924 return this->Visit(FinalExpr); 4925 } 4926 4927 APValue ReturnValue; 4928 StmtResult Result = { ReturnValue, nullptr }; 4929 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 4930 if (ESR != ESR_Succeeded) { 4931 // FIXME: If the statement-expression terminated due to 'return', 4932 // 'break', or 'continue', it would be nice to propagate that to 4933 // the outer statement evaluation rather than bailing out. 4934 if (ESR != ESR_Failed) 4935 Info.FFDiag((*BI)->getLocStart(), 4936 diag::note_constexpr_stmt_expr_unsupported); 4937 return false; 4938 } 4939 } 4940 4941 llvm_unreachable("Return from function from the loop above."); 4942 } 4943 4944 /// Visit a value which is evaluated, but whose value is ignored. 4945 void VisitIgnoredValue(const Expr *E) { 4946 EvaluateIgnoredValue(Info, E); 4947 } 4948 4949 /// Potentially visit a MemberExpr's base expression. 4950 void VisitIgnoredBaseExpression(const Expr *E) { 4951 // While MSVC doesn't evaluate the base expression, it does diagnose the 4952 // presence of side-effecting behavior. 4953 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 4954 return; 4955 VisitIgnoredValue(E); 4956 } 4957 }; 4958 4959 } 4960 4961 //===----------------------------------------------------------------------===// 4962 // Common base class for lvalue and temporary evaluation. 4963 //===----------------------------------------------------------------------===// 4964 namespace { 4965 template<class Derived> 4966 class LValueExprEvaluatorBase 4967 : public ExprEvaluatorBase<Derived> { 4968 protected: 4969 LValue &Result; 4970 bool InvalidBaseOK; 4971 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 4972 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 4973 4974 bool Success(APValue::LValueBase B) { 4975 Result.set(B); 4976 return true; 4977 } 4978 4979 bool evaluatePointer(const Expr *E, LValue &Result) { 4980 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 4981 } 4982 4983 public: 4984 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 4985 : ExprEvaluatorBaseTy(Info), Result(Result), 4986 InvalidBaseOK(InvalidBaseOK) {} 4987 4988 bool Success(const APValue &V, const Expr *E) { 4989 Result.setFrom(this->Info.Ctx, V); 4990 return true; 4991 } 4992 4993 bool VisitMemberExpr(const MemberExpr *E) { 4994 // Handle non-static data members. 4995 QualType BaseTy; 4996 bool EvalOK; 4997 if (E->isArrow()) { 4998 EvalOK = evaluatePointer(E->getBase(), Result); 4999 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 5000 } else if (E->getBase()->isRValue()) { 5001 assert(E->getBase()->getType()->isRecordType()); 5002 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 5003 BaseTy = E->getBase()->getType(); 5004 } else { 5005 EvalOK = this->Visit(E->getBase()); 5006 BaseTy = E->getBase()->getType(); 5007 } 5008 if (!EvalOK) { 5009 if (!InvalidBaseOK) 5010 return false; 5011 Result.setInvalid(E); 5012 return true; 5013 } 5014 5015 const ValueDecl *MD = E->getMemberDecl(); 5016 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 5017 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 5018 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 5019 (void)BaseTy; 5020 if (!HandleLValueMember(this->Info, E, Result, FD)) 5021 return false; 5022 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 5023 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 5024 return false; 5025 } else 5026 return this->Error(E); 5027 5028 if (MD->getType()->isReferenceType()) { 5029 APValue RefValue; 5030 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 5031 RefValue)) 5032 return false; 5033 return Success(RefValue, E); 5034 } 5035 return true; 5036 } 5037 5038 bool VisitBinaryOperator(const BinaryOperator *E) { 5039 switch (E->getOpcode()) { 5040 default: 5041 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5042 5043 case BO_PtrMemD: 5044 case BO_PtrMemI: 5045 return HandleMemberPointerAccess(this->Info, E, Result); 5046 } 5047 } 5048 5049 bool VisitCastExpr(const CastExpr *E) { 5050 switch (E->getCastKind()) { 5051 default: 5052 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5053 5054 case CK_DerivedToBase: 5055 case CK_UncheckedDerivedToBase: 5056 if (!this->Visit(E->getSubExpr())) 5057 return false; 5058 5059 // Now figure out the necessary offset to add to the base LV to get from 5060 // the derived class to the base class. 5061 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 5062 Result); 5063 } 5064 } 5065 }; 5066 } 5067 5068 //===----------------------------------------------------------------------===// 5069 // LValue Evaluation 5070 // 5071 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 5072 // function designators (in C), decl references to void objects (in C), and 5073 // temporaries (if building with -Wno-address-of-temporary). 5074 // 5075 // LValue evaluation produces values comprising a base expression of one of the 5076 // following types: 5077 // - Declarations 5078 // * VarDecl 5079 // * FunctionDecl 5080 // - Literals 5081 // * CompoundLiteralExpr in C (and in global scope in C++) 5082 // * StringLiteral 5083 // * CXXTypeidExpr 5084 // * PredefinedExpr 5085 // * ObjCStringLiteralExpr 5086 // * ObjCEncodeExpr 5087 // * AddrLabelExpr 5088 // * BlockExpr 5089 // * CallExpr for a MakeStringConstant builtin 5090 // - Locals and temporaries 5091 // * MaterializeTemporaryExpr 5092 // * Any Expr, with a CallIndex indicating the function in which the temporary 5093 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 5094 // from the AST (FIXME). 5095 // * A MaterializeTemporaryExpr that has static storage duration, with no 5096 // CallIndex, for a lifetime-extended temporary. 5097 // plus an offset in bytes. 5098 //===----------------------------------------------------------------------===// 5099 namespace { 5100 class LValueExprEvaluator 5101 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 5102 public: 5103 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 5104 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 5105 5106 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 5107 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 5108 5109 bool VisitDeclRefExpr(const DeclRefExpr *E); 5110 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 5111 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 5112 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 5113 bool VisitMemberExpr(const MemberExpr *E); 5114 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 5115 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 5116 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 5117 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 5118 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 5119 bool VisitUnaryDeref(const UnaryOperator *E); 5120 bool VisitUnaryReal(const UnaryOperator *E); 5121 bool VisitUnaryImag(const UnaryOperator *E); 5122 bool VisitUnaryPreInc(const UnaryOperator *UO) { 5123 return VisitUnaryPreIncDec(UO); 5124 } 5125 bool VisitUnaryPreDec(const UnaryOperator *UO) { 5126 return VisitUnaryPreIncDec(UO); 5127 } 5128 bool VisitBinAssign(const BinaryOperator *BO); 5129 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 5130 5131 bool VisitCastExpr(const CastExpr *E) { 5132 switch (E->getCastKind()) { 5133 default: 5134 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 5135 5136 case CK_LValueBitCast: 5137 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5138 if (!Visit(E->getSubExpr())) 5139 return false; 5140 Result.Designator.setInvalid(); 5141 return true; 5142 5143 case CK_BaseToDerived: 5144 if (!Visit(E->getSubExpr())) 5145 return false; 5146 return HandleBaseToDerivedCast(Info, E, Result); 5147 } 5148 } 5149 }; 5150 } // end anonymous namespace 5151 5152 /// Evaluate an expression as an lvalue. This can be legitimately called on 5153 /// expressions which are not glvalues, in three cases: 5154 /// * function designators in C, and 5155 /// * "extern void" objects 5156 /// * @selector() expressions in Objective-C 5157 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 5158 bool InvalidBaseOK) { 5159 assert(E->isGLValue() || E->getType()->isFunctionType() || 5160 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 5161 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5162 } 5163 5164 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 5165 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 5166 return Success(FD); 5167 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 5168 return VisitVarDecl(E, VD); 5169 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 5170 return Visit(BD->getBinding()); 5171 return Error(E); 5172 } 5173 5174 5175 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 5176 5177 // If we are within a lambda's call operator, check whether the 'VD' referred 5178 // to within 'E' actually represents a lambda-capture that maps to a 5179 // data-member/field within the closure object, and if so, evaluate to the 5180 // field or what the field refers to. 5181 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) { 5182 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 5183 if (Info.checkingPotentialConstantExpression()) 5184 return false; 5185 // Start with 'Result' referring to the complete closure object... 5186 Result = *Info.CurrentCall->This; 5187 // ... then update it to refer to the field of the closure object 5188 // that represents the capture. 5189 if (!HandleLValueMember(Info, E, Result, FD)) 5190 return false; 5191 // And if the field is of reference type, update 'Result' to refer to what 5192 // the field refers to. 5193 if (FD->getType()->isReferenceType()) { 5194 APValue RVal; 5195 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 5196 RVal)) 5197 return false; 5198 Result.setFrom(Info.Ctx, RVal); 5199 } 5200 return true; 5201 } 5202 } 5203 CallStackFrame *Frame = nullptr; 5204 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 5205 // Only if a local variable was declared in the function currently being 5206 // evaluated, do we expect to be able to find its value in the current 5207 // frame. (Otherwise it was likely declared in an enclosing context and 5208 // could either have a valid evaluatable value (for e.g. a constexpr 5209 // variable) or be ill-formed (and trigger an appropriate evaluation 5210 // diagnostic)). 5211 if (Info.CurrentCall->Callee && 5212 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 5213 Frame = Info.CurrentCall; 5214 } 5215 } 5216 5217 if (!VD->getType()->isReferenceType()) { 5218 if (Frame) { 5219 Result.set(VD, Frame->Index); 5220 return true; 5221 } 5222 return Success(VD); 5223 } 5224 5225 APValue *V; 5226 if (!evaluateVarDeclInit(Info, E, VD, Frame, V)) 5227 return false; 5228 if (V->isUninit()) { 5229 if (!Info.checkingPotentialConstantExpression()) 5230 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 5231 return false; 5232 } 5233 return Success(*V, E); 5234 } 5235 5236 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 5237 const MaterializeTemporaryExpr *E) { 5238 // Walk through the expression to find the materialized temporary itself. 5239 SmallVector<const Expr *, 2> CommaLHSs; 5240 SmallVector<SubobjectAdjustment, 2> Adjustments; 5241 const Expr *Inner = E->GetTemporaryExpr()-> 5242 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 5243 5244 // If we passed any comma operators, evaluate their LHSs. 5245 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 5246 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 5247 return false; 5248 5249 // A materialized temporary with static storage duration can appear within the 5250 // result of a constant expression evaluation, so we need to preserve its 5251 // value for use outside this evaluation. 5252 APValue *Value; 5253 if (E->getStorageDuration() == SD_Static) { 5254 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 5255 *Value = APValue(); 5256 Result.set(E); 5257 } else { 5258 Value = &Info.CurrentCall-> 5259 createTemporary(E, E->getStorageDuration() == SD_Automatic); 5260 Result.set(E, Info.CurrentCall->Index); 5261 } 5262 5263 QualType Type = Inner->getType(); 5264 5265 // Materialize the temporary itself. 5266 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 5267 (E->getStorageDuration() == SD_Static && 5268 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 5269 *Value = APValue(); 5270 return false; 5271 } 5272 5273 // Adjust our lvalue to refer to the desired subobject. 5274 for (unsigned I = Adjustments.size(); I != 0; /**/) { 5275 --I; 5276 switch (Adjustments[I].Kind) { 5277 case SubobjectAdjustment::DerivedToBaseAdjustment: 5278 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 5279 Type, Result)) 5280 return false; 5281 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 5282 break; 5283 5284 case SubobjectAdjustment::FieldAdjustment: 5285 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 5286 return false; 5287 Type = Adjustments[I].Field->getType(); 5288 break; 5289 5290 case SubobjectAdjustment::MemberPointerAdjustment: 5291 if (!HandleMemberPointerAccess(this->Info, Type, Result, 5292 Adjustments[I].Ptr.RHS)) 5293 return false; 5294 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 5295 break; 5296 } 5297 } 5298 5299 return true; 5300 } 5301 5302 bool 5303 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 5304 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 5305 "lvalue compound literal in c++?"); 5306 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 5307 // only see this when folding in C, so there's no standard to follow here. 5308 return Success(E); 5309 } 5310 5311 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 5312 if (!E->isPotentiallyEvaluated()) 5313 return Success(E); 5314 5315 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic) 5316 << E->getExprOperand()->getType() 5317 << E->getExprOperand()->getSourceRange(); 5318 return false; 5319 } 5320 5321 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 5322 return Success(E); 5323 } 5324 5325 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 5326 // Handle static data members. 5327 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 5328 VisitIgnoredBaseExpression(E->getBase()); 5329 return VisitVarDecl(E, VD); 5330 } 5331 5332 // Handle static member functions. 5333 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 5334 if (MD->isStatic()) { 5335 VisitIgnoredBaseExpression(E->getBase()); 5336 return Success(MD); 5337 } 5338 } 5339 5340 // Handle non-static data members. 5341 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 5342 } 5343 5344 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 5345 // FIXME: Deal with vectors as array subscript bases. 5346 if (E->getBase()->getType()->isVectorType()) 5347 return Error(E); 5348 5349 bool Success = true; 5350 if (!evaluatePointer(E->getBase(), Result)) { 5351 if (!Info.noteFailure()) 5352 return false; 5353 Success = false; 5354 } 5355 5356 APSInt Index; 5357 if (!EvaluateInteger(E->getIdx(), Index, Info)) 5358 return false; 5359 5360 return Success && 5361 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 5362 } 5363 5364 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 5365 return evaluatePointer(E->getSubExpr(), Result); 5366 } 5367 5368 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 5369 if (!Visit(E->getSubExpr())) 5370 return false; 5371 // __real is a no-op on scalar lvalues. 5372 if (E->getSubExpr()->getType()->isAnyComplexType()) 5373 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 5374 return true; 5375 } 5376 5377 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 5378 assert(E->getSubExpr()->getType()->isAnyComplexType() && 5379 "lvalue __imag__ on scalar?"); 5380 if (!Visit(E->getSubExpr())) 5381 return false; 5382 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 5383 return true; 5384 } 5385 5386 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 5387 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5388 return Error(UO); 5389 5390 if (!this->Visit(UO->getSubExpr())) 5391 return false; 5392 5393 return handleIncDec( 5394 this->Info, UO, Result, UO->getSubExpr()->getType(), 5395 UO->isIncrementOp(), nullptr); 5396 } 5397 5398 bool LValueExprEvaluator::VisitCompoundAssignOperator( 5399 const CompoundAssignOperator *CAO) { 5400 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5401 return Error(CAO); 5402 5403 APValue RHS; 5404 5405 // The overall lvalue result is the result of evaluating the LHS. 5406 if (!this->Visit(CAO->getLHS())) { 5407 if (Info.noteFailure()) 5408 Evaluate(RHS, this->Info, CAO->getRHS()); 5409 return false; 5410 } 5411 5412 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 5413 return false; 5414 5415 return handleCompoundAssignment( 5416 this->Info, CAO, 5417 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 5418 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 5419 } 5420 5421 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 5422 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5423 return Error(E); 5424 5425 APValue NewVal; 5426 5427 if (!this->Visit(E->getLHS())) { 5428 if (Info.noteFailure()) 5429 Evaluate(NewVal, this->Info, E->getRHS()); 5430 return false; 5431 } 5432 5433 if (!Evaluate(NewVal, this->Info, E->getRHS())) 5434 return false; 5435 5436 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 5437 NewVal); 5438 } 5439 5440 //===----------------------------------------------------------------------===// 5441 // Pointer Evaluation 5442 //===----------------------------------------------------------------------===// 5443 5444 /// \brief Attempts to compute the number of bytes available at the pointer 5445 /// returned by a function with the alloc_size attribute. Returns true if we 5446 /// were successful. Places an unsigned number into `Result`. 5447 /// 5448 /// This expects the given CallExpr to be a call to a function with an 5449 /// alloc_size attribute. 5450 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5451 const CallExpr *Call, 5452 llvm::APInt &Result) { 5453 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 5454 5455 // alloc_size args are 1-indexed, 0 means not present. 5456 assert(AllocSize && AllocSize->getElemSizeParam() != 0); 5457 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1; 5458 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 5459 if (Call->getNumArgs() <= SizeArgNo) 5460 return false; 5461 5462 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 5463 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects)) 5464 return false; 5465 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 5466 return false; 5467 Into = Into.zextOrSelf(BitsInSizeT); 5468 return true; 5469 }; 5470 5471 APSInt SizeOfElem; 5472 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 5473 return false; 5474 5475 if (!AllocSize->getNumElemsParam()) { 5476 Result = std::move(SizeOfElem); 5477 return true; 5478 } 5479 5480 APSInt NumberOfElems; 5481 // Argument numbers start at 1 5482 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1; 5483 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 5484 return false; 5485 5486 bool Overflow; 5487 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 5488 if (Overflow) 5489 return false; 5490 5491 Result = std::move(BytesAvailable); 5492 return true; 5493 } 5494 5495 /// \brief Convenience function. LVal's base must be a call to an alloc_size 5496 /// function. 5497 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5498 const LValue &LVal, 5499 llvm::APInt &Result) { 5500 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 5501 "Can't get the size of a non alloc_size function"); 5502 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 5503 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 5504 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 5505 } 5506 5507 /// \brief Attempts to evaluate the given LValueBase as the result of a call to 5508 /// a function with the alloc_size attribute. If it was possible to do so, this 5509 /// function will return true, make Result's Base point to said function call, 5510 /// and mark Result's Base as invalid. 5511 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 5512 LValue &Result) { 5513 if (Base.isNull()) 5514 return false; 5515 5516 // Because we do no form of static analysis, we only support const variables. 5517 // 5518 // Additionally, we can't support parameters, nor can we support static 5519 // variables (in the latter case, use-before-assign isn't UB; in the former, 5520 // we have no clue what they'll be assigned to). 5521 const auto *VD = 5522 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 5523 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 5524 return false; 5525 5526 const Expr *Init = VD->getAnyInitializer(); 5527 if (!Init) 5528 return false; 5529 5530 const Expr *E = Init->IgnoreParens(); 5531 if (!tryUnwrapAllocSizeCall(E)) 5532 return false; 5533 5534 // Store E instead of E unwrapped so that the type of the LValue's base is 5535 // what the user wanted. 5536 Result.setInvalid(E); 5537 5538 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 5539 Result.addUnsizedArray(Info, E, Pointee); 5540 return true; 5541 } 5542 5543 namespace { 5544 class PointerExprEvaluator 5545 : public ExprEvaluatorBase<PointerExprEvaluator> { 5546 LValue &Result; 5547 bool InvalidBaseOK; 5548 5549 bool Success(const Expr *E) { 5550 Result.set(E); 5551 return true; 5552 } 5553 5554 bool evaluateLValue(const Expr *E, LValue &Result) { 5555 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 5556 } 5557 5558 bool evaluatePointer(const Expr *E, LValue &Result) { 5559 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 5560 } 5561 5562 bool visitNonBuiltinCallExpr(const CallExpr *E); 5563 public: 5564 5565 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 5566 : ExprEvaluatorBaseTy(info), Result(Result), 5567 InvalidBaseOK(InvalidBaseOK) {} 5568 5569 bool Success(const APValue &V, const Expr *E) { 5570 Result.setFrom(Info.Ctx, V); 5571 return true; 5572 } 5573 bool ZeroInitialization(const Expr *E) { 5574 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 5575 Result.setNull(E->getType(), TargetVal); 5576 return true; 5577 } 5578 5579 bool VisitBinaryOperator(const BinaryOperator *E); 5580 bool VisitCastExpr(const CastExpr* E); 5581 bool VisitUnaryAddrOf(const UnaryOperator *E); 5582 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 5583 { return Success(E); } 5584 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 5585 if (Info.noteFailure()) 5586 EvaluateIgnoredValue(Info, E->getSubExpr()); 5587 return Error(E); 5588 } 5589 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 5590 { return Success(E); } 5591 bool VisitCallExpr(const CallExpr *E); 5592 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 5593 bool VisitBlockExpr(const BlockExpr *E) { 5594 if (!E->getBlockDecl()->hasCaptures()) 5595 return Success(E); 5596 return Error(E); 5597 } 5598 bool VisitCXXThisExpr(const CXXThisExpr *E) { 5599 // Can't look at 'this' when checking a potential constant expression. 5600 if (Info.checkingPotentialConstantExpression()) 5601 return false; 5602 if (!Info.CurrentCall->This) { 5603 if (Info.getLangOpts().CPlusPlus11) 5604 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 5605 else 5606 Info.FFDiag(E); 5607 return false; 5608 } 5609 Result = *Info.CurrentCall->This; 5610 // If we are inside a lambda's call operator, the 'this' expression refers 5611 // to the enclosing '*this' object (either by value or reference) which is 5612 // either copied into the closure object's field that represents the '*this' 5613 // or refers to '*this'. 5614 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 5615 // Update 'Result' to refer to the data member/field of the closure object 5616 // that represents the '*this' capture. 5617 if (!HandleLValueMember(Info, E, Result, 5618 Info.CurrentCall->LambdaThisCaptureField)) 5619 return false; 5620 // If we captured '*this' by reference, replace the field with its referent. 5621 if (Info.CurrentCall->LambdaThisCaptureField->getType() 5622 ->isPointerType()) { 5623 APValue RVal; 5624 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 5625 RVal)) 5626 return false; 5627 5628 Result.setFrom(Info.Ctx, RVal); 5629 } 5630 } 5631 return true; 5632 } 5633 5634 // FIXME: Missing: @protocol, @selector 5635 }; 5636 } // end anonymous namespace 5637 5638 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 5639 bool InvalidBaseOK) { 5640 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 5641 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5642 } 5643 5644 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 5645 if (E->getOpcode() != BO_Add && 5646 E->getOpcode() != BO_Sub) 5647 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5648 5649 const Expr *PExp = E->getLHS(); 5650 const Expr *IExp = E->getRHS(); 5651 if (IExp->getType()->isPointerType()) 5652 std::swap(PExp, IExp); 5653 5654 bool EvalPtrOK = evaluatePointer(PExp, Result); 5655 if (!EvalPtrOK && !Info.noteFailure()) 5656 return false; 5657 5658 llvm::APSInt Offset; 5659 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 5660 return false; 5661 5662 if (E->getOpcode() == BO_Sub) 5663 negateAsSigned(Offset); 5664 5665 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 5666 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 5667 } 5668 5669 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 5670 return evaluateLValue(E->getSubExpr(), Result); 5671 } 5672 5673 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) { 5674 const Expr* SubExpr = E->getSubExpr(); 5675 5676 switch (E->getCastKind()) { 5677 default: 5678 break; 5679 5680 case CK_BitCast: 5681 case CK_CPointerToObjCPointerCast: 5682 case CK_BlockPointerToObjCPointerCast: 5683 case CK_AnyPointerToBlockPointerCast: 5684 case CK_AddressSpaceConversion: 5685 if (!Visit(SubExpr)) 5686 return false; 5687 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 5688 // permitted in constant expressions in C++11. Bitcasts from cv void* are 5689 // also static_casts, but we disallow them as a resolution to DR1312. 5690 if (!E->getType()->isVoidPointerType()) { 5691 Result.Designator.setInvalid(); 5692 if (SubExpr->getType()->isVoidPointerType()) 5693 CCEDiag(E, diag::note_constexpr_invalid_cast) 5694 << 3 << SubExpr->getType(); 5695 else 5696 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5697 } 5698 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 5699 ZeroInitialization(E); 5700 return true; 5701 5702 case CK_DerivedToBase: 5703 case CK_UncheckedDerivedToBase: 5704 if (!evaluatePointer(E->getSubExpr(), Result)) 5705 return false; 5706 if (!Result.Base && Result.Offset.isZero()) 5707 return true; 5708 5709 // Now figure out the necessary offset to add to the base LV to get from 5710 // the derived class to the base class. 5711 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 5712 castAs<PointerType>()->getPointeeType(), 5713 Result); 5714 5715 case CK_BaseToDerived: 5716 if (!Visit(E->getSubExpr())) 5717 return false; 5718 if (!Result.Base && Result.Offset.isZero()) 5719 return true; 5720 return HandleBaseToDerivedCast(Info, E, Result); 5721 5722 case CK_NullToPointer: 5723 VisitIgnoredValue(E->getSubExpr()); 5724 return ZeroInitialization(E); 5725 5726 case CK_IntegralToPointer: { 5727 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5728 5729 APValue Value; 5730 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 5731 break; 5732 5733 if (Value.isInt()) { 5734 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 5735 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 5736 Result.Base = (Expr*)nullptr; 5737 Result.InvalidBase = false; 5738 Result.Offset = CharUnits::fromQuantity(N); 5739 Result.CallIndex = 0; 5740 Result.Designator.setInvalid(); 5741 Result.IsNullPtr = false; 5742 return true; 5743 } else { 5744 // Cast is of an lvalue, no need to change value. 5745 Result.setFrom(Info.Ctx, Value); 5746 return true; 5747 } 5748 } 5749 5750 case CK_ArrayToPointerDecay: { 5751 if (SubExpr->isGLValue()) { 5752 if (!evaluateLValue(SubExpr, Result)) 5753 return false; 5754 } else { 5755 Result.set(SubExpr, Info.CurrentCall->Index); 5756 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false), 5757 Info, Result, SubExpr)) 5758 return false; 5759 } 5760 // The result is a pointer to the first element of the array. 5761 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 5762 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 5763 Result.addArray(Info, E, CAT); 5764 else 5765 Result.addUnsizedArray(Info, E, AT->getElementType()); 5766 return true; 5767 } 5768 5769 case CK_FunctionToPointerDecay: 5770 return evaluateLValue(SubExpr, Result); 5771 5772 case CK_LValueToRValue: { 5773 LValue LVal; 5774 if (!evaluateLValue(E->getSubExpr(), LVal)) 5775 return false; 5776 5777 APValue RVal; 5778 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5779 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5780 LVal, RVal)) 5781 return InvalidBaseOK && 5782 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 5783 return Success(RVal, E); 5784 } 5785 } 5786 5787 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5788 } 5789 5790 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) { 5791 // C++ [expr.alignof]p3: 5792 // When alignof is applied to a reference type, the result is the 5793 // alignment of the referenced type. 5794 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 5795 T = Ref->getPointeeType(); 5796 5797 // __alignof is defined to return the preferred alignment. 5798 if (T.getQualifiers().hasUnaligned()) 5799 return CharUnits::One(); 5800 return Info.Ctx.toCharUnitsFromBits( 5801 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 5802 } 5803 5804 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) { 5805 E = E->IgnoreParens(); 5806 5807 // The kinds of expressions that we have special-case logic here for 5808 // should be kept up to date with the special checks for those 5809 // expressions in Sema. 5810 5811 // alignof decl is always accepted, even if it doesn't make sense: we default 5812 // to 1 in those cases. 5813 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5814 return Info.Ctx.getDeclAlign(DRE->getDecl(), 5815 /*RefAsPointee*/true); 5816 5817 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 5818 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 5819 /*RefAsPointee*/true); 5820 5821 return GetAlignOfType(Info, E->getType()); 5822 } 5823 5824 // To be clear: this happily visits unsupported builtins. Better name welcomed. 5825 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 5826 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 5827 return true; 5828 5829 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 5830 return false; 5831 5832 Result.setInvalid(E); 5833 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 5834 Result.addUnsizedArray(Info, E, PointeeTy); 5835 return true; 5836 } 5837 5838 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 5839 if (IsStringLiteralCall(E)) 5840 return Success(E); 5841 5842 if (unsigned BuiltinOp = E->getBuiltinCallee()) 5843 return VisitBuiltinCallExpr(E, BuiltinOp); 5844 5845 return visitNonBuiltinCallExpr(E); 5846 } 5847 5848 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 5849 unsigned BuiltinOp) { 5850 switch (BuiltinOp) { 5851 case Builtin::BI__builtin_addressof: 5852 return evaluateLValue(E->getArg(0), Result); 5853 case Builtin::BI__builtin_assume_aligned: { 5854 // We need to be very careful here because: if the pointer does not have the 5855 // asserted alignment, then the behavior is undefined, and undefined 5856 // behavior is non-constant. 5857 if (!evaluatePointer(E->getArg(0), Result)) 5858 return false; 5859 5860 LValue OffsetResult(Result); 5861 APSInt Alignment; 5862 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 5863 return false; 5864 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 5865 5866 if (E->getNumArgs() > 2) { 5867 APSInt Offset; 5868 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 5869 return false; 5870 5871 int64_t AdditionalOffset = -Offset.getZExtValue(); 5872 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 5873 } 5874 5875 // If there is a base object, then it must have the correct alignment. 5876 if (OffsetResult.Base) { 5877 CharUnits BaseAlignment; 5878 if (const ValueDecl *VD = 5879 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 5880 BaseAlignment = Info.Ctx.getDeclAlign(VD); 5881 } else { 5882 BaseAlignment = 5883 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>()); 5884 } 5885 5886 if (BaseAlignment < Align) { 5887 Result.Designator.setInvalid(); 5888 // FIXME: Add support to Diagnostic for long / long long. 5889 CCEDiag(E->getArg(0), 5890 diag::note_constexpr_baa_insufficient_alignment) << 0 5891 << (unsigned)BaseAlignment.getQuantity() 5892 << (unsigned)Align.getQuantity(); 5893 return false; 5894 } 5895 } 5896 5897 // The offset must also have the correct alignment. 5898 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 5899 Result.Designator.setInvalid(); 5900 5901 (OffsetResult.Base 5902 ? CCEDiag(E->getArg(0), 5903 diag::note_constexpr_baa_insufficient_alignment) << 1 5904 : CCEDiag(E->getArg(0), 5905 diag::note_constexpr_baa_value_insufficient_alignment)) 5906 << (int)OffsetResult.Offset.getQuantity() 5907 << (unsigned)Align.getQuantity(); 5908 return false; 5909 } 5910 5911 return true; 5912 } 5913 5914 case Builtin::BIstrchr: 5915 case Builtin::BIwcschr: 5916 case Builtin::BImemchr: 5917 case Builtin::BIwmemchr: 5918 if (Info.getLangOpts().CPlusPlus11) 5919 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 5920 << /*isConstexpr*/0 << /*isConstructor*/0 5921 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 5922 else 5923 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 5924 LLVM_FALLTHROUGH; 5925 case Builtin::BI__builtin_strchr: 5926 case Builtin::BI__builtin_wcschr: 5927 case Builtin::BI__builtin_memchr: 5928 case Builtin::BI__builtin_char_memchr: 5929 case Builtin::BI__builtin_wmemchr: { 5930 if (!Visit(E->getArg(0))) 5931 return false; 5932 APSInt Desired; 5933 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 5934 return false; 5935 uint64_t MaxLength = uint64_t(-1); 5936 if (BuiltinOp != Builtin::BIstrchr && 5937 BuiltinOp != Builtin::BIwcschr && 5938 BuiltinOp != Builtin::BI__builtin_strchr && 5939 BuiltinOp != Builtin::BI__builtin_wcschr) { 5940 APSInt N; 5941 if (!EvaluateInteger(E->getArg(2), N, Info)) 5942 return false; 5943 MaxLength = N.getExtValue(); 5944 } 5945 5946 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 5947 5948 // Figure out what value we're actually looking for (after converting to 5949 // the corresponding unsigned type if necessary). 5950 uint64_t DesiredVal; 5951 bool StopAtNull = false; 5952 switch (BuiltinOp) { 5953 case Builtin::BIstrchr: 5954 case Builtin::BI__builtin_strchr: 5955 // strchr compares directly to the passed integer, and therefore 5956 // always fails if given an int that is not a char. 5957 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 5958 E->getArg(1)->getType(), 5959 Desired), 5960 Desired)) 5961 return ZeroInitialization(E); 5962 StopAtNull = true; 5963 LLVM_FALLTHROUGH; 5964 case Builtin::BImemchr: 5965 case Builtin::BI__builtin_memchr: 5966 case Builtin::BI__builtin_char_memchr: 5967 // memchr compares by converting both sides to unsigned char. That's also 5968 // correct for strchr if we get this far (to cope with plain char being 5969 // unsigned in the strchr case). 5970 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 5971 break; 5972 5973 case Builtin::BIwcschr: 5974 case Builtin::BI__builtin_wcschr: 5975 StopAtNull = true; 5976 LLVM_FALLTHROUGH; 5977 case Builtin::BIwmemchr: 5978 case Builtin::BI__builtin_wmemchr: 5979 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 5980 DesiredVal = Desired.getZExtValue(); 5981 break; 5982 } 5983 5984 for (; MaxLength; --MaxLength) { 5985 APValue Char; 5986 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 5987 !Char.isInt()) 5988 return false; 5989 if (Char.getInt().getZExtValue() == DesiredVal) 5990 return true; 5991 if (StopAtNull && !Char.getInt()) 5992 break; 5993 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 5994 return false; 5995 } 5996 // Not found: return nullptr. 5997 return ZeroInitialization(E); 5998 } 5999 6000 default: 6001 return visitNonBuiltinCallExpr(E); 6002 } 6003 } 6004 6005 //===----------------------------------------------------------------------===// 6006 // Member Pointer Evaluation 6007 //===----------------------------------------------------------------------===// 6008 6009 namespace { 6010 class MemberPointerExprEvaluator 6011 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 6012 MemberPtr &Result; 6013 6014 bool Success(const ValueDecl *D) { 6015 Result = MemberPtr(D); 6016 return true; 6017 } 6018 public: 6019 6020 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 6021 : ExprEvaluatorBaseTy(Info), Result(Result) {} 6022 6023 bool Success(const APValue &V, const Expr *E) { 6024 Result.setFrom(V); 6025 return true; 6026 } 6027 bool ZeroInitialization(const Expr *E) { 6028 return Success((const ValueDecl*)nullptr); 6029 } 6030 6031 bool VisitCastExpr(const CastExpr *E); 6032 bool VisitUnaryAddrOf(const UnaryOperator *E); 6033 }; 6034 } // end anonymous namespace 6035 6036 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 6037 EvalInfo &Info) { 6038 assert(E->isRValue() && E->getType()->isMemberPointerType()); 6039 return MemberPointerExprEvaluator(Info, Result).Visit(E); 6040 } 6041 6042 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 6043 switch (E->getCastKind()) { 6044 default: 6045 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6046 6047 case CK_NullToMemberPointer: 6048 VisitIgnoredValue(E->getSubExpr()); 6049 return ZeroInitialization(E); 6050 6051 case CK_BaseToDerivedMemberPointer: { 6052 if (!Visit(E->getSubExpr())) 6053 return false; 6054 if (E->path_empty()) 6055 return true; 6056 // Base-to-derived member pointer casts store the path in derived-to-base 6057 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 6058 // the wrong end of the derived->base arc, so stagger the path by one class. 6059 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 6060 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 6061 PathI != PathE; ++PathI) { 6062 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6063 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 6064 if (!Result.castToDerived(Derived)) 6065 return Error(E); 6066 } 6067 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 6068 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 6069 return Error(E); 6070 return true; 6071 } 6072 6073 case CK_DerivedToBaseMemberPointer: 6074 if (!Visit(E->getSubExpr())) 6075 return false; 6076 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6077 PathE = E->path_end(); PathI != PathE; ++PathI) { 6078 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6079 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6080 if (!Result.castToBase(Base)) 6081 return Error(E); 6082 } 6083 return true; 6084 } 6085 } 6086 6087 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 6088 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 6089 // member can be formed. 6090 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 6091 } 6092 6093 //===----------------------------------------------------------------------===// 6094 // Record Evaluation 6095 //===----------------------------------------------------------------------===// 6096 6097 namespace { 6098 class RecordExprEvaluator 6099 : public ExprEvaluatorBase<RecordExprEvaluator> { 6100 const LValue &This; 6101 APValue &Result; 6102 public: 6103 6104 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 6105 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 6106 6107 bool Success(const APValue &V, const Expr *E) { 6108 Result = V; 6109 return true; 6110 } 6111 bool ZeroInitialization(const Expr *E) { 6112 return ZeroInitialization(E, E->getType()); 6113 } 6114 bool ZeroInitialization(const Expr *E, QualType T); 6115 6116 bool VisitCallExpr(const CallExpr *E) { 6117 return handleCallExpr(E, Result, &This); 6118 } 6119 bool VisitCastExpr(const CastExpr *E); 6120 bool VisitInitListExpr(const InitListExpr *E); 6121 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6122 return VisitCXXConstructExpr(E, E->getType()); 6123 } 6124 bool VisitLambdaExpr(const LambdaExpr *E); 6125 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 6126 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 6127 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 6128 }; 6129 } 6130 6131 /// Perform zero-initialization on an object of non-union class type. 6132 /// C++11 [dcl.init]p5: 6133 /// To zero-initialize an object or reference of type T means: 6134 /// [...] 6135 /// -- if T is a (possibly cv-qualified) non-union class type, 6136 /// each non-static data member and each base-class subobject is 6137 /// zero-initialized 6138 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 6139 const RecordDecl *RD, 6140 const LValue &This, APValue &Result) { 6141 assert(!RD->isUnion() && "Expected non-union class type"); 6142 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 6143 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 6144 std::distance(RD->field_begin(), RD->field_end())); 6145 6146 if (RD->isInvalidDecl()) return false; 6147 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6148 6149 if (CD) { 6150 unsigned Index = 0; 6151 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 6152 End = CD->bases_end(); I != End; ++I, ++Index) { 6153 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 6154 LValue Subobject = This; 6155 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 6156 return false; 6157 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 6158 Result.getStructBase(Index))) 6159 return false; 6160 } 6161 } 6162 6163 for (const auto *I : RD->fields()) { 6164 // -- if T is a reference type, no initialization is performed. 6165 if (I->getType()->isReferenceType()) 6166 continue; 6167 6168 LValue Subobject = This; 6169 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 6170 return false; 6171 6172 ImplicitValueInitExpr VIE(I->getType()); 6173 if (!EvaluateInPlace( 6174 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 6175 return false; 6176 } 6177 6178 return true; 6179 } 6180 6181 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 6182 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 6183 if (RD->isInvalidDecl()) return false; 6184 if (RD->isUnion()) { 6185 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 6186 // object's first non-static named data member is zero-initialized 6187 RecordDecl::field_iterator I = RD->field_begin(); 6188 if (I == RD->field_end()) { 6189 Result = APValue((const FieldDecl*)nullptr); 6190 return true; 6191 } 6192 6193 LValue Subobject = This; 6194 if (!HandleLValueMember(Info, E, Subobject, *I)) 6195 return false; 6196 Result = APValue(*I); 6197 ImplicitValueInitExpr VIE(I->getType()); 6198 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 6199 } 6200 6201 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 6202 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 6203 return false; 6204 } 6205 6206 return HandleClassZeroInitialization(Info, E, RD, This, Result); 6207 } 6208 6209 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 6210 switch (E->getCastKind()) { 6211 default: 6212 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6213 6214 case CK_ConstructorConversion: 6215 return Visit(E->getSubExpr()); 6216 6217 case CK_DerivedToBase: 6218 case CK_UncheckedDerivedToBase: { 6219 APValue DerivedObject; 6220 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 6221 return false; 6222 if (!DerivedObject.isStruct()) 6223 return Error(E->getSubExpr()); 6224 6225 // Derived-to-base rvalue conversion: just slice off the derived part. 6226 APValue *Value = &DerivedObject; 6227 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 6228 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6229 PathE = E->path_end(); PathI != PathE; ++PathI) { 6230 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 6231 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6232 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 6233 RD = Base; 6234 } 6235 Result = *Value; 6236 return true; 6237 } 6238 } 6239 } 6240 6241 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6242 if (E->isTransparent()) 6243 return Visit(E->getInit(0)); 6244 6245 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 6246 if (RD->isInvalidDecl()) return false; 6247 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6248 6249 if (RD->isUnion()) { 6250 const FieldDecl *Field = E->getInitializedFieldInUnion(); 6251 Result = APValue(Field); 6252 if (!Field) 6253 return true; 6254 6255 // If the initializer list for a union does not contain any elements, the 6256 // first element of the union is value-initialized. 6257 // FIXME: The element should be initialized from an initializer list. 6258 // Is this difference ever observable for initializer lists which 6259 // we don't build? 6260 ImplicitValueInitExpr VIE(Field->getType()); 6261 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 6262 6263 LValue Subobject = This; 6264 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 6265 return false; 6266 6267 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6268 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6269 isa<CXXDefaultInitExpr>(InitExpr)); 6270 6271 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 6272 } 6273 6274 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 6275 if (Result.isUninit()) 6276 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 6277 std::distance(RD->field_begin(), RD->field_end())); 6278 unsigned ElementNo = 0; 6279 bool Success = true; 6280 6281 // Initialize base classes. 6282 if (CXXRD) { 6283 for (const auto &Base : CXXRD->bases()) { 6284 assert(ElementNo < E->getNumInits() && "missing init for base class"); 6285 const Expr *Init = E->getInit(ElementNo); 6286 6287 LValue Subobject = This; 6288 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 6289 return false; 6290 6291 APValue &FieldVal = Result.getStructBase(ElementNo); 6292 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 6293 if (!Info.noteFailure()) 6294 return false; 6295 Success = false; 6296 } 6297 ++ElementNo; 6298 } 6299 } 6300 6301 // Initialize members. 6302 for (const auto *Field : RD->fields()) { 6303 // Anonymous bit-fields are not considered members of the class for 6304 // purposes of aggregate initialization. 6305 if (Field->isUnnamedBitfield()) 6306 continue; 6307 6308 LValue Subobject = This; 6309 6310 bool HaveInit = ElementNo < E->getNumInits(); 6311 6312 // FIXME: Diagnostics here should point to the end of the initializer 6313 // list, not the start. 6314 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 6315 Subobject, Field, &Layout)) 6316 return false; 6317 6318 // Perform an implicit value-initialization for members beyond the end of 6319 // the initializer list. 6320 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 6321 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 6322 6323 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6324 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6325 isa<CXXDefaultInitExpr>(Init)); 6326 6327 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6328 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 6329 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 6330 FieldVal, Field))) { 6331 if (!Info.noteFailure()) 6332 return false; 6333 Success = false; 6334 } 6335 } 6336 6337 return Success; 6338 } 6339 6340 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 6341 QualType T) { 6342 // Note that E's type is not necessarily the type of our class here; we might 6343 // be initializing an array element instead. 6344 const CXXConstructorDecl *FD = E->getConstructor(); 6345 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 6346 6347 bool ZeroInit = E->requiresZeroInitialization(); 6348 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 6349 // If we've already performed zero-initialization, we're already done. 6350 if (!Result.isUninit()) 6351 return true; 6352 6353 // We can get here in two different ways: 6354 // 1) We're performing value-initialization, and should zero-initialize 6355 // the object, or 6356 // 2) We're performing default-initialization of an object with a trivial 6357 // constexpr default constructor, in which case we should start the 6358 // lifetimes of all the base subobjects (there can be no data member 6359 // subobjects in this case) per [basic.life]p1. 6360 // Either way, ZeroInitialization is appropriate. 6361 return ZeroInitialization(E, T); 6362 } 6363 6364 const FunctionDecl *Definition = nullptr; 6365 auto Body = FD->getBody(Definition); 6366 6367 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6368 return false; 6369 6370 // Avoid materializing a temporary for an elidable copy/move constructor. 6371 if (E->isElidable() && !ZeroInit) 6372 if (const MaterializeTemporaryExpr *ME 6373 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 6374 return Visit(ME->GetTemporaryExpr()); 6375 6376 if (ZeroInit && !ZeroInitialization(E, T)) 6377 return false; 6378 6379 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 6380 return HandleConstructorCall(E, This, Args, 6381 cast<CXXConstructorDecl>(Definition), Info, 6382 Result); 6383 } 6384 6385 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 6386 const CXXInheritedCtorInitExpr *E) { 6387 if (!Info.CurrentCall) { 6388 assert(Info.checkingPotentialConstantExpression()); 6389 return false; 6390 } 6391 6392 const CXXConstructorDecl *FD = E->getConstructor(); 6393 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 6394 return false; 6395 6396 const FunctionDecl *Definition = nullptr; 6397 auto Body = FD->getBody(Definition); 6398 6399 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6400 return false; 6401 6402 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 6403 cast<CXXConstructorDecl>(Definition), Info, 6404 Result); 6405 } 6406 6407 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 6408 const CXXStdInitializerListExpr *E) { 6409 const ConstantArrayType *ArrayType = 6410 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 6411 6412 LValue Array; 6413 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 6414 return false; 6415 6416 // Get a pointer to the first element of the array. 6417 Array.addArray(Info, E, ArrayType); 6418 6419 // FIXME: Perform the checks on the field types in SemaInit. 6420 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 6421 RecordDecl::field_iterator Field = Record->field_begin(); 6422 if (Field == Record->field_end()) 6423 return Error(E); 6424 6425 // Start pointer. 6426 if (!Field->getType()->isPointerType() || 6427 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6428 ArrayType->getElementType())) 6429 return Error(E); 6430 6431 // FIXME: What if the initializer_list type has base classes, etc? 6432 Result = APValue(APValue::UninitStruct(), 0, 2); 6433 Array.moveInto(Result.getStructField(0)); 6434 6435 if (++Field == Record->field_end()) 6436 return Error(E); 6437 6438 if (Field->getType()->isPointerType() && 6439 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6440 ArrayType->getElementType())) { 6441 // End pointer. 6442 if (!HandleLValueArrayAdjustment(Info, E, Array, 6443 ArrayType->getElementType(), 6444 ArrayType->getSize().getZExtValue())) 6445 return false; 6446 Array.moveInto(Result.getStructField(1)); 6447 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 6448 // Length. 6449 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 6450 else 6451 return Error(E); 6452 6453 if (++Field != Record->field_end()) 6454 return Error(E); 6455 6456 return true; 6457 } 6458 6459 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 6460 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 6461 if (ClosureClass->isInvalidDecl()) return false; 6462 6463 if (Info.checkingPotentialConstantExpression()) return true; 6464 6465 const size_t NumFields = 6466 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 6467 6468 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 6469 E->capture_init_end()) && 6470 "The number of lambda capture initializers should equal the number of " 6471 "fields within the closure type"); 6472 6473 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 6474 // Iterate through all the lambda's closure object's fields and initialize 6475 // them. 6476 auto *CaptureInitIt = E->capture_init_begin(); 6477 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 6478 bool Success = true; 6479 for (const auto *Field : ClosureClass->fields()) { 6480 assert(CaptureInitIt != E->capture_init_end()); 6481 // Get the initializer for this field 6482 Expr *const CurFieldInit = *CaptureInitIt++; 6483 6484 // If there is no initializer, either this is a VLA or an error has 6485 // occurred. 6486 if (!CurFieldInit) 6487 return Error(E); 6488 6489 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6490 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 6491 if (!Info.keepEvaluatingAfterFailure()) 6492 return false; 6493 Success = false; 6494 } 6495 ++CaptureIt; 6496 } 6497 return Success; 6498 } 6499 6500 static bool EvaluateRecord(const Expr *E, const LValue &This, 6501 APValue &Result, EvalInfo &Info) { 6502 assert(E->isRValue() && E->getType()->isRecordType() && 6503 "can't evaluate expression as a record rvalue"); 6504 return RecordExprEvaluator(Info, This, Result).Visit(E); 6505 } 6506 6507 //===----------------------------------------------------------------------===// 6508 // Temporary Evaluation 6509 // 6510 // Temporaries are represented in the AST as rvalues, but generally behave like 6511 // lvalues. The full-object of which the temporary is a subobject is implicitly 6512 // materialized so that a reference can bind to it. 6513 //===----------------------------------------------------------------------===// 6514 namespace { 6515 class TemporaryExprEvaluator 6516 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 6517 public: 6518 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 6519 LValueExprEvaluatorBaseTy(Info, Result, false) {} 6520 6521 /// Visit an expression which constructs the value of this temporary. 6522 bool VisitConstructExpr(const Expr *E) { 6523 Result.set(E, Info.CurrentCall->Index); 6524 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false), 6525 Info, Result, E); 6526 } 6527 6528 bool VisitCastExpr(const CastExpr *E) { 6529 switch (E->getCastKind()) { 6530 default: 6531 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 6532 6533 case CK_ConstructorConversion: 6534 return VisitConstructExpr(E->getSubExpr()); 6535 } 6536 } 6537 bool VisitInitListExpr(const InitListExpr *E) { 6538 return VisitConstructExpr(E); 6539 } 6540 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6541 return VisitConstructExpr(E); 6542 } 6543 bool VisitCallExpr(const CallExpr *E) { 6544 return VisitConstructExpr(E); 6545 } 6546 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 6547 return VisitConstructExpr(E); 6548 } 6549 bool VisitLambdaExpr(const LambdaExpr *E) { 6550 return VisitConstructExpr(E); 6551 } 6552 }; 6553 } // end anonymous namespace 6554 6555 /// Evaluate an expression of record type as a temporary. 6556 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 6557 assert(E->isRValue() && E->getType()->isRecordType()); 6558 return TemporaryExprEvaluator(Info, Result).Visit(E); 6559 } 6560 6561 //===----------------------------------------------------------------------===// 6562 // Vector Evaluation 6563 //===----------------------------------------------------------------------===// 6564 6565 namespace { 6566 class VectorExprEvaluator 6567 : public ExprEvaluatorBase<VectorExprEvaluator> { 6568 APValue &Result; 6569 public: 6570 6571 VectorExprEvaluator(EvalInfo &info, APValue &Result) 6572 : ExprEvaluatorBaseTy(info), Result(Result) {} 6573 6574 bool Success(ArrayRef<APValue> V, const Expr *E) { 6575 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 6576 // FIXME: remove this APValue copy. 6577 Result = APValue(V.data(), V.size()); 6578 return true; 6579 } 6580 bool Success(const APValue &V, const Expr *E) { 6581 assert(V.isVector()); 6582 Result = V; 6583 return true; 6584 } 6585 bool ZeroInitialization(const Expr *E); 6586 6587 bool VisitUnaryReal(const UnaryOperator *E) 6588 { return Visit(E->getSubExpr()); } 6589 bool VisitCastExpr(const CastExpr* E); 6590 bool VisitInitListExpr(const InitListExpr *E); 6591 bool VisitUnaryImag(const UnaryOperator *E); 6592 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 6593 // binary comparisons, binary and/or/xor, 6594 // shufflevector, ExtVectorElementExpr 6595 }; 6596 } // end anonymous namespace 6597 6598 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 6599 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 6600 return VectorExprEvaluator(Info, Result).Visit(E); 6601 } 6602 6603 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 6604 const VectorType *VTy = E->getType()->castAs<VectorType>(); 6605 unsigned NElts = VTy->getNumElements(); 6606 6607 const Expr *SE = E->getSubExpr(); 6608 QualType SETy = SE->getType(); 6609 6610 switch (E->getCastKind()) { 6611 case CK_VectorSplat: { 6612 APValue Val = APValue(); 6613 if (SETy->isIntegerType()) { 6614 APSInt IntResult; 6615 if (!EvaluateInteger(SE, IntResult, Info)) 6616 return false; 6617 Val = APValue(std::move(IntResult)); 6618 } else if (SETy->isRealFloatingType()) { 6619 APFloat FloatResult(0.0); 6620 if (!EvaluateFloat(SE, FloatResult, Info)) 6621 return false; 6622 Val = APValue(std::move(FloatResult)); 6623 } else { 6624 return Error(E); 6625 } 6626 6627 // Splat and create vector APValue. 6628 SmallVector<APValue, 4> Elts(NElts, Val); 6629 return Success(Elts, E); 6630 } 6631 case CK_BitCast: { 6632 // Evaluate the operand into an APInt we can extract from. 6633 llvm::APInt SValInt; 6634 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 6635 return false; 6636 // Extract the elements 6637 QualType EltTy = VTy->getElementType(); 6638 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 6639 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 6640 SmallVector<APValue, 4> Elts; 6641 if (EltTy->isRealFloatingType()) { 6642 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 6643 unsigned FloatEltSize = EltSize; 6644 if (&Sem == &APFloat::x87DoubleExtended()) 6645 FloatEltSize = 80; 6646 for (unsigned i = 0; i < NElts; i++) { 6647 llvm::APInt Elt; 6648 if (BigEndian) 6649 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 6650 else 6651 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 6652 Elts.push_back(APValue(APFloat(Sem, Elt))); 6653 } 6654 } else if (EltTy->isIntegerType()) { 6655 for (unsigned i = 0; i < NElts; i++) { 6656 llvm::APInt Elt; 6657 if (BigEndian) 6658 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 6659 else 6660 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 6661 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 6662 } 6663 } else { 6664 return Error(E); 6665 } 6666 return Success(Elts, E); 6667 } 6668 default: 6669 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6670 } 6671 } 6672 6673 bool 6674 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6675 const VectorType *VT = E->getType()->castAs<VectorType>(); 6676 unsigned NumInits = E->getNumInits(); 6677 unsigned NumElements = VT->getNumElements(); 6678 6679 QualType EltTy = VT->getElementType(); 6680 SmallVector<APValue, 4> Elements; 6681 6682 // The number of initializers can be less than the number of 6683 // vector elements. For OpenCL, this can be due to nested vector 6684 // initialization. For GCC compatibility, missing trailing elements 6685 // should be initialized with zeroes. 6686 unsigned CountInits = 0, CountElts = 0; 6687 while (CountElts < NumElements) { 6688 // Handle nested vector initialization. 6689 if (CountInits < NumInits 6690 && E->getInit(CountInits)->getType()->isVectorType()) { 6691 APValue v; 6692 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 6693 return Error(E); 6694 unsigned vlen = v.getVectorLength(); 6695 for (unsigned j = 0; j < vlen; j++) 6696 Elements.push_back(v.getVectorElt(j)); 6697 CountElts += vlen; 6698 } else if (EltTy->isIntegerType()) { 6699 llvm::APSInt sInt(32); 6700 if (CountInits < NumInits) { 6701 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 6702 return false; 6703 } else // trailing integer zero. 6704 sInt = Info.Ctx.MakeIntValue(0, EltTy); 6705 Elements.push_back(APValue(sInt)); 6706 CountElts++; 6707 } else { 6708 llvm::APFloat f(0.0); 6709 if (CountInits < NumInits) { 6710 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 6711 return false; 6712 } else // trailing float zero. 6713 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 6714 Elements.push_back(APValue(f)); 6715 CountElts++; 6716 } 6717 CountInits++; 6718 } 6719 return Success(Elements, E); 6720 } 6721 6722 bool 6723 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 6724 const VectorType *VT = E->getType()->getAs<VectorType>(); 6725 QualType EltTy = VT->getElementType(); 6726 APValue ZeroElement; 6727 if (EltTy->isIntegerType()) 6728 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 6729 else 6730 ZeroElement = 6731 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 6732 6733 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 6734 return Success(Elements, E); 6735 } 6736 6737 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 6738 VisitIgnoredValue(E->getSubExpr()); 6739 return ZeroInitialization(E); 6740 } 6741 6742 //===----------------------------------------------------------------------===// 6743 // Array Evaluation 6744 //===----------------------------------------------------------------------===// 6745 6746 namespace { 6747 class ArrayExprEvaluator 6748 : public ExprEvaluatorBase<ArrayExprEvaluator> { 6749 const LValue &This; 6750 APValue &Result; 6751 public: 6752 6753 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 6754 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 6755 6756 bool Success(const APValue &V, const Expr *E) { 6757 assert((V.isArray() || V.isLValue()) && 6758 "expected array or string literal"); 6759 Result = V; 6760 return true; 6761 } 6762 6763 bool ZeroInitialization(const Expr *E) { 6764 const ConstantArrayType *CAT = 6765 Info.Ctx.getAsConstantArrayType(E->getType()); 6766 if (!CAT) 6767 return Error(E); 6768 6769 Result = APValue(APValue::UninitArray(), 0, 6770 CAT->getSize().getZExtValue()); 6771 if (!Result.hasArrayFiller()) return true; 6772 6773 // Zero-initialize all elements. 6774 LValue Subobject = This; 6775 Subobject.addArray(Info, E, CAT); 6776 ImplicitValueInitExpr VIE(CAT->getElementType()); 6777 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 6778 } 6779 6780 bool VisitCallExpr(const CallExpr *E) { 6781 return handleCallExpr(E, Result, &This); 6782 } 6783 bool VisitInitListExpr(const InitListExpr *E); 6784 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 6785 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 6786 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 6787 const LValue &Subobject, 6788 APValue *Value, QualType Type); 6789 }; 6790 } // end anonymous namespace 6791 6792 static bool EvaluateArray(const Expr *E, const LValue &This, 6793 APValue &Result, EvalInfo &Info) { 6794 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 6795 return ArrayExprEvaluator(Info, This, Result).Visit(E); 6796 } 6797 6798 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6799 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 6800 if (!CAT) 6801 return Error(E); 6802 6803 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 6804 // an appropriately-typed string literal enclosed in braces. 6805 if (E->isStringLiteralInit()) { 6806 LValue LV; 6807 if (!EvaluateLValue(E->getInit(0), LV, Info)) 6808 return false; 6809 APValue Val; 6810 LV.moveInto(Val); 6811 return Success(Val, E); 6812 } 6813 6814 bool Success = true; 6815 6816 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 6817 "zero-initialized array shouldn't have any initialized elts"); 6818 APValue Filler; 6819 if (Result.isArray() && Result.hasArrayFiller()) 6820 Filler = Result.getArrayFiller(); 6821 6822 unsigned NumEltsToInit = E->getNumInits(); 6823 unsigned NumElts = CAT->getSize().getZExtValue(); 6824 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 6825 6826 // If the initializer might depend on the array index, run it for each 6827 // array element. For now, just whitelist non-class value-initialization. 6828 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr)) 6829 NumEltsToInit = NumElts; 6830 6831 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 6832 6833 // If the array was previously zero-initialized, preserve the 6834 // zero-initialized values. 6835 if (!Filler.isUninit()) { 6836 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 6837 Result.getArrayInitializedElt(I) = Filler; 6838 if (Result.hasArrayFiller()) 6839 Result.getArrayFiller() = Filler; 6840 } 6841 6842 LValue Subobject = This; 6843 Subobject.addArray(Info, E, CAT); 6844 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 6845 const Expr *Init = 6846 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 6847 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 6848 Info, Subobject, Init) || 6849 !HandleLValueArrayAdjustment(Info, Init, Subobject, 6850 CAT->getElementType(), 1)) { 6851 if (!Info.noteFailure()) 6852 return false; 6853 Success = false; 6854 } 6855 } 6856 6857 if (!Result.hasArrayFiller()) 6858 return Success; 6859 6860 // If we get here, we have a trivial filler, which we can just evaluate 6861 // once and splat over the rest of the array elements. 6862 assert(FillerExpr && "no array filler for incomplete init list"); 6863 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 6864 FillerExpr) && Success; 6865 } 6866 6867 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 6868 if (E->getCommonExpr() && 6869 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false), 6870 Info, E->getCommonExpr()->getSourceExpr())) 6871 return false; 6872 6873 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 6874 6875 uint64_t Elements = CAT->getSize().getZExtValue(); 6876 Result = APValue(APValue::UninitArray(), Elements, Elements); 6877 6878 LValue Subobject = This; 6879 Subobject.addArray(Info, E, CAT); 6880 6881 bool Success = true; 6882 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 6883 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 6884 Info, Subobject, E->getSubExpr()) || 6885 !HandleLValueArrayAdjustment(Info, E, Subobject, 6886 CAT->getElementType(), 1)) { 6887 if (!Info.noteFailure()) 6888 return false; 6889 Success = false; 6890 } 6891 } 6892 6893 return Success; 6894 } 6895 6896 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 6897 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 6898 } 6899 6900 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 6901 const LValue &Subobject, 6902 APValue *Value, 6903 QualType Type) { 6904 bool HadZeroInit = !Value->isUninit(); 6905 6906 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 6907 unsigned N = CAT->getSize().getZExtValue(); 6908 6909 // Preserve the array filler if we had prior zero-initialization. 6910 APValue Filler = 6911 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 6912 : APValue(); 6913 6914 *Value = APValue(APValue::UninitArray(), N, N); 6915 6916 if (HadZeroInit) 6917 for (unsigned I = 0; I != N; ++I) 6918 Value->getArrayInitializedElt(I) = Filler; 6919 6920 // Initialize the elements. 6921 LValue ArrayElt = Subobject; 6922 ArrayElt.addArray(Info, E, CAT); 6923 for (unsigned I = 0; I != N; ++I) 6924 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 6925 CAT->getElementType()) || 6926 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 6927 CAT->getElementType(), 1)) 6928 return false; 6929 6930 return true; 6931 } 6932 6933 if (!Type->isRecordType()) 6934 return Error(E); 6935 6936 return RecordExprEvaluator(Info, Subobject, *Value) 6937 .VisitCXXConstructExpr(E, Type); 6938 } 6939 6940 //===----------------------------------------------------------------------===// 6941 // Integer Evaluation 6942 // 6943 // As a GNU extension, we support casting pointers to sufficiently-wide integer 6944 // types and back in constant folding. Integer values are thus represented 6945 // either as an integer-valued APValue, or as an lvalue-valued APValue. 6946 //===----------------------------------------------------------------------===// 6947 6948 namespace { 6949 class IntExprEvaluator 6950 : public ExprEvaluatorBase<IntExprEvaluator> { 6951 APValue &Result; 6952 public: 6953 IntExprEvaluator(EvalInfo &info, APValue &result) 6954 : ExprEvaluatorBaseTy(info), Result(result) {} 6955 6956 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 6957 assert(E->getType()->isIntegralOrEnumerationType() && 6958 "Invalid evaluation result."); 6959 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 6960 "Invalid evaluation result."); 6961 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 6962 "Invalid evaluation result."); 6963 Result = APValue(SI); 6964 return true; 6965 } 6966 bool Success(const llvm::APSInt &SI, const Expr *E) { 6967 return Success(SI, E, Result); 6968 } 6969 6970 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 6971 assert(E->getType()->isIntegralOrEnumerationType() && 6972 "Invalid evaluation result."); 6973 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 6974 "Invalid evaluation result."); 6975 Result = APValue(APSInt(I)); 6976 Result.getInt().setIsUnsigned( 6977 E->getType()->isUnsignedIntegerOrEnumerationType()); 6978 return true; 6979 } 6980 bool Success(const llvm::APInt &I, const Expr *E) { 6981 return Success(I, E, Result); 6982 } 6983 6984 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 6985 assert(E->getType()->isIntegralOrEnumerationType() && 6986 "Invalid evaluation result."); 6987 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 6988 return true; 6989 } 6990 bool Success(uint64_t Value, const Expr *E) { 6991 return Success(Value, E, Result); 6992 } 6993 6994 bool Success(CharUnits Size, const Expr *E) { 6995 return Success(Size.getQuantity(), E); 6996 } 6997 6998 bool Success(const APValue &V, const Expr *E) { 6999 if (V.isLValue() || V.isAddrLabelDiff()) { 7000 Result = V; 7001 return true; 7002 } 7003 return Success(V.getInt(), E); 7004 } 7005 7006 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 7007 7008 //===--------------------------------------------------------------------===// 7009 // Visitor Methods 7010 //===--------------------------------------------------------------------===// 7011 7012 bool VisitIntegerLiteral(const IntegerLiteral *E) { 7013 return Success(E->getValue(), E); 7014 } 7015 bool VisitCharacterLiteral(const CharacterLiteral *E) { 7016 return Success(E->getValue(), E); 7017 } 7018 7019 bool CheckReferencedDecl(const Expr *E, const Decl *D); 7020 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7021 if (CheckReferencedDecl(E, E->getDecl())) 7022 return true; 7023 7024 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 7025 } 7026 bool VisitMemberExpr(const MemberExpr *E) { 7027 if (CheckReferencedDecl(E, E->getMemberDecl())) { 7028 VisitIgnoredBaseExpression(E->getBase()); 7029 return true; 7030 } 7031 7032 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 7033 } 7034 7035 bool VisitCallExpr(const CallExpr *E); 7036 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 7037 bool VisitBinaryOperator(const BinaryOperator *E); 7038 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 7039 bool VisitUnaryOperator(const UnaryOperator *E); 7040 7041 bool VisitCastExpr(const CastExpr* E); 7042 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 7043 7044 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 7045 return Success(E->getValue(), E); 7046 } 7047 7048 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 7049 return Success(E->getValue(), E); 7050 } 7051 7052 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 7053 if (Info.ArrayInitIndex == uint64_t(-1)) { 7054 // We were asked to evaluate this subexpression independent of the 7055 // enclosing ArrayInitLoopExpr. We can't do that. 7056 Info.FFDiag(E); 7057 return false; 7058 } 7059 return Success(Info.ArrayInitIndex, E); 7060 } 7061 7062 // Note, GNU defines __null as an integer, not a pointer. 7063 bool VisitGNUNullExpr(const GNUNullExpr *E) { 7064 return ZeroInitialization(E); 7065 } 7066 7067 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 7068 return Success(E->getValue(), E); 7069 } 7070 7071 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 7072 return Success(E->getValue(), E); 7073 } 7074 7075 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 7076 return Success(E->getValue(), E); 7077 } 7078 7079 bool VisitUnaryReal(const UnaryOperator *E); 7080 bool VisitUnaryImag(const UnaryOperator *E); 7081 7082 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 7083 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 7084 7085 // FIXME: Missing: array subscript of vector, member of vector 7086 }; 7087 } // end anonymous namespace 7088 7089 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 7090 /// produce either the integer value or a pointer. 7091 /// 7092 /// GCC has a heinous extension which folds casts between pointer types and 7093 /// pointer-sized integral types. We support this by allowing the evaluation of 7094 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 7095 /// Some simple arithmetic on such values is supported (they are treated much 7096 /// like char*). 7097 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 7098 EvalInfo &Info) { 7099 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 7100 return IntExprEvaluator(Info, Result).Visit(E); 7101 } 7102 7103 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 7104 APValue Val; 7105 if (!EvaluateIntegerOrLValue(E, Val, Info)) 7106 return false; 7107 if (!Val.isInt()) { 7108 // FIXME: It would be better to produce the diagnostic for casting 7109 // a pointer to an integer. 7110 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 7111 return false; 7112 } 7113 Result = Val.getInt(); 7114 return true; 7115 } 7116 7117 /// Check whether the given declaration can be directly converted to an integral 7118 /// rvalue. If not, no diagnostic is produced; there are other things we can 7119 /// try. 7120 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 7121 // Enums are integer constant exprs. 7122 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 7123 // Check for signedness/width mismatches between E type and ECD value. 7124 bool SameSign = (ECD->getInitVal().isSigned() 7125 == E->getType()->isSignedIntegerOrEnumerationType()); 7126 bool SameWidth = (ECD->getInitVal().getBitWidth() 7127 == Info.Ctx.getIntWidth(E->getType())); 7128 if (SameSign && SameWidth) 7129 return Success(ECD->getInitVal(), E); 7130 else { 7131 // Get rid of mismatch (otherwise Success assertions will fail) 7132 // by computing a new value matching the type of E. 7133 llvm::APSInt Val = ECD->getInitVal(); 7134 if (!SameSign) 7135 Val.setIsSigned(!ECD->getInitVal().isSigned()); 7136 if (!SameWidth) 7137 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 7138 return Success(Val, E); 7139 } 7140 } 7141 return false; 7142 } 7143 7144 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 7145 /// as GCC. 7146 static int EvaluateBuiltinClassifyType(const CallExpr *E, 7147 const LangOptions &LangOpts) { 7148 // The following enum mimics the values returned by GCC. 7149 // FIXME: Does GCC differ between lvalue and rvalue references here? 7150 enum gcc_type_class { 7151 no_type_class = -1, 7152 void_type_class, integer_type_class, char_type_class, 7153 enumeral_type_class, boolean_type_class, 7154 pointer_type_class, reference_type_class, offset_type_class, 7155 real_type_class, complex_type_class, 7156 function_type_class, method_type_class, 7157 record_type_class, union_type_class, 7158 array_type_class, string_type_class, 7159 lang_type_class 7160 }; 7161 7162 // If no argument was supplied, default to "no_type_class". This isn't 7163 // ideal, however it is what gcc does. 7164 if (E->getNumArgs() == 0) 7165 return no_type_class; 7166 7167 QualType CanTy = E->getArg(0)->getType().getCanonicalType(); 7168 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 7169 7170 switch (CanTy->getTypeClass()) { 7171 #define TYPE(ID, BASE) 7172 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 7173 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 7174 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 7175 #include "clang/AST/TypeNodes.def" 7176 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7177 7178 case Type::Builtin: 7179 switch (BT->getKind()) { 7180 #define BUILTIN_TYPE(ID, SINGLETON_ID) 7181 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class; 7182 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class; 7183 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break; 7184 #include "clang/AST/BuiltinTypes.def" 7185 case BuiltinType::Void: 7186 return void_type_class; 7187 7188 case BuiltinType::Bool: 7189 return boolean_type_class; 7190 7191 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class 7192 case BuiltinType::UChar: 7193 case BuiltinType::UShort: 7194 case BuiltinType::UInt: 7195 case BuiltinType::ULong: 7196 case BuiltinType::ULongLong: 7197 case BuiltinType::UInt128: 7198 return integer_type_class; 7199 7200 case BuiltinType::NullPtr: 7201 return pointer_type_class; 7202 7203 case BuiltinType::WChar_U: 7204 case BuiltinType::Char16: 7205 case BuiltinType::Char32: 7206 case BuiltinType::ObjCId: 7207 case BuiltinType::ObjCClass: 7208 case BuiltinType::ObjCSel: 7209 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7210 case BuiltinType::Id: 7211 #include "clang/Basic/OpenCLImageTypes.def" 7212 case BuiltinType::OCLSampler: 7213 case BuiltinType::OCLEvent: 7214 case BuiltinType::OCLClkEvent: 7215 case BuiltinType::OCLQueue: 7216 case BuiltinType::OCLReserveID: 7217 case BuiltinType::Dependent: 7218 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7219 }; 7220 break; 7221 7222 case Type::Enum: 7223 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class; 7224 break; 7225 7226 case Type::Pointer: 7227 return pointer_type_class; 7228 break; 7229 7230 case Type::MemberPointer: 7231 if (CanTy->isMemberDataPointerType()) 7232 return offset_type_class; 7233 else { 7234 // We expect member pointers to be either data or function pointers, 7235 // nothing else. 7236 assert(CanTy->isMemberFunctionPointerType()); 7237 return method_type_class; 7238 } 7239 7240 case Type::Complex: 7241 return complex_type_class; 7242 7243 case Type::FunctionNoProto: 7244 case Type::FunctionProto: 7245 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class; 7246 7247 case Type::Record: 7248 if (const RecordType *RT = CanTy->getAs<RecordType>()) { 7249 switch (RT->getDecl()->getTagKind()) { 7250 case TagTypeKind::TTK_Struct: 7251 case TagTypeKind::TTK_Class: 7252 case TagTypeKind::TTK_Interface: 7253 return record_type_class; 7254 7255 case TagTypeKind::TTK_Enum: 7256 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class; 7257 7258 case TagTypeKind::TTK_Union: 7259 return union_type_class; 7260 } 7261 } 7262 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7263 7264 case Type::ConstantArray: 7265 case Type::VariableArray: 7266 case Type::IncompleteArray: 7267 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class; 7268 7269 case Type::BlockPointer: 7270 case Type::LValueReference: 7271 case Type::RValueReference: 7272 case Type::Vector: 7273 case Type::ExtVector: 7274 case Type::Auto: 7275 case Type::DeducedTemplateSpecialization: 7276 case Type::ObjCObject: 7277 case Type::ObjCInterface: 7278 case Type::ObjCObjectPointer: 7279 case Type::Pipe: 7280 case Type::Atomic: 7281 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7282 } 7283 7284 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type"); 7285 } 7286 7287 /// EvaluateBuiltinConstantPForLValue - Determine the result of 7288 /// __builtin_constant_p when applied to the given lvalue. 7289 /// 7290 /// An lvalue is only "constant" if it is a pointer or reference to the first 7291 /// character of a string literal. 7292 template<typename LValue> 7293 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) { 7294 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>(); 7295 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero(); 7296 } 7297 7298 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 7299 /// GCC as we can manage. 7300 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) { 7301 QualType ArgType = Arg->getType(); 7302 7303 // __builtin_constant_p always has one operand. The rules which gcc follows 7304 // are not precisely documented, but are as follows: 7305 // 7306 // - If the operand is of integral, floating, complex or enumeration type, 7307 // and can be folded to a known value of that type, it returns 1. 7308 // - If the operand and can be folded to a pointer to the first character 7309 // of a string literal (or such a pointer cast to an integral type), it 7310 // returns 1. 7311 // 7312 // Otherwise, it returns 0. 7313 // 7314 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 7315 // its support for this does not currently work. 7316 if (ArgType->isIntegralOrEnumerationType()) { 7317 Expr::EvalResult Result; 7318 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects) 7319 return false; 7320 7321 APValue &V = Result.Val; 7322 if (V.getKind() == APValue::Int) 7323 return true; 7324 if (V.getKind() == APValue::LValue) 7325 return EvaluateBuiltinConstantPForLValue(V); 7326 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) { 7327 return Arg->isEvaluatable(Ctx); 7328 } else if (ArgType->isPointerType() || Arg->isGLValue()) { 7329 LValue LV; 7330 Expr::EvalStatus Status; 7331 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 7332 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info) 7333 : EvaluatePointer(Arg, LV, Info)) && 7334 !Status.HasSideEffects) 7335 return EvaluateBuiltinConstantPForLValue(LV); 7336 } 7337 7338 // Anything else isn't considered to be sufficiently constant. 7339 return false; 7340 } 7341 7342 /// Retrieves the "underlying object type" of the given expression, 7343 /// as used by __builtin_object_size. 7344 static QualType getObjectType(APValue::LValueBase B) { 7345 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 7346 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 7347 return VD->getType(); 7348 } else if (const Expr *E = B.get<const Expr*>()) { 7349 if (isa<CompoundLiteralExpr>(E)) 7350 return E->getType(); 7351 } 7352 7353 return QualType(); 7354 } 7355 7356 /// A more selective version of E->IgnoreParenCasts for 7357 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 7358 /// to change the type of E. 7359 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 7360 /// 7361 /// Always returns an RValue with a pointer representation. 7362 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 7363 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 7364 7365 auto *NoParens = E->IgnoreParens(); 7366 auto *Cast = dyn_cast<CastExpr>(NoParens); 7367 if (Cast == nullptr) 7368 return NoParens; 7369 7370 // We only conservatively allow a few kinds of casts, because this code is 7371 // inherently a simple solution that seeks to support the common case. 7372 auto CastKind = Cast->getCastKind(); 7373 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 7374 CastKind != CK_AddressSpaceConversion) 7375 return NoParens; 7376 7377 auto *SubExpr = Cast->getSubExpr(); 7378 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 7379 return NoParens; 7380 return ignorePointerCastsAndParens(SubExpr); 7381 } 7382 7383 /// Checks to see if the given LValue's Designator is at the end of the LValue's 7384 /// record layout. e.g. 7385 /// struct { struct { int a, b; } fst, snd; } obj; 7386 /// obj.fst // no 7387 /// obj.snd // yes 7388 /// obj.fst.a // no 7389 /// obj.fst.b // no 7390 /// obj.snd.a // no 7391 /// obj.snd.b // yes 7392 /// 7393 /// Please note: this function is specialized for how __builtin_object_size 7394 /// views "objects". 7395 /// 7396 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 7397 /// correct result, it will always return true. 7398 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 7399 assert(!LVal.Designator.Invalid); 7400 7401 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 7402 const RecordDecl *Parent = FD->getParent(); 7403 Invalid = Parent->isInvalidDecl(); 7404 if (Invalid || Parent->isUnion()) 7405 return true; 7406 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 7407 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 7408 }; 7409 7410 auto &Base = LVal.getLValueBase(); 7411 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 7412 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 7413 bool Invalid; 7414 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7415 return Invalid; 7416 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 7417 for (auto *FD : IFD->chain()) { 7418 bool Invalid; 7419 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 7420 return Invalid; 7421 } 7422 } 7423 } 7424 7425 unsigned I = 0; 7426 QualType BaseType = getType(Base); 7427 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 7428 // If we don't know the array bound, conservatively assume we're looking at 7429 // the final array element. 7430 ++I; 7431 if (BaseType->isIncompleteArrayType()) 7432 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 7433 else 7434 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 7435 } 7436 7437 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 7438 const auto &Entry = LVal.Designator.Entries[I]; 7439 if (BaseType->isArrayType()) { 7440 // Because __builtin_object_size treats arrays as objects, we can ignore 7441 // the index iff this is the last array in the Designator. 7442 if (I + 1 == E) 7443 return true; 7444 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 7445 uint64_t Index = Entry.ArrayIndex; 7446 if (Index + 1 != CAT->getSize()) 7447 return false; 7448 BaseType = CAT->getElementType(); 7449 } else if (BaseType->isAnyComplexType()) { 7450 const auto *CT = BaseType->castAs<ComplexType>(); 7451 uint64_t Index = Entry.ArrayIndex; 7452 if (Index != 1) 7453 return false; 7454 BaseType = CT->getElementType(); 7455 } else if (auto *FD = getAsField(Entry)) { 7456 bool Invalid; 7457 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7458 return Invalid; 7459 BaseType = FD->getType(); 7460 } else { 7461 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 7462 return false; 7463 } 7464 } 7465 return true; 7466 } 7467 7468 /// Tests to see if the LValue has a user-specified designator (that isn't 7469 /// necessarily valid). Note that this always returns 'true' if the LValue has 7470 /// an unsized array as its first designator entry, because there's currently no 7471 /// way to tell if the user typed *foo or foo[0]. 7472 static bool refersToCompleteObject(const LValue &LVal) { 7473 if (LVal.Designator.Invalid) 7474 return false; 7475 7476 if (!LVal.Designator.Entries.empty()) 7477 return LVal.Designator.isMostDerivedAnUnsizedArray(); 7478 7479 if (!LVal.InvalidBase) 7480 return true; 7481 7482 // If `E` is a MemberExpr, then the first part of the designator is hiding in 7483 // the LValueBase. 7484 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 7485 return !E || !isa<MemberExpr>(E); 7486 } 7487 7488 /// Attempts to detect a user writing into a piece of memory that's impossible 7489 /// to figure out the size of by just using types. 7490 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 7491 const SubobjectDesignator &Designator = LVal.Designator; 7492 // Notes: 7493 // - Users can only write off of the end when we have an invalid base. Invalid 7494 // bases imply we don't know where the memory came from. 7495 // - We used to be a bit more aggressive here; we'd only be conservative if 7496 // the array at the end was flexible, or if it had 0 or 1 elements. This 7497 // broke some common standard library extensions (PR30346), but was 7498 // otherwise seemingly fine. It may be useful to reintroduce this behavior 7499 // with some sort of whitelist. OTOH, it seems that GCC is always 7500 // conservative with the last element in structs (if it's an array), so our 7501 // current behavior is more compatible than a whitelisting approach would 7502 // be. 7503 return LVal.InvalidBase && 7504 Designator.Entries.size() == Designator.MostDerivedPathLength && 7505 Designator.MostDerivedIsArrayElement && 7506 isDesignatorAtObjectEnd(Ctx, LVal); 7507 } 7508 7509 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 7510 /// Fails if the conversion would cause loss of precision. 7511 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 7512 CharUnits &Result) { 7513 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 7514 if (Int.ugt(CharUnitsMax)) 7515 return false; 7516 Result = CharUnits::fromQuantity(Int.getZExtValue()); 7517 return true; 7518 } 7519 7520 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 7521 /// determine how many bytes exist from the beginning of the object to either 7522 /// the end of the current subobject, or the end of the object itself, depending 7523 /// on what the LValue looks like + the value of Type. 7524 /// 7525 /// If this returns false, the value of Result is undefined. 7526 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 7527 unsigned Type, const LValue &LVal, 7528 CharUnits &EndOffset) { 7529 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 7530 7531 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 7532 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 7533 return false; 7534 return HandleSizeof(Info, ExprLoc, Ty, Result); 7535 }; 7536 7537 // We want to evaluate the size of the entire object. This is a valid fallback 7538 // for when Type=1 and the designator is invalid, because we're asked for an 7539 // upper-bound. 7540 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 7541 // Type=3 wants a lower bound, so we can't fall back to this. 7542 if (Type == 3 && !DetermineForCompleteObject) 7543 return false; 7544 7545 llvm::APInt APEndOffset; 7546 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7547 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 7548 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 7549 7550 if (LVal.InvalidBase) 7551 return false; 7552 7553 QualType BaseTy = getObjectType(LVal.getLValueBase()); 7554 return CheckedHandleSizeof(BaseTy, EndOffset); 7555 } 7556 7557 // We want to evaluate the size of a subobject. 7558 const SubobjectDesignator &Designator = LVal.Designator; 7559 7560 // The following is a moderately common idiom in C: 7561 // 7562 // struct Foo { int a; char c[1]; }; 7563 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 7564 // strcpy(&F->c[0], Bar); 7565 // 7566 // In order to not break too much legacy code, we need to support it. 7567 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 7568 // If we can resolve this to an alloc_size call, we can hand that back, 7569 // because we know for certain how many bytes there are to write to. 7570 llvm::APInt APEndOffset; 7571 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7572 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 7573 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 7574 7575 // If we cannot determine the size of the initial allocation, then we can't 7576 // given an accurate upper-bound. However, we are still able to give 7577 // conservative lower-bounds for Type=3. 7578 if (Type == 1) 7579 return false; 7580 } 7581 7582 CharUnits BytesPerElem; 7583 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 7584 return false; 7585 7586 // According to the GCC documentation, we want the size of the subobject 7587 // denoted by the pointer. But that's not quite right -- what we actually 7588 // want is the size of the immediately-enclosing array, if there is one. 7589 int64_t ElemsRemaining; 7590 if (Designator.MostDerivedIsArrayElement && 7591 Designator.Entries.size() == Designator.MostDerivedPathLength) { 7592 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 7593 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex; 7594 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 7595 } else { 7596 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 7597 } 7598 7599 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 7600 return true; 7601 } 7602 7603 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful, 7604 /// returns true and stores the result in @p Size. 7605 /// 7606 /// If @p WasError is non-null, this will report whether the failure to evaluate 7607 /// is to be treated as an Error in IntExprEvaluator. 7608 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 7609 EvalInfo &Info, uint64_t &Size) { 7610 // Determine the denoted object. 7611 LValue LVal; 7612 { 7613 // The operand of __builtin_object_size is never evaluated for side-effects. 7614 // If there are any, but we can determine the pointed-to object anyway, then 7615 // ignore the side-effects. 7616 SpeculativeEvaluationRAII SpeculativeEval(Info); 7617 FoldOffsetRAII Fold(Info); 7618 7619 if (E->isGLValue()) { 7620 // It's possible for us to be given GLValues if we're called via 7621 // Expr::tryEvaluateObjectSize. 7622 APValue RVal; 7623 if (!EvaluateAsRValue(Info, E, RVal)) 7624 return false; 7625 LVal.setFrom(Info.Ctx, RVal); 7626 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 7627 /*InvalidBaseOK=*/true)) 7628 return false; 7629 } 7630 7631 // If we point to before the start of the object, there are no accessible 7632 // bytes. 7633 if (LVal.getLValueOffset().isNegative()) { 7634 Size = 0; 7635 return true; 7636 } 7637 7638 CharUnits EndOffset; 7639 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 7640 return false; 7641 7642 // If we've fallen outside of the end offset, just pretend there's nothing to 7643 // write to/read from. 7644 if (EndOffset <= LVal.getLValueOffset()) 7645 Size = 0; 7646 else 7647 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 7648 return true; 7649 } 7650 7651 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 7652 if (unsigned BuiltinOp = E->getBuiltinCallee()) 7653 return VisitBuiltinCallExpr(E, BuiltinOp); 7654 7655 return ExprEvaluatorBaseTy::VisitCallExpr(E); 7656 } 7657 7658 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 7659 unsigned BuiltinOp) { 7660 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 7661 default: 7662 return ExprEvaluatorBaseTy::VisitCallExpr(E); 7663 7664 case Builtin::BI__builtin_object_size: { 7665 // The type was checked when we built the expression. 7666 unsigned Type = 7667 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 7668 assert(Type <= 3 && "unexpected type"); 7669 7670 uint64_t Size; 7671 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 7672 return Success(Size, E); 7673 7674 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 7675 return Success((Type & 2) ? 0 : -1, E); 7676 7677 // Expression had no side effects, but we couldn't statically determine the 7678 // size of the referenced object. 7679 switch (Info.EvalMode) { 7680 case EvalInfo::EM_ConstantExpression: 7681 case EvalInfo::EM_PotentialConstantExpression: 7682 case EvalInfo::EM_ConstantFold: 7683 case EvalInfo::EM_EvaluateForOverflow: 7684 case EvalInfo::EM_IgnoreSideEffects: 7685 case EvalInfo::EM_OffsetFold: 7686 // Leave it to IR generation. 7687 return Error(E); 7688 case EvalInfo::EM_ConstantExpressionUnevaluated: 7689 case EvalInfo::EM_PotentialConstantExpressionUnevaluated: 7690 // Reduce it to a constant now. 7691 return Success((Type & 2) ? 0 : -1, E); 7692 } 7693 7694 llvm_unreachable("unexpected EvalMode"); 7695 } 7696 7697 case Builtin::BI__builtin_bswap16: 7698 case Builtin::BI__builtin_bswap32: 7699 case Builtin::BI__builtin_bswap64: { 7700 APSInt Val; 7701 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7702 return false; 7703 7704 return Success(Val.byteSwap(), E); 7705 } 7706 7707 case Builtin::BI__builtin_classify_type: 7708 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 7709 7710 // FIXME: BI__builtin_clrsb 7711 // FIXME: BI__builtin_clrsbl 7712 // FIXME: BI__builtin_clrsbll 7713 7714 case Builtin::BI__builtin_clz: 7715 case Builtin::BI__builtin_clzl: 7716 case Builtin::BI__builtin_clzll: 7717 case Builtin::BI__builtin_clzs: { 7718 APSInt Val; 7719 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7720 return false; 7721 if (!Val) 7722 return Error(E); 7723 7724 return Success(Val.countLeadingZeros(), E); 7725 } 7726 7727 case Builtin::BI__builtin_constant_p: 7728 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E); 7729 7730 case Builtin::BI__builtin_ctz: 7731 case Builtin::BI__builtin_ctzl: 7732 case Builtin::BI__builtin_ctzll: 7733 case Builtin::BI__builtin_ctzs: { 7734 APSInt Val; 7735 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7736 return false; 7737 if (!Val) 7738 return Error(E); 7739 7740 return Success(Val.countTrailingZeros(), E); 7741 } 7742 7743 case Builtin::BI__builtin_eh_return_data_regno: { 7744 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 7745 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 7746 return Success(Operand, E); 7747 } 7748 7749 case Builtin::BI__builtin_expect: 7750 return Visit(E->getArg(0)); 7751 7752 case Builtin::BI__builtin_ffs: 7753 case Builtin::BI__builtin_ffsl: 7754 case Builtin::BI__builtin_ffsll: { 7755 APSInt Val; 7756 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7757 return false; 7758 7759 unsigned N = Val.countTrailingZeros(); 7760 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 7761 } 7762 7763 case Builtin::BI__builtin_fpclassify: { 7764 APFloat Val(0.0); 7765 if (!EvaluateFloat(E->getArg(5), Val, Info)) 7766 return false; 7767 unsigned Arg; 7768 switch (Val.getCategory()) { 7769 case APFloat::fcNaN: Arg = 0; break; 7770 case APFloat::fcInfinity: Arg = 1; break; 7771 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 7772 case APFloat::fcZero: Arg = 4; break; 7773 } 7774 return Visit(E->getArg(Arg)); 7775 } 7776 7777 case Builtin::BI__builtin_isinf_sign: { 7778 APFloat Val(0.0); 7779 return EvaluateFloat(E->getArg(0), Val, Info) && 7780 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 7781 } 7782 7783 case Builtin::BI__builtin_isinf: { 7784 APFloat Val(0.0); 7785 return EvaluateFloat(E->getArg(0), Val, Info) && 7786 Success(Val.isInfinity() ? 1 : 0, E); 7787 } 7788 7789 case Builtin::BI__builtin_isfinite: { 7790 APFloat Val(0.0); 7791 return EvaluateFloat(E->getArg(0), Val, Info) && 7792 Success(Val.isFinite() ? 1 : 0, E); 7793 } 7794 7795 case Builtin::BI__builtin_isnan: { 7796 APFloat Val(0.0); 7797 return EvaluateFloat(E->getArg(0), Val, Info) && 7798 Success(Val.isNaN() ? 1 : 0, E); 7799 } 7800 7801 case Builtin::BI__builtin_isnormal: { 7802 APFloat Val(0.0); 7803 return EvaluateFloat(E->getArg(0), Val, Info) && 7804 Success(Val.isNormal() ? 1 : 0, E); 7805 } 7806 7807 case Builtin::BI__builtin_parity: 7808 case Builtin::BI__builtin_parityl: 7809 case Builtin::BI__builtin_parityll: { 7810 APSInt Val; 7811 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7812 return false; 7813 7814 return Success(Val.countPopulation() % 2, E); 7815 } 7816 7817 case Builtin::BI__builtin_popcount: 7818 case Builtin::BI__builtin_popcountl: 7819 case Builtin::BI__builtin_popcountll: { 7820 APSInt Val; 7821 if (!EvaluateInteger(E->getArg(0), Val, Info)) 7822 return false; 7823 7824 return Success(Val.countPopulation(), E); 7825 } 7826 7827 case Builtin::BIstrlen: 7828 case Builtin::BIwcslen: 7829 // A call to strlen is not a constant expression. 7830 if (Info.getLangOpts().CPlusPlus11) 7831 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7832 << /*isConstexpr*/0 << /*isConstructor*/0 7833 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7834 else 7835 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7836 LLVM_FALLTHROUGH; 7837 case Builtin::BI__builtin_strlen: 7838 case Builtin::BI__builtin_wcslen: { 7839 // As an extension, we support __builtin_strlen() as a constant expression, 7840 // and support folding strlen() to a constant. 7841 LValue String; 7842 if (!EvaluatePointer(E->getArg(0), String, Info)) 7843 return false; 7844 7845 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 7846 7847 // Fast path: if it's a string literal, search the string value. 7848 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 7849 String.getLValueBase().dyn_cast<const Expr *>())) { 7850 // The string literal may have embedded null characters. Find the first 7851 // one and truncate there. 7852 StringRef Str = S->getBytes(); 7853 int64_t Off = String.Offset.getQuantity(); 7854 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 7855 S->getCharByteWidth() == 1 && 7856 // FIXME: Add fast-path for wchar_t too. 7857 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 7858 Str = Str.substr(Off); 7859 7860 StringRef::size_type Pos = Str.find(0); 7861 if (Pos != StringRef::npos) 7862 Str = Str.substr(0, Pos); 7863 7864 return Success(Str.size(), E); 7865 } 7866 7867 // Fall through to slow path to issue appropriate diagnostic. 7868 } 7869 7870 // Slow path: scan the bytes of the string looking for the terminating 0. 7871 for (uint64_t Strlen = 0; /**/; ++Strlen) { 7872 APValue Char; 7873 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 7874 !Char.isInt()) 7875 return false; 7876 if (!Char.getInt()) 7877 return Success(Strlen, E); 7878 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 7879 return false; 7880 } 7881 } 7882 7883 case Builtin::BIstrcmp: 7884 case Builtin::BIwcscmp: 7885 case Builtin::BIstrncmp: 7886 case Builtin::BIwcsncmp: 7887 case Builtin::BImemcmp: 7888 case Builtin::BIwmemcmp: 7889 // A call to strlen is not a constant expression. 7890 if (Info.getLangOpts().CPlusPlus11) 7891 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7892 << /*isConstexpr*/0 << /*isConstructor*/0 7893 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7894 else 7895 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7896 LLVM_FALLTHROUGH; 7897 case Builtin::BI__builtin_strcmp: 7898 case Builtin::BI__builtin_wcscmp: 7899 case Builtin::BI__builtin_strncmp: 7900 case Builtin::BI__builtin_wcsncmp: 7901 case Builtin::BI__builtin_memcmp: 7902 case Builtin::BI__builtin_wmemcmp: { 7903 LValue String1, String2; 7904 if (!EvaluatePointer(E->getArg(0), String1, Info) || 7905 !EvaluatePointer(E->getArg(1), String2, Info)) 7906 return false; 7907 7908 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 7909 7910 uint64_t MaxLength = uint64_t(-1); 7911 if (BuiltinOp != Builtin::BIstrcmp && 7912 BuiltinOp != Builtin::BIwcscmp && 7913 BuiltinOp != Builtin::BI__builtin_strcmp && 7914 BuiltinOp != Builtin::BI__builtin_wcscmp) { 7915 APSInt N; 7916 if (!EvaluateInteger(E->getArg(2), N, Info)) 7917 return false; 7918 MaxLength = N.getExtValue(); 7919 } 7920 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp && 7921 BuiltinOp != Builtin::BIwmemcmp && 7922 BuiltinOp != Builtin::BI__builtin_memcmp && 7923 BuiltinOp != Builtin::BI__builtin_wmemcmp); 7924 for (; MaxLength; --MaxLength) { 7925 APValue Char1, Char2; 7926 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) || 7927 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) || 7928 !Char1.isInt() || !Char2.isInt()) 7929 return false; 7930 if (Char1.getInt() != Char2.getInt()) 7931 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 7932 if (StopAtNull && !Char1.getInt()) 7933 return Success(0, E); 7934 assert(!(StopAtNull && !Char2.getInt())); 7935 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) || 7936 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1)) 7937 return false; 7938 } 7939 // We hit the strncmp / memcmp limit. 7940 return Success(0, E); 7941 } 7942 7943 case Builtin::BI__atomic_always_lock_free: 7944 case Builtin::BI__atomic_is_lock_free: 7945 case Builtin::BI__c11_atomic_is_lock_free: { 7946 APSInt SizeVal; 7947 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 7948 return false; 7949 7950 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 7951 // of two less than the maximum inline atomic width, we know it is 7952 // lock-free. If the size isn't a power of two, or greater than the 7953 // maximum alignment where we promote atomics, we know it is not lock-free 7954 // (at least not in the sense of atomic_is_lock_free). Otherwise, 7955 // the answer can only be determined at runtime; for example, 16-byte 7956 // atomics have lock-free implementations on some, but not all, 7957 // x86-64 processors. 7958 7959 // Check power-of-two. 7960 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 7961 if (Size.isPowerOfTwo()) { 7962 // Check against inlining width. 7963 unsigned InlineWidthBits = 7964 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 7965 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 7966 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 7967 Size == CharUnits::One() || 7968 E->getArg(1)->isNullPointerConstant(Info.Ctx, 7969 Expr::NPC_NeverValueDependent)) 7970 // OK, we will inline appropriately-aligned operations of this size, 7971 // and _Atomic(T) is appropriately-aligned. 7972 return Success(1, E); 7973 7974 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 7975 castAs<PointerType>()->getPointeeType(); 7976 if (!PointeeType->isIncompleteType() && 7977 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 7978 // OK, we will inline operations on this object. 7979 return Success(1, E); 7980 } 7981 } 7982 } 7983 7984 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 7985 Success(0, E) : Error(E); 7986 } 7987 case Builtin::BIomp_is_initial_device: 7988 // We can decide statically which value the runtime would return if called. 7989 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 7990 } 7991 } 7992 7993 static bool HasSameBase(const LValue &A, const LValue &B) { 7994 if (!A.getLValueBase()) 7995 return !B.getLValueBase(); 7996 if (!B.getLValueBase()) 7997 return false; 7998 7999 if (A.getLValueBase().getOpaqueValue() != 8000 B.getLValueBase().getOpaqueValue()) { 8001 const Decl *ADecl = GetLValueBaseDecl(A); 8002 if (!ADecl) 8003 return false; 8004 const Decl *BDecl = GetLValueBaseDecl(B); 8005 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 8006 return false; 8007 } 8008 8009 return IsGlobalLValue(A.getLValueBase()) || 8010 A.getLValueCallIndex() == B.getLValueCallIndex(); 8011 } 8012 8013 /// \brief Determine whether this is a pointer past the end of the complete 8014 /// object referred to by the lvalue. 8015 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 8016 const LValue &LV) { 8017 // A null pointer can be viewed as being "past the end" but we don't 8018 // choose to look at it that way here. 8019 if (!LV.getLValueBase()) 8020 return false; 8021 8022 // If the designator is valid and refers to a subobject, we're not pointing 8023 // past the end. 8024 if (!LV.getLValueDesignator().Invalid && 8025 !LV.getLValueDesignator().isOnePastTheEnd()) 8026 return false; 8027 8028 // A pointer to an incomplete type might be past-the-end if the type's size is 8029 // zero. We cannot tell because the type is incomplete. 8030 QualType Ty = getType(LV.getLValueBase()); 8031 if (Ty->isIncompleteType()) 8032 return true; 8033 8034 // We're a past-the-end pointer if we point to the byte after the object, 8035 // no matter what our type or path is. 8036 auto Size = Ctx.getTypeSizeInChars(Ty); 8037 return LV.getLValueOffset() == Size; 8038 } 8039 8040 namespace { 8041 8042 /// \brief Data recursive integer evaluator of certain binary operators. 8043 /// 8044 /// We use a data recursive algorithm for binary operators so that we are able 8045 /// to handle extreme cases of chained binary operators without causing stack 8046 /// overflow. 8047 class DataRecursiveIntBinOpEvaluator { 8048 struct EvalResult { 8049 APValue Val; 8050 bool Failed; 8051 8052 EvalResult() : Failed(false) { } 8053 8054 void swap(EvalResult &RHS) { 8055 Val.swap(RHS.Val); 8056 Failed = RHS.Failed; 8057 RHS.Failed = false; 8058 } 8059 }; 8060 8061 struct Job { 8062 const Expr *E; 8063 EvalResult LHSResult; // meaningful only for binary operator expression. 8064 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 8065 8066 Job() = default; 8067 Job(Job &&) = default; 8068 8069 void startSpeculativeEval(EvalInfo &Info) { 8070 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 8071 } 8072 8073 private: 8074 SpeculativeEvaluationRAII SpecEvalRAII; 8075 }; 8076 8077 SmallVector<Job, 16> Queue; 8078 8079 IntExprEvaluator &IntEval; 8080 EvalInfo &Info; 8081 APValue &FinalResult; 8082 8083 public: 8084 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 8085 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 8086 8087 /// \brief True if \param E is a binary operator that we are going to handle 8088 /// data recursively. 8089 /// We handle binary operators that are comma, logical, or that have operands 8090 /// with integral or enumeration type. 8091 static bool shouldEnqueue(const BinaryOperator *E) { 8092 return E->getOpcode() == BO_Comma || 8093 E->isLogicalOp() || 8094 (E->isRValue() && 8095 E->getType()->isIntegralOrEnumerationType() && 8096 E->getLHS()->getType()->isIntegralOrEnumerationType() && 8097 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8098 } 8099 8100 bool Traverse(const BinaryOperator *E) { 8101 enqueue(E); 8102 EvalResult PrevResult; 8103 while (!Queue.empty()) 8104 process(PrevResult); 8105 8106 if (PrevResult.Failed) return false; 8107 8108 FinalResult.swap(PrevResult.Val); 8109 return true; 8110 } 8111 8112 private: 8113 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 8114 return IntEval.Success(Value, E, Result); 8115 } 8116 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 8117 return IntEval.Success(Value, E, Result); 8118 } 8119 bool Error(const Expr *E) { 8120 return IntEval.Error(E); 8121 } 8122 bool Error(const Expr *E, diag::kind D) { 8123 return IntEval.Error(E, D); 8124 } 8125 8126 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 8127 return Info.CCEDiag(E, D); 8128 } 8129 8130 // \brief Returns true if visiting the RHS is necessary, false otherwise. 8131 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8132 bool &SuppressRHSDiags); 8133 8134 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8135 const BinaryOperator *E, APValue &Result); 8136 8137 void EvaluateExpr(const Expr *E, EvalResult &Result) { 8138 Result.Failed = !Evaluate(Result.Val, Info, E); 8139 if (Result.Failed) 8140 Result.Val = APValue(); 8141 } 8142 8143 void process(EvalResult &Result); 8144 8145 void enqueue(const Expr *E) { 8146 E = E->IgnoreParens(); 8147 Queue.resize(Queue.size()+1); 8148 Queue.back().E = E; 8149 Queue.back().Kind = Job::AnyExprKind; 8150 } 8151 }; 8152 8153 } 8154 8155 bool DataRecursiveIntBinOpEvaluator:: 8156 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8157 bool &SuppressRHSDiags) { 8158 if (E->getOpcode() == BO_Comma) { 8159 // Ignore LHS but note if we could not evaluate it. 8160 if (LHSResult.Failed) 8161 return Info.noteSideEffect(); 8162 return true; 8163 } 8164 8165 if (E->isLogicalOp()) { 8166 bool LHSAsBool; 8167 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 8168 // We were able to evaluate the LHS, see if we can get away with not 8169 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 8170 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 8171 Success(LHSAsBool, E, LHSResult.Val); 8172 return false; // Ignore RHS 8173 } 8174 } else { 8175 LHSResult.Failed = true; 8176 8177 // Since we weren't able to evaluate the left hand side, it 8178 // might have had side effects. 8179 if (!Info.noteSideEffect()) 8180 return false; 8181 8182 // We can't evaluate the LHS; however, sometimes the result 8183 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8184 // Don't ignore RHS and suppress diagnostics from this arm. 8185 SuppressRHSDiags = true; 8186 } 8187 8188 return true; 8189 } 8190 8191 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8192 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8193 8194 if (LHSResult.Failed && !Info.noteFailure()) 8195 return false; // Ignore RHS; 8196 8197 return true; 8198 } 8199 8200 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 8201 bool IsSub) { 8202 // Compute the new offset in the appropriate width, wrapping at 64 bits. 8203 // FIXME: When compiling for a 32-bit target, we should use 32-bit 8204 // offsets. 8205 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 8206 CharUnits &Offset = LVal.getLValueOffset(); 8207 uint64_t Offset64 = Offset.getQuantity(); 8208 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 8209 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 8210 : Offset64 + Index64); 8211 } 8212 8213 bool DataRecursiveIntBinOpEvaluator:: 8214 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8215 const BinaryOperator *E, APValue &Result) { 8216 if (E->getOpcode() == BO_Comma) { 8217 if (RHSResult.Failed) 8218 return false; 8219 Result = RHSResult.Val; 8220 return true; 8221 } 8222 8223 if (E->isLogicalOp()) { 8224 bool lhsResult, rhsResult; 8225 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 8226 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 8227 8228 if (LHSIsOK) { 8229 if (RHSIsOK) { 8230 if (E->getOpcode() == BO_LOr) 8231 return Success(lhsResult || rhsResult, E, Result); 8232 else 8233 return Success(lhsResult && rhsResult, E, Result); 8234 } 8235 } else { 8236 if (RHSIsOK) { 8237 // We can't evaluate the LHS; however, sometimes the result 8238 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8239 if (rhsResult == (E->getOpcode() == BO_LOr)) 8240 return Success(rhsResult, E, Result); 8241 } 8242 } 8243 8244 return false; 8245 } 8246 8247 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8248 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8249 8250 if (LHSResult.Failed || RHSResult.Failed) 8251 return false; 8252 8253 const APValue &LHSVal = LHSResult.Val; 8254 const APValue &RHSVal = RHSResult.Val; 8255 8256 // Handle cases like (unsigned long)&a + 4. 8257 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 8258 Result = LHSVal; 8259 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 8260 return true; 8261 } 8262 8263 // Handle cases like 4 + (unsigned long)&a 8264 if (E->getOpcode() == BO_Add && 8265 RHSVal.isLValue() && LHSVal.isInt()) { 8266 Result = RHSVal; 8267 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 8268 return true; 8269 } 8270 8271 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 8272 // Handle (intptr_t)&&A - (intptr_t)&&B. 8273 if (!LHSVal.getLValueOffset().isZero() || 8274 !RHSVal.getLValueOffset().isZero()) 8275 return false; 8276 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 8277 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 8278 if (!LHSExpr || !RHSExpr) 8279 return false; 8280 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 8281 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 8282 if (!LHSAddrExpr || !RHSAddrExpr) 8283 return false; 8284 // Make sure both labels come from the same function. 8285 if (LHSAddrExpr->getLabel()->getDeclContext() != 8286 RHSAddrExpr->getLabel()->getDeclContext()) 8287 return false; 8288 Result = APValue(LHSAddrExpr, RHSAddrExpr); 8289 return true; 8290 } 8291 8292 // All the remaining cases expect both operands to be an integer 8293 if (!LHSVal.isInt() || !RHSVal.isInt()) 8294 return Error(E); 8295 8296 // Set up the width and signedness manually, in case it can't be deduced 8297 // from the operation we're performing. 8298 // FIXME: Don't do this in the cases where we can deduce it. 8299 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 8300 E->getType()->isUnsignedIntegerOrEnumerationType()); 8301 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 8302 RHSVal.getInt(), Value)) 8303 return false; 8304 return Success(Value, E, Result); 8305 } 8306 8307 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 8308 Job &job = Queue.back(); 8309 8310 switch (job.Kind) { 8311 case Job::AnyExprKind: { 8312 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 8313 if (shouldEnqueue(Bop)) { 8314 job.Kind = Job::BinOpKind; 8315 enqueue(Bop->getLHS()); 8316 return; 8317 } 8318 } 8319 8320 EvaluateExpr(job.E, Result); 8321 Queue.pop_back(); 8322 return; 8323 } 8324 8325 case Job::BinOpKind: { 8326 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8327 bool SuppressRHSDiags = false; 8328 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 8329 Queue.pop_back(); 8330 return; 8331 } 8332 if (SuppressRHSDiags) 8333 job.startSpeculativeEval(Info); 8334 job.LHSResult.swap(Result); 8335 job.Kind = Job::BinOpVisitedLHSKind; 8336 enqueue(Bop->getRHS()); 8337 return; 8338 } 8339 8340 case Job::BinOpVisitedLHSKind: { 8341 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8342 EvalResult RHS; 8343 RHS.swap(Result); 8344 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 8345 Queue.pop_back(); 8346 return; 8347 } 8348 } 8349 8350 llvm_unreachable("Invalid Job::Kind!"); 8351 } 8352 8353 namespace { 8354 /// Used when we determine that we should fail, but can keep evaluating prior to 8355 /// noting that we had a failure. 8356 class DelayedNoteFailureRAII { 8357 EvalInfo &Info; 8358 bool NoteFailure; 8359 8360 public: 8361 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 8362 : Info(Info), NoteFailure(NoteFailure) {} 8363 ~DelayedNoteFailureRAII() { 8364 if (NoteFailure) { 8365 bool ContinueAfterFailure = Info.noteFailure(); 8366 (void)ContinueAfterFailure; 8367 assert(ContinueAfterFailure && 8368 "Shouldn't have kept evaluating on failure."); 8369 } 8370 } 8371 }; 8372 } 8373 8374 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 8375 // We don't call noteFailure immediately because the assignment happens after 8376 // we evaluate LHS and RHS. 8377 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 8378 return Error(E); 8379 8380 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 8381 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 8382 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 8383 8384 QualType LHSTy = E->getLHS()->getType(); 8385 QualType RHSTy = E->getRHS()->getType(); 8386 8387 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 8388 ComplexValue LHS, RHS; 8389 bool LHSOK; 8390 if (E->isAssignmentOp()) { 8391 LValue LV; 8392 EvaluateLValue(E->getLHS(), LV, Info); 8393 LHSOK = false; 8394 } else if (LHSTy->isRealFloatingType()) { 8395 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 8396 if (LHSOK) { 8397 LHS.makeComplexFloat(); 8398 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 8399 } 8400 } else { 8401 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 8402 } 8403 if (!LHSOK && !Info.noteFailure()) 8404 return false; 8405 8406 if (E->getRHS()->getType()->isRealFloatingType()) { 8407 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 8408 return false; 8409 RHS.makeComplexFloat(); 8410 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 8411 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 8412 return false; 8413 8414 if (LHS.isComplexFloat()) { 8415 APFloat::cmpResult CR_r = 8416 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 8417 APFloat::cmpResult CR_i = 8418 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 8419 8420 if (E->getOpcode() == BO_EQ) 8421 return Success((CR_r == APFloat::cmpEqual && 8422 CR_i == APFloat::cmpEqual), E); 8423 else { 8424 assert(E->getOpcode() == BO_NE && 8425 "Invalid complex comparison."); 8426 return Success(((CR_r == APFloat::cmpGreaterThan || 8427 CR_r == APFloat::cmpLessThan || 8428 CR_r == APFloat::cmpUnordered) || 8429 (CR_i == APFloat::cmpGreaterThan || 8430 CR_i == APFloat::cmpLessThan || 8431 CR_i == APFloat::cmpUnordered)), E); 8432 } 8433 } else { 8434 if (E->getOpcode() == BO_EQ) 8435 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() && 8436 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E); 8437 else { 8438 assert(E->getOpcode() == BO_NE && 8439 "Invalid compex comparison."); 8440 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() || 8441 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E); 8442 } 8443 } 8444 } 8445 8446 if (LHSTy->isRealFloatingType() && 8447 RHSTy->isRealFloatingType()) { 8448 APFloat RHS(0.0), LHS(0.0); 8449 8450 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 8451 if (!LHSOK && !Info.noteFailure()) 8452 return false; 8453 8454 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 8455 return false; 8456 8457 APFloat::cmpResult CR = LHS.compare(RHS); 8458 8459 switch (E->getOpcode()) { 8460 default: 8461 llvm_unreachable("Invalid binary operator!"); 8462 case BO_LT: 8463 return Success(CR == APFloat::cmpLessThan, E); 8464 case BO_GT: 8465 return Success(CR == APFloat::cmpGreaterThan, E); 8466 case BO_LE: 8467 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E); 8468 case BO_GE: 8469 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual, 8470 E); 8471 case BO_EQ: 8472 return Success(CR == APFloat::cmpEqual, E); 8473 case BO_NE: 8474 return Success(CR == APFloat::cmpGreaterThan 8475 || CR == APFloat::cmpLessThan 8476 || CR == APFloat::cmpUnordered, E); 8477 } 8478 } 8479 8480 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 8481 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) { 8482 LValue LHSValue, RHSValue; 8483 8484 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 8485 if (!LHSOK && !Info.noteFailure()) 8486 return false; 8487 8488 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 8489 return false; 8490 8491 // Reject differing bases from the normal codepath; we special-case 8492 // comparisons to null. 8493 if (!HasSameBase(LHSValue, RHSValue)) { 8494 if (E->getOpcode() == BO_Sub) { 8495 // Handle &&A - &&B. 8496 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 8497 return Error(E); 8498 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>(); 8499 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>(); 8500 if (!LHSExpr || !RHSExpr) 8501 return Error(E); 8502 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 8503 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 8504 if (!LHSAddrExpr || !RHSAddrExpr) 8505 return Error(E); 8506 // Make sure both labels come from the same function. 8507 if (LHSAddrExpr->getLabel()->getDeclContext() != 8508 RHSAddrExpr->getLabel()->getDeclContext()) 8509 return Error(E); 8510 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 8511 } 8512 // Inequalities and subtractions between unrelated pointers have 8513 // unspecified or undefined behavior. 8514 if (!E->isEqualityOp()) 8515 return Error(E); 8516 // A constant address may compare equal to the address of a symbol. 8517 // The one exception is that address of an object cannot compare equal 8518 // to a null pointer constant. 8519 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 8520 (!RHSValue.Base && !RHSValue.Offset.isZero())) 8521 return Error(E); 8522 // It's implementation-defined whether distinct literals will have 8523 // distinct addresses. In clang, the result of such a comparison is 8524 // unspecified, so it is not a constant expression. However, we do know 8525 // that the address of a literal will be non-null. 8526 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 8527 LHSValue.Base && RHSValue.Base) 8528 return Error(E); 8529 // We can't tell whether weak symbols will end up pointing to the same 8530 // object. 8531 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 8532 return Error(E); 8533 // We can't compare the address of the start of one object with the 8534 // past-the-end address of another object, per C++ DR1652. 8535 if ((LHSValue.Base && LHSValue.Offset.isZero() && 8536 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 8537 (RHSValue.Base && RHSValue.Offset.isZero() && 8538 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 8539 return Error(E); 8540 // We can't tell whether an object is at the same address as another 8541 // zero sized object. 8542 if ((RHSValue.Base && isZeroSized(LHSValue)) || 8543 (LHSValue.Base && isZeroSized(RHSValue))) 8544 return Error(E); 8545 // Pointers with different bases cannot represent the same object. 8546 return Success(E->getOpcode() == BO_NE, E); 8547 } 8548 8549 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 8550 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 8551 8552 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 8553 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 8554 8555 if (E->getOpcode() == BO_Sub) { 8556 // C++11 [expr.add]p6: 8557 // Unless both pointers point to elements of the same array object, or 8558 // one past the last element of the array object, the behavior is 8559 // undefined. 8560 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 8561 !AreElementsOfSameArray(getType(LHSValue.Base), 8562 LHSDesignator, RHSDesignator)) 8563 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 8564 8565 QualType Type = E->getLHS()->getType(); 8566 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 8567 8568 CharUnits ElementSize; 8569 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 8570 return false; 8571 8572 // As an extension, a type may have zero size (empty struct or union in 8573 // C, array of zero length). Pointer subtraction in such cases has 8574 // undefined behavior, so is not constant. 8575 if (ElementSize.isZero()) { 8576 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 8577 << ElementType; 8578 return false; 8579 } 8580 8581 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 8582 // and produce incorrect results when it overflows. Such behavior 8583 // appears to be non-conforming, but is common, so perhaps we should 8584 // assume the standard intended for such cases to be undefined behavior 8585 // and check for them. 8586 8587 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 8588 // overflow in the final conversion to ptrdiff_t. 8589 APSInt LHS( 8590 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 8591 APSInt RHS( 8592 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 8593 APSInt ElemSize( 8594 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false); 8595 APSInt TrueResult = (LHS - RHS) / ElemSize; 8596 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 8597 8598 if (Result.extend(65) != TrueResult && 8599 !HandleOverflow(Info, E, TrueResult, E->getType())) 8600 return false; 8601 return Success(Result, E); 8602 } 8603 8604 // C++11 [expr.rel]p3: 8605 // Pointers to void (after pointer conversions) can be compared, with a 8606 // result defined as follows: If both pointers represent the same 8607 // address or are both the null pointer value, the result is true if the 8608 // operator is <= or >= and false otherwise; otherwise the result is 8609 // unspecified. 8610 // We interpret this as applying to pointers to *cv* void. 8611 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && 8612 E->isRelationalOp()) 8613 CCEDiag(E, diag::note_constexpr_void_comparison); 8614 8615 // C++11 [expr.rel]p2: 8616 // - If two pointers point to non-static data members of the same object, 8617 // or to subobjects or array elements fo such members, recursively, the 8618 // pointer to the later declared member compares greater provided the 8619 // two members have the same access control and provided their class is 8620 // not a union. 8621 // [...] 8622 // - Otherwise pointer comparisons are unspecified. 8623 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 8624 E->isRelationalOp()) { 8625 bool WasArrayIndex; 8626 unsigned Mismatch = 8627 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator, 8628 RHSDesignator, WasArrayIndex); 8629 // At the point where the designators diverge, the comparison has a 8630 // specified value if: 8631 // - we are comparing array indices 8632 // - we are comparing fields of a union, or fields with the same access 8633 // Otherwise, the result is unspecified and thus the comparison is not a 8634 // constant expression. 8635 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 8636 Mismatch < RHSDesignator.Entries.size()) { 8637 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 8638 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 8639 if (!LF && !RF) 8640 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 8641 else if (!LF) 8642 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 8643 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 8644 << RF->getParent() << RF; 8645 else if (!RF) 8646 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 8647 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 8648 << LF->getParent() << LF; 8649 else if (!LF->getParent()->isUnion() && 8650 LF->getAccess() != RF->getAccess()) 8651 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access) 8652 << LF << LF->getAccess() << RF << RF->getAccess() 8653 << LF->getParent(); 8654 } 8655 } 8656 8657 // The comparison here must be unsigned, and performed with the same 8658 // width as the pointer. 8659 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 8660 uint64_t CompareLHS = LHSOffset.getQuantity(); 8661 uint64_t CompareRHS = RHSOffset.getQuantity(); 8662 assert(PtrSize <= 64 && "Unexpected pointer width"); 8663 uint64_t Mask = ~0ULL >> (64 - PtrSize); 8664 CompareLHS &= Mask; 8665 CompareRHS &= Mask; 8666 8667 // If there is a base and this is a relational operator, we can only 8668 // compare pointers within the object in question; otherwise, the result 8669 // depends on where the object is located in memory. 8670 if (!LHSValue.Base.isNull() && E->isRelationalOp()) { 8671 QualType BaseTy = getType(LHSValue.Base); 8672 if (BaseTy->isIncompleteType()) 8673 return Error(E); 8674 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 8675 uint64_t OffsetLimit = Size.getQuantity(); 8676 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 8677 return Error(E); 8678 } 8679 8680 switch (E->getOpcode()) { 8681 default: llvm_unreachable("missing comparison operator"); 8682 case BO_LT: return Success(CompareLHS < CompareRHS, E); 8683 case BO_GT: return Success(CompareLHS > CompareRHS, E); 8684 case BO_LE: return Success(CompareLHS <= CompareRHS, E); 8685 case BO_GE: return Success(CompareLHS >= CompareRHS, E); 8686 case BO_EQ: return Success(CompareLHS == CompareRHS, E); 8687 case BO_NE: return Success(CompareLHS != CompareRHS, E); 8688 } 8689 } 8690 } 8691 8692 if (LHSTy->isMemberPointerType()) { 8693 assert(E->isEqualityOp() && "unexpected member pointer operation"); 8694 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 8695 8696 MemberPtr LHSValue, RHSValue; 8697 8698 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 8699 if (!LHSOK && !Info.noteFailure()) 8700 return false; 8701 8702 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 8703 return false; 8704 8705 // C++11 [expr.eq]p2: 8706 // If both operands are null, they compare equal. Otherwise if only one is 8707 // null, they compare unequal. 8708 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 8709 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 8710 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E); 8711 } 8712 8713 // Otherwise if either is a pointer to a virtual member function, the 8714 // result is unspecified. 8715 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 8716 if (MD->isVirtual()) 8717 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 8718 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 8719 if (MD->isVirtual()) 8720 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 8721 8722 // Otherwise they compare equal if and only if they would refer to the 8723 // same member of the same most derived object or the same subobject if 8724 // they were dereferenced with a hypothetical object of the associated 8725 // class type. 8726 bool Equal = LHSValue == RHSValue; 8727 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E); 8728 } 8729 8730 if (LHSTy->isNullPtrType()) { 8731 assert(E->isComparisonOp() && "unexpected nullptr operation"); 8732 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 8733 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 8734 // are compared, the result is true of the operator is <=, >= or ==, and 8735 // false otherwise. 8736 BinaryOperator::Opcode Opcode = E->getOpcode(); 8737 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E); 8738 } 8739 8740 assert((!LHSTy->isIntegralOrEnumerationType() || 8741 !RHSTy->isIntegralOrEnumerationType()) && 8742 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 8743 // We can't continue from here for non-integral types. 8744 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 8745 } 8746 8747 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 8748 /// a result as the expression's type. 8749 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 8750 const UnaryExprOrTypeTraitExpr *E) { 8751 switch(E->getKind()) { 8752 case UETT_AlignOf: { 8753 if (E->isArgumentType()) 8754 return Success(GetAlignOfType(Info, E->getArgumentType()), E); 8755 else 8756 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E); 8757 } 8758 8759 case UETT_VecStep: { 8760 QualType Ty = E->getTypeOfArgument(); 8761 8762 if (Ty->isVectorType()) { 8763 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 8764 8765 // The vec_step built-in functions that take a 3-component 8766 // vector return 4. (OpenCL 1.1 spec 6.11.12) 8767 if (n == 3) 8768 n = 4; 8769 8770 return Success(n, E); 8771 } else 8772 return Success(1, E); 8773 } 8774 8775 case UETT_SizeOf: { 8776 QualType SrcTy = E->getTypeOfArgument(); 8777 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 8778 // the result is the size of the referenced type." 8779 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 8780 SrcTy = Ref->getPointeeType(); 8781 8782 CharUnits Sizeof; 8783 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 8784 return false; 8785 return Success(Sizeof, E); 8786 } 8787 case UETT_OpenMPRequiredSimdAlign: 8788 assert(E->isArgumentType()); 8789 return Success( 8790 Info.Ctx.toCharUnitsFromBits( 8791 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 8792 .getQuantity(), 8793 E); 8794 } 8795 8796 llvm_unreachable("unknown expr/type trait"); 8797 } 8798 8799 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 8800 CharUnits Result; 8801 unsigned n = OOE->getNumComponents(); 8802 if (n == 0) 8803 return Error(OOE); 8804 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 8805 for (unsigned i = 0; i != n; ++i) { 8806 OffsetOfNode ON = OOE->getComponent(i); 8807 switch (ON.getKind()) { 8808 case OffsetOfNode::Array: { 8809 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 8810 APSInt IdxResult; 8811 if (!EvaluateInteger(Idx, IdxResult, Info)) 8812 return false; 8813 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 8814 if (!AT) 8815 return Error(OOE); 8816 CurrentType = AT->getElementType(); 8817 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 8818 Result += IdxResult.getSExtValue() * ElementSize; 8819 break; 8820 } 8821 8822 case OffsetOfNode::Field: { 8823 FieldDecl *MemberDecl = ON.getField(); 8824 const RecordType *RT = CurrentType->getAs<RecordType>(); 8825 if (!RT) 8826 return Error(OOE); 8827 RecordDecl *RD = RT->getDecl(); 8828 if (RD->isInvalidDecl()) return false; 8829 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 8830 unsigned i = MemberDecl->getFieldIndex(); 8831 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 8832 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 8833 CurrentType = MemberDecl->getType().getNonReferenceType(); 8834 break; 8835 } 8836 8837 case OffsetOfNode::Identifier: 8838 llvm_unreachable("dependent __builtin_offsetof"); 8839 8840 case OffsetOfNode::Base: { 8841 CXXBaseSpecifier *BaseSpec = ON.getBase(); 8842 if (BaseSpec->isVirtual()) 8843 return Error(OOE); 8844 8845 // Find the layout of the class whose base we are looking into. 8846 const RecordType *RT = CurrentType->getAs<RecordType>(); 8847 if (!RT) 8848 return Error(OOE); 8849 RecordDecl *RD = RT->getDecl(); 8850 if (RD->isInvalidDecl()) return false; 8851 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 8852 8853 // Find the base class itself. 8854 CurrentType = BaseSpec->getType(); 8855 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 8856 if (!BaseRT) 8857 return Error(OOE); 8858 8859 // Add the offset to the base. 8860 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 8861 break; 8862 } 8863 } 8864 } 8865 return Success(Result, OOE); 8866 } 8867 8868 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 8869 switch (E->getOpcode()) { 8870 default: 8871 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 8872 // See C99 6.6p3. 8873 return Error(E); 8874 case UO_Extension: 8875 // FIXME: Should extension allow i-c-e extension expressions in its scope? 8876 // If so, we could clear the diagnostic ID. 8877 return Visit(E->getSubExpr()); 8878 case UO_Plus: 8879 // The result is just the value. 8880 return Visit(E->getSubExpr()); 8881 case UO_Minus: { 8882 if (!Visit(E->getSubExpr())) 8883 return false; 8884 if (!Result.isInt()) return Error(E); 8885 const APSInt &Value = Result.getInt(); 8886 if (Value.isSigned() && Value.isMinSignedValue() && 8887 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 8888 E->getType())) 8889 return false; 8890 return Success(-Value, E); 8891 } 8892 case UO_Not: { 8893 if (!Visit(E->getSubExpr())) 8894 return false; 8895 if (!Result.isInt()) return Error(E); 8896 return Success(~Result.getInt(), E); 8897 } 8898 case UO_LNot: { 8899 bool bres; 8900 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 8901 return false; 8902 return Success(!bres, E); 8903 } 8904 } 8905 } 8906 8907 /// HandleCast - This is used to evaluate implicit or explicit casts where the 8908 /// result type is integer. 8909 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 8910 const Expr *SubExpr = E->getSubExpr(); 8911 QualType DestType = E->getType(); 8912 QualType SrcType = SubExpr->getType(); 8913 8914 switch (E->getCastKind()) { 8915 case CK_BaseToDerived: 8916 case CK_DerivedToBase: 8917 case CK_UncheckedDerivedToBase: 8918 case CK_Dynamic: 8919 case CK_ToUnion: 8920 case CK_ArrayToPointerDecay: 8921 case CK_FunctionToPointerDecay: 8922 case CK_NullToPointer: 8923 case CK_NullToMemberPointer: 8924 case CK_BaseToDerivedMemberPointer: 8925 case CK_DerivedToBaseMemberPointer: 8926 case CK_ReinterpretMemberPointer: 8927 case CK_ConstructorConversion: 8928 case CK_IntegralToPointer: 8929 case CK_ToVoid: 8930 case CK_VectorSplat: 8931 case CK_IntegralToFloating: 8932 case CK_FloatingCast: 8933 case CK_CPointerToObjCPointerCast: 8934 case CK_BlockPointerToObjCPointerCast: 8935 case CK_AnyPointerToBlockPointerCast: 8936 case CK_ObjCObjectLValueCast: 8937 case CK_FloatingRealToComplex: 8938 case CK_FloatingComplexToReal: 8939 case CK_FloatingComplexCast: 8940 case CK_FloatingComplexToIntegralComplex: 8941 case CK_IntegralRealToComplex: 8942 case CK_IntegralComplexCast: 8943 case CK_IntegralComplexToFloatingComplex: 8944 case CK_BuiltinFnToFnPtr: 8945 case CK_ZeroToOCLEvent: 8946 case CK_ZeroToOCLQueue: 8947 case CK_NonAtomicToAtomic: 8948 case CK_AddressSpaceConversion: 8949 case CK_IntToOCLSampler: 8950 llvm_unreachable("invalid cast kind for integral value"); 8951 8952 case CK_BitCast: 8953 case CK_Dependent: 8954 case CK_LValueBitCast: 8955 case CK_ARCProduceObject: 8956 case CK_ARCConsumeObject: 8957 case CK_ARCReclaimReturnedObject: 8958 case CK_ARCExtendBlockObject: 8959 case CK_CopyAndAutoreleaseBlockObject: 8960 return Error(E); 8961 8962 case CK_UserDefinedConversion: 8963 case CK_LValueToRValue: 8964 case CK_AtomicToNonAtomic: 8965 case CK_NoOp: 8966 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8967 8968 case CK_MemberPointerToBoolean: 8969 case CK_PointerToBoolean: 8970 case CK_IntegralToBoolean: 8971 case CK_FloatingToBoolean: 8972 case CK_BooleanToSignedIntegral: 8973 case CK_FloatingComplexToBoolean: 8974 case CK_IntegralComplexToBoolean: { 8975 bool BoolResult; 8976 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 8977 return false; 8978 uint64_t IntResult = BoolResult; 8979 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 8980 IntResult = (uint64_t)-1; 8981 return Success(IntResult, E); 8982 } 8983 8984 case CK_IntegralCast: { 8985 if (!Visit(SubExpr)) 8986 return false; 8987 8988 if (!Result.isInt()) { 8989 // Allow casts of address-of-label differences if they are no-ops 8990 // or narrowing. (The narrowing case isn't actually guaranteed to 8991 // be constant-evaluatable except in some narrow cases which are hard 8992 // to detect here. We let it through on the assumption the user knows 8993 // what they are doing.) 8994 if (Result.isAddrLabelDiff()) 8995 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 8996 // Only allow casts of lvalues if they are lossless. 8997 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 8998 } 8999 9000 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 9001 Result.getInt()), E); 9002 } 9003 9004 case CK_PointerToIntegral: { 9005 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 9006 9007 LValue LV; 9008 if (!EvaluatePointer(SubExpr, LV, Info)) 9009 return false; 9010 9011 if (LV.getLValueBase()) { 9012 // Only allow based lvalue casts if they are lossless. 9013 // FIXME: Allow a larger integer size than the pointer size, and allow 9014 // narrowing back down to pointer width in subsequent integral casts. 9015 // FIXME: Check integer type's active bits, not its type size. 9016 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 9017 return Error(E); 9018 9019 LV.Designator.setInvalid(); 9020 LV.moveInto(Result); 9021 return true; 9022 } 9023 9024 uint64_t V; 9025 if (LV.isNullPointer()) 9026 V = Info.Ctx.getTargetNullPointerValue(SrcType); 9027 else 9028 V = LV.getLValueOffset().getQuantity(); 9029 9030 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType); 9031 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 9032 } 9033 9034 case CK_IntegralComplexToReal: { 9035 ComplexValue C; 9036 if (!EvaluateComplex(SubExpr, C, Info)) 9037 return false; 9038 return Success(C.getComplexIntReal(), E); 9039 } 9040 9041 case CK_FloatingToIntegral: { 9042 APFloat F(0.0); 9043 if (!EvaluateFloat(SubExpr, F, Info)) 9044 return false; 9045 9046 APSInt Value; 9047 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 9048 return false; 9049 return Success(Value, E); 9050 } 9051 } 9052 9053 llvm_unreachable("unknown cast resulting in integral value"); 9054 } 9055 9056 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9057 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9058 ComplexValue LV; 9059 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9060 return false; 9061 if (!LV.isComplexInt()) 9062 return Error(E); 9063 return Success(LV.getComplexIntReal(), E); 9064 } 9065 9066 return Visit(E->getSubExpr()); 9067 } 9068 9069 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9070 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 9071 ComplexValue LV; 9072 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9073 return false; 9074 if (!LV.isComplexInt()) 9075 return Error(E); 9076 return Success(LV.getComplexIntImag(), E); 9077 } 9078 9079 VisitIgnoredValue(E->getSubExpr()); 9080 return Success(0, E); 9081 } 9082 9083 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 9084 return Success(E->getPackLength(), E); 9085 } 9086 9087 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 9088 return Success(E->getValue(), E); 9089 } 9090 9091 //===----------------------------------------------------------------------===// 9092 // Float Evaluation 9093 //===----------------------------------------------------------------------===// 9094 9095 namespace { 9096 class FloatExprEvaluator 9097 : public ExprEvaluatorBase<FloatExprEvaluator> { 9098 APFloat &Result; 9099 public: 9100 FloatExprEvaluator(EvalInfo &info, APFloat &result) 9101 : ExprEvaluatorBaseTy(info), Result(result) {} 9102 9103 bool Success(const APValue &V, const Expr *e) { 9104 Result = V.getFloat(); 9105 return true; 9106 } 9107 9108 bool ZeroInitialization(const Expr *E) { 9109 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 9110 return true; 9111 } 9112 9113 bool VisitCallExpr(const CallExpr *E); 9114 9115 bool VisitUnaryOperator(const UnaryOperator *E); 9116 bool VisitBinaryOperator(const BinaryOperator *E); 9117 bool VisitFloatingLiteral(const FloatingLiteral *E); 9118 bool VisitCastExpr(const CastExpr *E); 9119 9120 bool VisitUnaryReal(const UnaryOperator *E); 9121 bool VisitUnaryImag(const UnaryOperator *E); 9122 9123 // FIXME: Missing: array subscript of vector, member of vector 9124 }; 9125 } // end anonymous namespace 9126 9127 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 9128 assert(E->isRValue() && E->getType()->isRealFloatingType()); 9129 return FloatExprEvaluator(Info, Result).Visit(E); 9130 } 9131 9132 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 9133 QualType ResultTy, 9134 const Expr *Arg, 9135 bool SNaN, 9136 llvm::APFloat &Result) { 9137 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 9138 if (!S) return false; 9139 9140 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 9141 9142 llvm::APInt fill; 9143 9144 // Treat empty strings as if they were zero. 9145 if (S->getString().empty()) 9146 fill = llvm::APInt(32, 0); 9147 else if (S->getString().getAsInteger(0, fill)) 9148 return false; 9149 9150 if (Context.getTargetInfo().isNan2008()) { 9151 if (SNaN) 9152 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9153 else 9154 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9155 } else { 9156 // Prior to IEEE 754-2008, architectures were allowed to choose whether 9157 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 9158 // a different encoding to what became a standard in 2008, and for pre- 9159 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 9160 // sNaN. This is now known as "legacy NaN" encoding. 9161 if (SNaN) 9162 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9163 else 9164 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9165 } 9166 9167 return true; 9168 } 9169 9170 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 9171 switch (E->getBuiltinCallee()) { 9172 default: 9173 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9174 9175 case Builtin::BI__builtin_huge_val: 9176 case Builtin::BI__builtin_huge_valf: 9177 case Builtin::BI__builtin_huge_vall: 9178 case Builtin::BI__builtin_inf: 9179 case Builtin::BI__builtin_inff: 9180 case Builtin::BI__builtin_infl: { 9181 const llvm::fltSemantics &Sem = 9182 Info.Ctx.getFloatTypeSemantics(E->getType()); 9183 Result = llvm::APFloat::getInf(Sem); 9184 return true; 9185 } 9186 9187 case Builtin::BI__builtin_nans: 9188 case Builtin::BI__builtin_nansf: 9189 case Builtin::BI__builtin_nansl: 9190 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9191 true, Result)) 9192 return Error(E); 9193 return true; 9194 9195 case Builtin::BI__builtin_nan: 9196 case Builtin::BI__builtin_nanf: 9197 case Builtin::BI__builtin_nanl: 9198 // If this is __builtin_nan() turn this into a nan, otherwise we 9199 // can't constant fold it. 9200 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9201 false, Result)) 9202 return Error(E); 9203 return true; 9204 9205 case Builtin::BI__builtin_fabs: 9206 case Builtin::BI__builtin_fabsf: 9207 case Builtin::BI__builtin_fabsl: 9208 if (!EvaluateFloat(E->getArg(0), Result, Info)) 9209 return false; 9210 9211 if (Result.isNegative()) 9212 Result.changeSign(); 9213 return true; 9214 9215 // FIXME: Builtin::BI__builtin_powi 9216 // FIXME: Builtin::BI__builtin_powif 9217 // FIXME: Builtin::BI__builtin_powil 9218 9219 case Builtin::BI__builtin_copysign: 9220 case Builtin::BI__builtin_copysignf: 9221 case Builtin::BI__builtin_copysignl: { 9222 APFloat RHS(0.); 9223 if (!EvaluateFloat(E->getArg(0), Result, Info) || 9224 !EvaluateFloat(E->getArg(1), RHS, Info)) 9225 return false; 9226 Result.copySign(RHS); 9227 return true; 9228 } 9229 } 9230 } 9231 9232 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9233 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9234 ComplexValue CV; 9235 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9236 return false; 9237 Result = CV.FloatReal; 9238 return true; 9239 } 9240 9241 return Visit(E->getSubExpr()); 9242 } 9243 9244 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9245 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9246 ComplexValue CV; 9247 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9248 return false; 9249 Result = CV.FloatImag; 9250 return true; 9251 } 9252 9253 VisitIgnoredValue(E->getSubExpr()); 9254 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 9255 Result = llvm::APFloat::getZero(Sem); 9256 return true; 9257 } 9258 9259 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9260 switch (E->getOpcode()) { 9261 default: return Error(E); 9262 case UO_Plus: 9263 return EvaluateFloat(E->getSubExpr(), Result, Info); 9264 case UO_Minus: 9265 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 9266 return false; 9267 Result.changeSign(); 9268 return true; 9269 } 9270 } 9271 9272 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9273 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 9274 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9275 9276 APFloat RHS(0.0); 9277 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 9278 if (!LHSOK && !Info.noteFailure()) 9279 return false; 9280 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 9281 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 9282 } 9283 9284 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 9285 Result = E->getValue(); 9286 return true; 9287 } 9288 9289 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 9290 const Expr* SubExpr = E->getSubExpr(); 9291 9292 switch (E->getCastKind()) { 9293 default: 9294 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9295 9296 case CK_IntegralToFloating: { 9297 APSInt IntResult; 9298 return EvaluateInteger(SubExpr, IntResult, Info) && 9299 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 9300 E->getType(), Result); 9301 } 9302 9303 case CK_FloatingCast: { 9304 if (!Visit(SubExpr)) 9305 return false; 9306 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 9307 Result); 9308 } 9309 9310 case CK_FloatingComplexToReal: { 9311 ComplexValue V; 9312 if (!EvaluateComplex(SubExpr, V, Info)) 9313 return false; 9314 Result = V.getComplexFloatReal(); 9315 return true; 9316 } 9317 } 9318 } 9319 9320 //===----------------------------------------------------------------------===// 9321 // Complex Evaluation (for float and integer) 9322 //===----------------------------------------------------------------------===// 9323 9324 namespace { 9325 class ComplexExprEvaluator 9326 : public ExprEvaluatorBase<ComplexExprEvaluator> { 9327 ComplexValue &Result; 9328 9329 public: 9330 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 9331 : ExprEvaluatorBaseTy(info), Result(Result) {} 9332 9333 bool Success(const APValue &V, const Expr *e) { 9334 Result.setFrom(V); 9335 return true; 9336 } 9337 9338 bool ZeroInitialization(const Expr *E); 9339 9340 //===--------------------------------------------------------------------===// 9341 // Visitor Methods 9342 //===--------------------------------------------------------------------===// 9343 9344 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 9345 bool VisitCastExpr(const CastExpr *E); 9346 bool VisitBinaryOperator(const BinaryOperator *E); 9347 bool VisitUnaryOperator(const UnaryOperator *E); 9348 bool VisitInitListExpr(const InitListExpr *E); 9349 }; 9350 } // end anonymous namespace 9351 9352 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 9353 EvalInfo &Info) { 9354 assert(E->isRValue() && E->getType()->isAnyComplexType()); 9355 return ComplexExprEvaluator(Info, Result).Visit(E); 9356 } 9357 9358 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 9359 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 9360 if (ElemTy->isRealFloatingType()) { 9361 Result.makeComplexFloat(); 9362 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 9363 Result.FloatReal = Zero; 9364 Result.FloatImag = Zero; 9365 } else { 9366 Result.makeComplexInt(); 9367 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 9368 Result.IntReal = Zero; 9369 Result.IntImag = Zero; 9370 } 9371 return true; 9372 } 9373 9374 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 9375 const Expr* SubExpr = E->getSubExpr(); 9376 9377 if (SubExpr->getType()->isRealFloatingType()) { 9378 Result.makeComplexFloat(); 9379 APFloat &Imag = Result.FloatImag; 9380 if (!EvaluateFloat(SubExpr, Imag, Info)) 9381 return false; 9382 9383 Result.FloatReal = APFloat(Imag.getSemantics()); 9384 return true; 9385 } else { 9386 assert(SubExpr->getType()->isIntegerType() && 9387 "Unexpected imaginary literal."); 9388 9389 Result.makeComplexInt(); 9390 APSInt &Imag = Result.IntImag; 9391 if (!EvaluateInteger(SubExpr, Imag, Info)) 9392 return false; 9393 9394 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 9395 return true; 9396 } 9397 } 9398 9399 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 9400 9401 switch (E->getCastKind()) { 9402 case CK_BitCast: 9403 case CK_BaseToDerived: 9404 case CK_DerivedToBase: 9405 case CK_UncheckedDerivedToBase: 9406 case CK_Dynamic: 9407 case CK_ToUnion: 9408 case CK_ArrayToPointerDecay: 9409 case CK_FunctionToPointerDecay: 9410 case CK_NullToPointer: 9411 case CK_NullToMemberPointer: 9412 case CK_BaseToDerivedMemberPointer: 9413 case CK_DerivedToBaseMemberPointer: 9414 case CK_MemberPointerToBoolean: 9415 case CK_ReinterpretMemberPointer: 9416 case CK_ConstructorConversion: 9417 case CK_IntegralToPointer: 9418 case CK_PointerToIntegral: 9419 case CK_PointerToBoolean: 9420 case CK_ToVoid: 9421 case CK_VectorSplat: 9422 case CK_IntegralCast: 9423 case CK_BooleanToSignedIntegral: 9424 case CK_IntegralToBoolean: 9425 case CK_IntegralToFloating: 9426 case CK_FloatingToIntegral: 9427 case CK_FloatingToBoolean: 9428 case CK_FloatingCast: 9429 case CK_CPointerToObjCPointerCast: 9430 case CK_BlockPointerToObjCPointerCast: 9431 case CK_AnyPointerToBlockPointerCast: 9432 case CK_ObjCObjectLValueCast: 9433 case CK_FloatingComplexToReal: 9434 case CK_FloatingComplexToBoolean: 9435 case CK_IntegralComplexToReal: 9436 case CK_IntegralComplexToBoolean: 9437 case CK_ARCProduceObject: 9438 case CK_ARCConsumeObject: 9439 case CK_ARCReclaimReturnedObject: 9440 case CK_ARCExtendBlockObject: 9441 case CK_CopyAndAutoreleaseBlockObject: 9442 case CK_BuiltinFnToFnPtr: 9443 case CK_ZeroToOCLEvent: 9444 case CK_ZeroToOCLQueue: 9445 case CK_NonAtomicToAtomic: 9446 case CK_AddressSpaceConversion: 9447 case CK_IntToOCLSampler: 9448 llvm_unreachable("invalid cast kind for complex value"); 9449 9450 case CK_LValueToRValue: 9451 case CK_AtomicToNonAtomic: 9452 case CK_NoOp: 9453 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9454 9455 case CK_Dependent: 9456 case CK_LValueBitCast: 9457 case CK_UserDefinedConversion: 9458 return Error(E); 9459 9460 case CK_FloatingRealToComplex: { 9461 APFloat &Real = Result.FloatReal; 9462 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 9463 return false; 9464 9465 Result.makeComplexFloat(); 9466 Result.FloatImag = APFloat(Real.getSemantics()); 9467 return true; 9468 } 9469 9470 case CK_FloatingComplexCast: { 9471 if (!Visit(E->getSubExpr())) 9472 return false; 9473 9474 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 9475 QualType From 9476 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 9477 9478 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 9479 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 9480 } 9481 9482 case CK_FloatingComplexToIntegralComplex: { 9483 if (!Visit(E->getSubExpr())) 9484 return false; 9485 9486 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 9487 QualType From 9488 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 9489 Result.makeComplexInt(); 9490 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 9491 To, Result.IntReal) && 9492 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 9493 To, Result.IntImag); 9494 } 9495 9496 case CK_IntegralRealToComplex: { 9497 APSInt &Real = Result.IntReal; 9498 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 9499 return false; 9500 9501 Result.makeComplexInt(); 9502 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 9503 return true; 9504 } 9505 9506 case CK_IntegralComplexCast: { 9507 if (!Visit(E->getSubExpr())) 9508 return false; 9509 9510 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 9511 QualType From 9512 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 9513 9514 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 9515 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 9516 return true; 9517 } 9518 9519 case CK_IntegralComplexToFloatingComplex: { 9520 if (!Visit(E->getSubExpr())) 9521 return false; 9522 9523 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 9524 QualType From 9525 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 9526 Result.makeComplexFloat(); 9527 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 9528 To, Result.FloatReal) && 9529 HandleIntToFloatCast(Info, E, From, Result.IntImag, 9530 To, Result.FloatImag); 9531 } 9532 } 9533 9534 llvm_unreachable("unknown cast resulting in complex value"); 9535 } 9536 9537 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9538 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 9539 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9540 9541 // Track whether the LHS or RHS is real at the type system level. When this is 9542 // the case we can simplify our evaluation strategy. 9543 bool LHSReal = false, RHSReal = false; 9544 9545 bool LHSOK; 9546 if (E->getLHS()->getType()->isRealFloatingType()) { 9547 LHSReal = true; 9548 APFloat &Real = Result.FloatReal; 9549 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 9550 if (LHSOK) { 9551 Result.makeComplexFloat(); 9552 Result.FloatImag = APFloat(Real.getSemantics()); 9553 } 9554 } else { 9555 LHSOK = Visit(E->getLHS()); 9556 } 9557 if (!LHSOK && !Info.noteFailure()) 9558 return false; 9559 9560 ComplexValue RHS; 9561 if (E->getRHS()->getType()->isRealFloatingType()) { 9562 RHSReal = true; 9563 APFloat &Real = RHS.FloatReal; 9564 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 9565 return false; 9566 RHS.makeComplexFloat(); 9567 RHS.FloatImag = APFloat(Real.getSemantics()); 9568 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 9569 return false; 9570 9571 assert(!(LHSReal && RHSReal) && 9572 "Cannot have both operands of a complex operation be real."); 9573 switch (E->getOpcode()) { 9574 default: return Error(E); 9575 case BO_Add: 9576 if (Result.isComplexFloat()) { 9577 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 9578 APFloat::rmNearestTiesToEven); 9579 if (LHSReal) 9580 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 9581 else if (!RHSReal) 9582 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 9583 APFloat::rmNearestTiesToEven); 9584 } else { 9585 Result.getComplexIntReal() += RHS.getComplexIntReal(); 9586 Result.getComplexIntImag() += RHS.getComplexIntImag(); 9587 } 9588 break; 9589 case BO_Sub: 9590 if (Result.isComplexFloat()) { 9591 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 9592 APFloat::rmNearestTiesToEven); 9593 if (LHSReal) { 9594 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 9595 Result.getComplexFloatImag().changeSign(); 9596 } else if (!RHSReal) { 9597 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 9598 APFloat::rmNearestTiesToEven); 9599 } 9600 } else { 9601 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 9602 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 9603 } 9604 break; 9605 case BO_Mul: 9606 if (Result.isComplexFloat()) { 9607 // This is an implementation of complex multiplication according to the 9608 // constraints laid out in C11 Annex G. The implemention uses the 9609 // following naming scheme: 9610 // (a + ib) * (c + id) 9611 ComplexValue LHS = Result; 9612 APFloat &A = LHS.getComplexFloatReal(); 9613 APFloat &B = LHS.getComplexFloatImag(); 9614 APFloat &C = RHS.getComplexFloatReal(); 9615 APFloat &D = RHS.getComplexFloatImag(); 9616 APFloat &ResR = Result.getComplexFloatReal(); 9617 APFloat &ResI = Result.getComplexFloatImag(); 9618 if (LHSReal) { 9619 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 9620 ResR = A * C; 9621 ResI = A * D; 9622 } else if (RHSReal) { 9623 ResR = C * A; 9624 ResI = C * B; 9625 } else { 9626 // In the fully general case, we need to handle NaNs and infinities 9627 // robustly. 9628 APFloat AC = A * C; 9629 APFloat BD = B * D; 9630 APFloat AD = A * D; 9631 APFloat BC = B * C; 9632 ResR = AC - BD; 9633 ResI = AD + BC; 9634 if (ResR.isNaN() && ResI.isNaN()) { 9635 bool Recalc = false; 9636 if (A.isInfinity() || B.isInfinity()) { 9637 A = APFloat::copySign( 9638 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 9639 B = APFloat::copySign( 9640 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 9641 if (C.isNaN()) 9642 C = APFloat::copySign(APFloat(C.getSemantics()), C); 9643 if (D.isNaN()) 9644 D = APFloat::copySign(APFloat(D.getSemantics()), D); 9645 Recalc = true; 9646 } 9647 if (C.isInfinity() || D.isInfinity()) { 9648 C = APFloat::copySign( 9649 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 9650 D = APFloat::copySign( 9651 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 9652 if (A.isNaN()) 9653 A = APFloat::copySign(APFloat(A.getSemantics()), A); 9654 if (B.isNaN()) 9655 B = APFloat::copySign(APFloat(B.getSemantics()), B); 9656 Recalc = true; 9657 } 9658 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 9659 AD.isInfinity() || BC.isInfinity())) { 9660 if (A.isNaN()) 9661 A = APFloat::copySign(APFloat(A.getSemantics()), A); 9662 if (B.isNaN()) 9663 B = APFloat::copySign(APFloat(B.getSemantics()), B); 9664 if (C.isNaN()) 9665 C = APFloat::copySign(APFloat(C.getSemantics()), C); 9666 if (D.isNaN()) 9667 D = APFloat::copySign(APFloat(D.getSemantics()), D); 9668 Recalc = true; 9669 } 9670 if (Recalc) { 9671 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 9672 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 9673 } 9674 } 9675 } 9676 } else { 9677 ComplexValue LHS = Result; 9678 Result.getComplexIntReal() = 9679 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 9680 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 9681 Result.getComplexIntImag() = 9682 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 9683 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 9684 } 9685 break; 9686 case BO_Div: 9687 if (Result.isComplexFloat()) { 9688 // This is an implementation of complex division according to the 9689 // constraints laid out in C11 Annex G. The implemention uses the 9690 // following naming scheme: 9691 // (a + ib) / (c + id) 9692 ComplexValue LHS = Result; 9693 APFloat &A = LHS.getComplexFloatReal(); 9694 APFloat &B = LHS.getComplexFloatImag(); 9695 APFloat &C = RHS.getComplexFloatReal(); 9696 APFloat &D = RHS.getComplexFloatImag(); 9697 APFloat &ResR = Result.getComplexFloatReal(); 9698 APFloat &ResI = Result.getComplexFloatImag(); 9699 if (RHSReal) { 9700 ResR = A / C; 9701 ResI = B / C; 9702 } else { 9703 if (LHSReal) { 9704 // No real optimizations we can do here, stub out with zero. 9705 B = APFloat::getZero(A.getSemantics()); 9706 } 9707 int DenomLogB = 0; 9708 APFloat MaxCD = maxnum(abs(C), abs(D)); 9709 if (MaxCD.isFinite()) { 9710 DenomLogB = ilogb(MaxCD); 9711 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 9712 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 9713 } 9714 APFloat Denom = C * C + D * D; 9715 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 9716 APFloat::rmNearestTiesToEven); 9717 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 9718 APFloat::rmNearestTiesToEven); 9719 if (ResR.isNaN() && ResI.isNaN()) { 9720 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 9721 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 9722 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 9723 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 9724 D.isFinite()) { 9725 A = APFloat::copySign( 9726 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 9727 B = APFloat::copySign( 9728 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 9729 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 9730 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 9731 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 9732 C = APFloat::copySign( 9733 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 9734 D = APFloat::copySign( 9735 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 9736 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 9737 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 9738 } 9739 } 9740 } 9741 } else { 9742 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 9743 return Error(E, diag::note_expr_divide_by_zero); 9744 9745 ComplexValue LHS = Result; 9746 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 9747 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 9748 Result.getComplexIntReal() = 9749 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 9750 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 9751 Result.getComplexIntImag() = 9752 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 9753 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 9754 } 9755 break; 9756 } 9757 9758 return true; 9759 } 9760 9761 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9762 // Get the operand value into 'Result'. 9763 if (!Visit(E->getSubExpr())) 9764 return false; 9765 9766 switch (E->getOpcode()) { 9767 default: 9768 return Error(E); 9769 case UO_Extension: 9770 return true; 9771 case UO_Plus: 9772 // The result is always just the subexpr. 9773 return true; 9774 case UO_Minus: 9775 if (Result.isComplexFloat()) { 9776 Result.getComplexFloatReal().changeSign(); 9777 Result.getComplexFloatImag().changeSign(); 9778 } 9779 else { 9780 Result.getComplexIntReal() = -Result.getComplexIntReal(); 9781 Result.getComplexIntImag() = -Result.getComplexIntImag(); 9782 } 9783 return true; 9784 case UO_Not: 9785 if (Result.isComplexFloat()) 9786 Result.getComplexFloatImag().changeSign(); 9787 else 9788 Result.getComplexIntImag() = -Result.getComplexIntImag(); 9789 return true; 9790 } 9791 } 9792 9793 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9794 if (E->getNumInits() == 2) { 9795 if (E->getType()->isComplexType()) { 9796 Result.makeComplexFloat(); 9797 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 9798 return false; 9799 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 9800 return false; 9801 } else { 9802 Result.makeComplexInt(); 9803 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 9804 return false; 9805 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 9806 return false; 9807 } 9808 return true; 9809 } 9810 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 9811 } 9812 9813 //===----------------------------------------------------------------------===// 9814 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 9815 // implicit conversion. 9816 //===----------------------------------------------------------------------===// 9817 9818 namespace { 9819 class AtomicExprEvaluator : 9820 public ExprEvaluatorBase<AtomicExprEvaluator> { 9821 const LValue *This; 9822 APValue &Result; 9823 public: 9824 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 9825 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 9826 9827 bool Success(const APValue &V, const Expr *E) { 9828 Result = V; 9829 return true; 9830 } 9831 9832 bool ZeroInitialization(const Expr *E) { 9833 ImplicitValueInitExpr VIE( 9834 E->getType()->castAs<AtomicType>()->getValueType()); 9835 // For atomic-qualified class (and array) types in C++, initialize the 9836 // _Atomic-wrapped subobject directly, in-place. 9837 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 9838 : Evaluate(Result, Info, &VIE); 9839 } 9840 9841 bool VisitCastExpr(const CastExpr *E) { 9842 switch (E->getCastKind()) { 9843 default: 9844 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9845 case CK_NonAtomicToAtomic: 9846 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 9847 : Evaluate(Result, Info, E->getSubExpr()); 9848 } 9849 } 9850 }; 9851 } // end anonymous namespace 9852 9853 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 9854 EvalInfo &Info) { 9855 assert(E->isRValue() && E->getType()->isAtomicType()); 9856 return AtomicExprEvaluator(Info, This, Result).Visit(E); 9857 } 9858 9859 //===----------------------------------------------------------------------===// 9860 // Void expression evaluation, primarily for a cast to void on the LHS of a 9861 // comma operator 9862 //===----------------------------------------------------------------------===// 9863 9864 namespace { 9865 class VoidExprEvaluator 9866 : public ExprEvaluatorBase<VoidExprEvaluator> { 9867 public: 9868 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 9869 9870 bool Success(const APValue &V, const Expr *e) { return true; } 9871 9872 bool ZeroInitialization(const Expr *E) { return true; } 9873 9874 bool VisitCastExpr(const CastExpr *E) { 9875 switch (E->getCastKind()) { 9876 default: 9877 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9878 case CK_ToVoid: 9879 VisitIgnoredValue(E->getSubExpr()); 9880 return true; 9881 } 9882 } 9883 9884 bool VisitCallExpr(const CallExpr *E) { 9885 switch (E->getBuiltinCallee()) { 9886 default: 9887 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9888 case Builtin::BI__assume: 9889 case Builtin::BI__builtin_assume: 9890 // The argument is not evaluated! 9891 return true; 9892 } 9893 } 9894 }; 9895 } // end anonymous namespace 9896 9897 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 9898 assert(E->isRValue() && E->getType()->isVoidType()); 9899 return VoidExprEvaluator(Info).Visit(E); 9900 } 9901 9902 //===----------------------------------------------------------------------===// 9903 // Top level Expr::EvaluateAsRValue method. 9904 //===----------------------------------------------------------------------===// 9905 9906 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 9907 // In C, function designators are not lvalues, but we evaluate them as if they 9908 // are. 9909 QualType T = E->getType(); 9910 if (E->isGLValue() || T->isFunctionType()) { 9911 LValue LV; 9912 if (!EvaluateLValue(E, LV, Info)) 9913 return false; 9914 LV.moveInto(Result); 9915 } else if (T->isVectorType()) { 9916 if (!EvaluateVector(E, Result, Info)) 9917 return false; 9918 } else if (T->isIntegralOrEnumerationType()) { 9919 if (!IntExprEvaluator(Info, Result).Visit(E)) 9920 return false; 9921 } else if (T->hasPointerRepresentation()) { 9922 LValue LV; 9923 if (!EvaluatePointer(E, LV, Info)) 9924 return false; 9925 LV.moveInto(Result); 9926 } else if (T->isRealFloatingType()) { 9927 llvm::APFloat F(0.0); 9928 if (!EvaluateFloat(E, F, Info)) 9929 return false; 9930 Result = APValue(F); 9931 } else if (T->isAnyComplexType()) { 9932 ComplexValue C; 9933 if (!EvaluateComplex(E, C, Info)) 9934 return false; 9935 C.moveInto(Result); 9936 } else if (T->isMemberPointerType()) { 9937 MemberPtr P; 9938 if (!EvaluateMemberPointer(E, P, Info)) 9939 return false; 9940 P.moveInto(Result); 9941 return true; 9942 } else if (T->isArrayType()) { 9943 LValue LV; 9944 LV.set(E, Info.CurrentCall->Index); 9945 APValue &Value = Info.CurrentCall->createTemporary(E, false); 9946 if (!EvaluateArray(E, LV, Value, Info)) 9947 return false; 9948 Result = Value; 9949 } else if (T->isRecordType()) { 9950 LValue LV; 9951 LV.set(E, Info.CurrentCall->Index); 9952 APValue &Value = Info.CurrentCall->createTemporary(E, false); 9953 if (!EvaluateRecord(E, LV, Value, Info)) 9954 return false; 9955 Result = Value; 9956 } else if (T->isVoidType()) { 9957 if (!Info.getLangOpts().CPlusPlus11) 9958 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 9959 << E->getType(); 9960 if (!EvaluateVoid(E, Info)) 9961 return false; 9962 } else if (T->isAtomicType()) { 9963 QualType Unqual = T.getAtomicUnqualifiedType(); 9964 if (Unqual->isArrayType() || Unqual->isRecordType()) { 9965 LValue LV; 9966 LV.set(E, Info.CurrentCall->Index); 9967 APValue &Value = Info.CurrentCall->createTemporary(E, false); 9968 if (!EvaluateAtomic(E, &LV, Value, Info)) 9969 return false; 9970 } else { 9971 if (!EvaluateAtomic(E, nullptr, Result, Info)) 9972 return false; 9973 } 9974 } else if (Info.getLangOpts().CPlusPlus11) { 9975 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 9976 return false; 9977 } else { 9978 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 9979 return false; 9980 } 9981 9982 return true; 9983 } 9984 9985 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 9986 /// cases, the in-place evaluation is essential, since later initializers for 9987 /// an object can indirectly refer to subobjects which were initialized earlier. 9988 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 9989 const Expr *E, bool AllowNonLiteralTypes) { 9990 assert(!E->isValueDependent()); 9991 9992 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 9993 return false; 9994 9995 if (E->isRValue()) { 9996 // Evaluate arrays and record types in-place, so that later initializers can 9997 // refer to earlier-initialized members of the object. 9998 QualType T = E->getType(); 9999 if (T->isArrayType()) 10000 return EvaluateArray(E, This, Result, Info); 10001 else if (T->isRecordType()) 10002 return EvaluateRecord(E, This, Result, Info); 10003 else if (T->isAtomicType()) { 10004 QualType Unqual = T.getAtomicUnqualifiedType(); 10005 if (Unqual->isArrayType() || Unqual->isRecordType()) 10006 return EvaluateAtomic(E, &This, Result, Info); 10007 } 10008 } 10009 10010 // For any other type, in-place evaluation is unimportant. 10011 return Evaluate(Result, Info, E); 10012 } 10013 10014 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 10015 /// lvalue-to-rvalue cast if it is an lvalue. 10016 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 10017 if (E->getType().isNull()) 10018 return false; 10019 10020 if (!CheckLiteralType(Info, E)) 10021 return false; 10022 10023 if (!::Evaluate(Result, Info, E)) 10024 return false; 10025 10026 if (E->isGLValue()) { 10027 LValue LV; 10028 LV.setFrom(Info.Ctx, Result); 10029 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 10030 return false; 10031 } 10032 10033 // Check this core constant expression is a constant expression. 10034 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 10035 } 10036 10037 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 10038 const ASTContext &Ctx, bool &IsConst) { 10039 // Fast-path evaluations of integer literals, since we sometimes see files 10040 // containing vast quantities of these. 10041 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 10042 Result.Val = APValue(APSInt(L->getValue(), 10043 L->getType()->isUnsignedIntegerType())); 10044 IsConst = true; 10045 return true; 10046 } 10047 10048 // This case should be rare, but we need to check it before we check on 10049 // the type below. 10050 if (Exp->getType().isNull()) { 10051 IsConst = false; 10052 return true; 10053 } 10054 10055 // FIXME: Evaluating values of large array and record types can cause 10056 // performance problems. Only do so in C++11 for now. 10057 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 10058 Exp->getType()->isRecordType()) && 10059 !Ctx.getLangOpts().CPlusPlus11) { 10060 IsConst = false; 10061 return true; 10062 } 10063 return false; 10064 } 10065 10066 10067 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 10068 /// any crazy technique (that has nothing to do with language standards) that 10069 /// we want to. If this function returns true, it returns the folded constant 10070 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 10071 /// will be applied to the result. 10072 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { 10073 bool IsConst; 10074 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst)) 10075 return IsConst; 10076 10077 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 10078 return ::EvaluateAsRValue(Info, this, Result.Val); 10079 } 10080 10081 bool Expr::EvaluateAsBooleanCondition(bool &Result, 10082 const ASTContext &Ctx) const { 10083 EvalResult Scratch; 10084 return EvaluateAsRValue(Scratch, Ctx) && 10085 HandleConversionToBool(Scratch.Val, Result); 10086 } 10087 10088 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 10089 Expr::SideEffectsKind SEK) { 10090 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 10091 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 10092 } 10093 10094 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx, 10095 SideEffectsKind AllowSideEffects) const { 10096 if (!getType()->isIntegralOrEnumerationType()) 10097 return false; 10098 10099 EvalResult ExprResult; 10100 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() || 10101 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10102 return false; 10103 10104 Result = ExprResult.Val.getInt(); 10105 return true; 10106 } 10107 10108 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 10109 SideEffectsKind AllowSideEffects) const { 10110 if (!getType()->isRealFloatingType()) 10111 return false; 10112 10113 EvalResult ExprResult; 10114 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() || 10115 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10116 return false; 10117 10118 Result = ExprResult.Val.getFloat(); 10119 return true; 10120 } 10121 10122 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 10123 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 10124 10125 LValue LV; 10126 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 10127 !CheckLValueConstantExpression(Info, getExprLoc(), 10128 Ctx.getLValueReferenceType(getType()), LV)) 10129 return false; 10130 10131 LV.moveInto(Result.Val); 10132 return true; 10133 } 10134 10135 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 10136 const VarDecl *VD, 10137 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 10138 // FIXME: Evaluating initializers for large array and record types can cause 10139 // performance problems. Only do so in C++11 for now. 10140 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 10141 !Ctx.getLangOpts().CPlusPlus11) 10142 return false; 10143 10144 Expr::EvalStatus EStatus; 10145 EStatus.Diag = &Notes; 10146 10147 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr() 10148 ? EvalInfo::EM_ConstantExpression 10149 : EvalInfo::EM_ConstantFold); 10150 InitInfo.setEvaluatingDecl(VD, Value); 10151 10152 LValue LVal; 10153 LVal.set(VD); 10154 10155 // C++11 [basic.start.init]p2: 10156 // Variables with static storage duration or thread storage duration shall be 10157 // zero-initialized before any other initialization takes place. 10158 // This behavior is not present in C. 10159 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 10160 !VD->getType()->isReferenceType()) { 10161 ImplicitValueInitExpr VIE(VD->getType()); 10162 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, 10163 /*AllowNonLiteralTypes=*/true)) 10164 return false; 10165 } 10166 10167 if (!EvaluateInPlace(Value, InitInfo, LVal, this, 10168 /*AllowNonLiteralTypes=*/true) || 10169 EStatus.HasSideEffects) 10170 return false; 10171 10172 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 10173 Value); 10174 } 10175 10176 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 10177 /// constant folded, but discard the result. 10178 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 10179 EvalResult Result; 10180 return EvaluateAsRValue(Result, Ctx) && 10181 !hasUnacceptableSideEffect(Result, SEK); 10182 } 10183 10184 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 10185 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 10186 EvalResult EvalResult; 10187 EvalResult.Diag = Diag; 10188 bool Result = EvaluateAsRValue(EvalResult, Ctx); 10189 (void)Result; 10190 assert(Result && "Could not evaluate expression"); 10191 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 10192 10193 return EvalResult.Val.getInt(); 10194 } 10195 10196 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 10197 bool IsConst; 10198 EvalResult EvalResult; 10199 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) { 10200 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow); 10201 (void)::EvaluateAsRValue(Info, this, EvalResult.Val); 10202 } 10203 } 10204 10205 bool Expr::EvalResult::isGlobalLValue() const { 10206 assert(Val.isLValue()); 10207 return IsGlobalLValue(Val.getLValueBase()); 10208 } 10209 10210 10211 /// isIntegerConstantExpr - this recursive routine will test if an expression is 10212 /// an integer constant expression. 10213 10214 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 10215 /// comma, etc 10216 10217 // CheckICE - This function does the fundamental ICE checking: the returned 10218 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 10219 // and a (possibly null) SourceLocation indicating the location of the problem. 10220 // 10221 // Note that to reduce code duplication, this helper does no evaluation 10222 // itself; the caller checks whether the expression is evaluatable, and 10223 // in the rare cases where CheckICE actually cares about the evaluated 10224 // value, it calls into Evaluate. 10225 10226 namespace { 10227 10228 enum ICEKind { 10229 /// This expression is an ICE. 10230 IK_ICE, 10231 /// This expression is not an ICE, but if it isn't evaluated, it's 10232 /// a legal subexpression for an ICE. This return value is used to handle 10233 /// the comma operator in C99 mode, and non-constant subexpressions. 10234 IK_ICEIfUnevaluated, 10235 /// This expression is not an ICE, and is not a legal subexpression for one. 10236 IK_NotICE 10237 }; 10238 10239 struct ICEDiag { 10240 ICEKind Kind; 10241 SourceLocation Loc; 10242 10243 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 10244 }; 10245 10246 } 10247 10248 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 10249 10250 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 10251 10252 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 10253 Expr::EvalResult EVResult; 10254 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects || 10255 !EVResult.Val.isInt()) 10256 return ICEDiag(IK_NotICE, E->getLocStart()); 10257 10258 return NoDiag(); 10259 } 10260 10261 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 10262 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 10263 if (!E->getType()->isIntegralOrEnumerationType()) 10264 return ICEDiag(IK_NotICE, E->getLocStart()); 10265 10266 switch (E->getStmtClass()) { 10267 #define ABSTRACT_STMT(Node) 10268 #define STMT(Node, Base) case Expr::Node##Class: 10269 #define EXPR(Node, Base) 10270 #include "clang/AST/StmtNodes.inc" 10271 case Expr::PredefinedExprClass: 10272 case Expr::FloatingLiteralClass: 10273 case Expr::ImaginaryLiteralClass: 10274 case Expr::StringLiteralClass: 10275 case Expr::ArraySubscriptExprClass: 10276 case Expr::OMPArraySectionExprClass: 10277 case Expr::MemberExprClass: 10278 case Expr::CompoundAssignOperatorClass: 10279 case Expr::CompoundLiteralExprClass: 10280 case Expr::ExtVectorElementExprClass: 10281 case Expr::DesignatedInitExprClass: 10282 case Expr::ArrayInitLoopExprClass: 10283 case Expr::ArrayInitIndexExprClass: 10284 case Expr::NoInitExprClass: 10285 case Expr::DesignatedInitUpdateExprClass: 10286 case Expr::ImplicitValueInitExprClass: 10287 case Expr::ParenListExprClass: 10288 case Expr::VAArgExprClass: 10289 case Expr::AddrLabelExprClass: 10290 case Expr::StmtExprClass: 10291 case Expr::CXXMemberCallExprClass: 10292 case Expr::CUDAKernelCallExprClass: 10293 case Expr::CXXDynamicCastExprClass: 10294 case Expr::CXXTypeidExprClass: 10295 case Expr::CXXUuidofExprClass: 10296 case Expr::MSPropertyRefExprClass: 10297 case Expr::MSPropertySubscriptExprClass: 10298 case Expr::CXXNullPtrLiteralExprClass: 10299 case Expr::UserDefinedLiteralClass: 10300 case Expr::CXXThisExprClass: 10301 case Expr::CXXThrowExprClass: 10302 case Expr::CXXNewExprClass: 10303 case Expr::CXXDeleteExprClass: 10304 case Expr::CXXPseudoDestructorExprClass: 10305 case Expr::UnresolvedLookupExprClass: 10306 case Expr::TypoExprClass: 10307 case Expr::DependentScopeDeclRefExprClass: 10308 case Expr::CXXConstructExprClass: 10309 case Expr::CXXInheritedCtorInitExprClass: 10310 case Expr::CXXStdInitializerListExprClass: 10311 case Expr::CXXBindTemporaryExprClass: 10312 case Expr::ExprWithCleanupsClass: 10313 case Expr::CXXTemporaryObjectExprClass: 10314 case Expr::CXXUnresolvedConstructExprClass: 10315 case Expr::CXXDependentScopeMemberExprClass: 10316 case Expr::UnresolvedMemberExprClass: 10317 case Expr::ObjCStringLiteralClass: 10318 case Expr::ObjCBoxedExprClass: 10319 case Expr::ObjCArrayLiteralClass: 10320 case Expr::ObjCDictionaryLiteralClass: 10321 case Expr::ObjCEncodeExprClass: 10322 case Expr::ObjCMessageExprClass: 10323 case Expr::ObjCSelectorExprClass: 10324 case Expr::ObjCProtocolExprClass: 10325 case Expr::ObjCIvarRefExprClass: 10326 case Expr::ObjCPropertyRefExprClass: 10327 case Expr::ObjCSubscriptRefExprClass: 10328 case Expr::ObjCIsaExprClass: 10329 case Expr::ObjCAvailabilityCheckExprClass: 10330 case Expr::ShuffleVectorExprClass: 10331 case Expr::ConvertVectorExprClass: 10332 case Expr::BlockExprClass: 10333 case Expr::NoStmtClass: 10334 case Expr::OpaqueValueExprClass: 10335 case Expr::PackExpansionExprClass: 10336 case Expr::SubstNonTypeTemplateParmPackExprClass: 10337 case Expr::FunctionParmPackExprClass: 10338 case Expr::AsTypeExprClass: 10339 case Expr::ObjCIndirectCopyRestoreExprClass: 10340 case Expr::MaterializeTemporaryExprClass: 10341 case Expr::PseudoObjectExprClass: 10342 case Expr::AtomicExprClass: 10343 case Expr::LambdaExprClass: 10344 case Expr::CXXFoldExprClass: 10345 case Expr::CoawaitExprClass: 10346 case Expr::DependentCoawaitExprClass: 10347 case Expr::CoyieldExprClass: 10348 return ICEDiag(IK_NotICE, E->getLocStart()); 10349 10350 case Expr::InitListExprClass: { 10351 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 10352 // form "T x = { a };" is equivalent to "T x = a;". 10353 // Unless we're initializing a reference, T is a scalar as it is known to be 10354 // of integral or enumeration type. 10355 if (E->isRValue()) 10356 if (cast<InitListExpr>(E)->getNumInits() == 1) 10357 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 10358 return ICEDiag(IK_NotICE, E->getLocStart()); 10359 } 10360 10361 case Expr::SizeOfPackExprClass: 10362 case Expr::GNUNullExprClass: 10363 // GCC considers the GNU __null value to be an integral constant expression. 10364 return NoDiag(); 10365 10366 case Expr::SubstNonTypeTemplateParmExprClass: 10367 return 10368 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 10369 10370 case Expr::ParenExprClass: 10371 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 10372 case Expr::GenericSelectionExprClass: 10373 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 10374 case Expr::IntegerLiteralClass: 10375 case Expr::CharacterLiteralClass: 10376 case Expr::ObjCBoolLiteralExprClass: 10377 case Expr::CXXBoolLiteralExprClass: 10378 case Expr::CXXScalarValueInitExprClass: 10379 case Expr::TypeTraitExprClass: 10380 case Expr::ArrayTypeTraitExprClass: 10381 case Expr::ExpressionTraitExprClass: 10382 case Expr::CXXNoexceptExprClass: 10383 return NoDiag(); 10384 case Expr::CallExprClass: 10385 case Expr::CXXOperatorCallExprClass: { 10386 // C99 6.6/3 allows function calls within unevaluated subexpressions of 10387 // constant expressions, but they can never be ICEs because an ICE cannot 10388 // contain an operand of (pointer to) function type. 10389 const CallExpr *CE = cast<CallExpr>(E); 10390 if (CE->getBuiltinCallee()) 10391 return CheckEvalInICE(E, Ctx); 10392 return ICEDiag(IK_NotICE, E->getLocStart()); 10393 } 10394 case Expr::DeclRefExprClass: { 10395 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 10396 return NoDiag(); 10397 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl()); 10398 if (Ctx.getLangOpts().CPlusPlus && 10399 D && IsConstNonVolatile(D->getType())) { 10400 // Parameter variables are never constants. Without this check, 10401 // getAnyInitializer() can find a default argument, which leads 10402 // to chaos. 10403 if (isa<ParmVarDecl>(D)) 10404 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 10405 10406 // C++ 7.1.5.1p2 10407 // A variable of non-volatile const-qualified integral or enumeration 10408 // type initialized by an ICE can be used in ICEs. 10409 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 10410 if (!Dcl->getType()->isIntegralOrEnumerationType()) 10411 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 10412 10413 const VarDecl *VD; 10414 // Look for a declaration of this variable that has an initializer, and 10415 // check whether it is an ICE. 10416 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 10417 return NoDiag(); 10418 else 10419 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 10420 } 10421 } 10422 return ICEDiag(IK_NotICE, E->getLocStart()); 10423 } 10424 case Expr::UnaryOperatorClass: { 10425 const UnaryOperator *Exp = cast<UnaryOperator>(E); 10426 switch (Exp->getOpcode()) { 10427 case UO_PostInc: 10428 case UO_PostDec: 10429 case UO_PreInc: 10430 case UO_PreDec: 10431 case UO_AddrOf: 10432 case UO_Deref: 10433 case UO_Coawait: 10434 // C99 6.6/3 allows increment and decrement within unevaluated 10435 // subexpressions of constant expressions, but they can never be ICEs 10436 // because an ICE cannot contain an lvalue operand. 10437 return ICEDiag(IK_NotICE, E->getLocStart()); 10438 case UO_Extension: 10439 case UO_LNot: 10440 case UO_Plus: 10441 case UO_Minus: 10442 case UO_Not: 10443 case UO_Real: 10444 case UO_Imag: 10445 return CheckICE(Exp->getSubExpr(), Ctx); 10446 } 10447 10448 // OffsetOf falls through here. 10449 LLVM_FALLTHROUGH; 10450 } 10451 case Expr::OffsetOfExprClass: { 10452 // Note that per C99, offsetof must be an ICE. And AFAIK, using 10453 // EvaluateAsRValue matches the proposed gcc behavior for cases like 10454 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 10455 // compliance: we should warn earlier for offsetof expressions with 10456 // array subscripts that aren't ICEs, and if the array subscripts 10457 // are ICEs, the value of the offsetof must be an integer constant. 10458 return CheckEvalInICE(E, Ctx); 10459 } 10460 case Expr::UnaryExprOrTypeTraitExprClass: { 10461 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 10462 if ((Exp->getKind() == UETT_SizeOf) && 10463 Exp->getTypeOfArgument()->isVariableArrayType()) 10464 return ICEDiag(IK_NotICE, E->getLocStart()); 10465 return NoDiag(); 10466 } 10467 case Expr::BinaryOperatorClass: { 10468 const BinaryOperator *Exp = cast<BinaryOperator>(E); 10469 switch (Exp->getOpcode()) { 10470 case BO_PtrMemD: 10471 case BO_PtrMemI: 10472 case BO_Assign: 10473 case BO_MulAssign: 10474 case BO_DivAssign: 10475 case BO_RemAssign: 10476 case BO_AddAssign: 10477 case BO_SubAssign: 10478 case BO_ShlAssign: 10479 case BO_ShrAssign: 10480 case BO_AndAssign: 10481 case BO_XorAssign: 10482 case BO_OrAssign: 10483 case BO_Cmp: // FIXME: Re-enable once we can evaluate this. 10484 // C99 6.6/3 allows assignments within unevaluated subexpressions of 10485 // constant expressions, but they can never be ICEs because an ICE cannot 10486 // contain an lvalue operand. 10487 return ICEDiag(IK_NotICE, E->getLocStart()); 10488 10489 case BO_Mul: 10490 case BO_Div: 10491 case BO_Rem: 10492 case BO_Add: 10493 case BO_Sub: 10494 case BO_Shl: 10495 case BO_Shr: 10496 case BO_LT: 10497 case BO_GT: 10498 case BO_LE: 10499 case BO_GE: 10500 case BO_EQ: 10501 case BO_NE: 10502 case BO_And: 10503 case BO_Xor: 10504 case BO_Or: 10505 case BO_Comma: { 10506 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 10507 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 10508 if (Exp->getOpcode() == BO_Div || 10509 Exp->getOpcode() == BO_Rem) { 10510 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 10511 // we don't evaluate one. 10512 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 10513 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 10514 if (REval == 0) 10515 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 10516 if (REval.isSigned() && REval.isAllOnesValue()) { 10517 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 10518 if (LEval.isMinSignedValue()) 10519 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 10520 } 10521 } 10522 } 10523 if (Exp->getOpcode() == BO_Comma) { 10524 if (Ctx.getLangOpts().C99) { 10525 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 10526 // if it isn't evaluated. 10527 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 10528 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart()); 10529 } else { 10530 // In both C89 and C++, commas in ICEs are illegal. 10531 return ICEDiag(IK_NotICE, E->getLocStart()); 10532 } 10533 } 10534 return Worst(LHSResult, RHSResult); 10535 } 10536 case BO_LAnd: 10537 case BO_LOr: { 10538 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 10539 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 10540 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 10541 // Rare case where the RHS has a comma "side-effect"; we need 10542 // to actually check the condition to see whether the side 10543 // with the comma is evaluated. 10544 if ((Exp->getOpcode() == BO_LAnd) != 10545 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 10546 return RHSResult; 10547 return NoDiag(); 10548 } 10549 10550 return Worst(LHSResult, RHSResult); 10551 } 10552 } 10553 LLVM_FALLTHROUGH; 10554 } 10555 case Expr::ImplicitCastExprClass: 10556 case Expr::CStyleCastExprClass: 10557 case Expr::CXXFunctionalCastExprClass: 10558 case Expr::CXXStaticCastExprClass: 10559 case Expr::CXXReinterpretCastExprClass: 10560 case Expr::CXXConstCastExprClass: 10561 case Expr::ObjCBridgedCastExprClass: { 10562 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 10563 if (isa<ExplicitCastExpr>(E)) { 10564 if (const FloatingLiteral *FL 10565 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 10566 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 10567 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 10568 APSInt IgnoredVal(DestWidth, !DestSigned); 10569 bool Ignored; 10570 // If the value does not fit in the destination type, the behavior is 10571 // undefined, so we are not required to treat it as a constant 10572 // expression. 10573 if (FL->getValue().convertToInteger(IgnoredVal, 10574 llvm::APFloat::rmTowardZero, 10575 &Ignored) & APFloat::opInvalidOp) 10576 return ICEDiag(IK_NotICE, E->getLocStart()); 10577 return NoDiag(); 10578 } 10579 } 10580 switch (cast<CastExpr>(E)->getCastKind()) { 10581 case CK_LValueToRValue: 10582 case CK_AtomicToNonAtomic: 10583 case CK_NonAtomicToAtomic: 10584 case CK_NoOp: 10585 case CK_IntegralToBoolean: 10586 case CK_IntegralCast: 10587 return CheckICE(SubExpr, Ctx); 10588 default: 10589 return ICEDiag(IK_NotICE, E->getLocStart()); 10590 } 10591 } 10592 case Expr::BinaryConditionalOperatorClass: { 10593 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 10594 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 10595 if (CommonResult.Kind == IK_NotICE) return CommonResult; 10596 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 10597 if (FalseResult.Kind == IK_NotICE) return FalseResult; 10598 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 10599 if (FalseResult.Kind == IK_ICEIfUnevaluated && 10600 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 10601 return FalseResult; 10602 } 10603 case Expr::ConditionalOperatorClass: { 10604 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 10605 // If the condition (ignoring parens) is a __builtin_constant_p call, 10606 // then only the true side is actually considered in an integer constant 10607 // expression, and it is fully evaluated. This is an important GNU 10608 // extension. See GCC PR38377 for discussion. 10609 if (const CallExpr *CallCE 10610 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 10611 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 10612 return CheckEvalInICE(E, Ctx); 10613 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 10614 if (CondResult.Kind == IK_NotICE) 10615 return CondResult; 10616 10617 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 10618 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 10619 10620 if (TrueResult.Kind == IK_NotICE) 10621 return TrueResult; 10622 if (FalseResult.Kind == IK_NotICE) 10623 return FalseResult; 10624 if (CondResult.Kind == IK_ICEIfUnevaluated) 10625 return CondResult; 10626 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 10627 return NoDiag(); 10628 // Rare case where the diagnostics depend on which side is evaluated 10629 // Note that if we get here, CondResult is 0, and at least one of 10630 // TrueResult and FalseResult is non-zero. 10631 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 10632 return FalseResult; 10633 return TrueResult; 10634 } 10635 case Expr::CXXDefaultArgExprClass: 10636 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 10637 case Expr::CXXDefaultInitExprClass: 10638 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 10639 case Expr::ChooseExprClass: { 10640 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 10641 } 10642 } 10643 10644 llvm_unreachable("Invalid StmtClass!"); 10645 } 10646 10647 /// Evaluate an expression as a C++11 integral constant expression. 10648 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 10649 const Expr *E, 10650 llvm::APSInt *Value, 10651 SourceLocation *Loc) { 10652 if (!E->getType()->isIntegralOrEnumerationType()) { 10653 if (Loc) *Loc = E->getExprLoc(); 10654 return false; 10655 } 10656 10657 APValue Result; 10658 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 10659 return false; 10660 10661 if (!Result.isInt()) { 10662 if (Loc) *Loc = E->getExprLoc(); 10663 return false; 10664 } 10665 10666 if (Value) *Value = Result.getInt(); 10667 return true; 10668 } 10669 10670 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 10671 SourceLocation *Loc) const { 10672 if (Ctx.getLangOpts().CPlusPlus11) 10673 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 10674 10675 ICEDiag D = CheckICE(this, Ctx); 10676 if (D.Kind != IK_ICE) { 10677 if (Loc) *Loc = D.Loc; 10678 return false; 10679 } 10680 return true; 10681 } 10682 10683 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 10684 SourceLocation *Loc, bool isEvaluated) const { 10685 if (Ctx.getLangOpts().CPlusPlus11) 10686 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 10687 10688 if (!isIntegerConstantExpr(Ctx, Loc)) 10689 return false; 10690 // The only possible side-effects here are due to UB discovered in the 10691 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 10692 // required to treat the expression as an ICE, so we produce the folded 10693 // value. 10694 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects)) 10695 llvm_unreachable("ICE cannot be evaluated!"); 10696 return true; 10697 } 10698 10699 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 10700 return CheckICE(this, Ctx).Kind == IK_ICE; 10701 } 10702 10703 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 10704 SourceLocation *Loc) const { 10705 // We support this checking in C++98 mode in order to diagnose compatibility 10706 // issues. 10707 assert(Ctx.getLangOpts().CPlusPlus); 10708 10709 // Build evaluation settings. 10710 Expr::EvalStatus Status; 10711 SmallVector<PartialDiagnosticAt, 8> Diags; 10712 Status.Diag = &Diags; 10713 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 10714 10715 APValue Scratch; 10716 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 10717 10718 if (!Diags.empty()) { 10719 IsConstExpr = false; 10720 if (Loc) *Loc = Diags[0].first; 10721 } else if (!IsConstExpr) { 10722 // FIXME: This shouldn't happen. 10723 if (Loc) *Loc = getExprLoc(); 10724 } 10725 10726 return IsConstExpr; 10727 } 10728 10729 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 10730 const FunctionDecl *Callee, 10731 ArrayRef<const Expr*> Args, 10732 const Expr *This) const { 10733 Expr::EvalStatus Status; 10734 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 10735 10736 LValue ThisVal; 10737 const LValue *ThisPtr = nullptr; 10738 if (This) { 10739 #ifndef NDEBUG 10740 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 10741 assert(MD && "Don't provide `this` for non-methods."); 10742 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 10743 #endif 10744 if (EvaluateObjectArgument(Info, This, ThisVal)) 10745 ThisPtr = &ThisVal; 10746 if (Info.EvalStatus.HasSideEffects) 10747 return false; 10748 } 10749 10750 ArgVector ArgValues(Args.size()); 10751 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 10752 I != E; ++I) { 10753 if ((*I)->isValueDependent() || 10754 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 10755 // If evaluation fails, throw away the argument entirely. 10756 ArgValues[I - Args.begin()] = APValue(); 10757 if (Info.EvalStatus.HasSideEffects) 10758 return false; 10759 } 10760 10761 // Build fake call to Callee. 10762 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 10763 ArgValues.data()); 10764 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 10765 } 10766 10767 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 10768 SmallVectorImpl< 10769 PartialDiagnosticAt> &Diags) { 10770 // FIXME: It would be useful to check constexpr function templates, but at the 10771 // moment the constant expression evaluator cannot cope with the non-rigorous 10772 // ASTs which we build for dependent expressions. 10773 if (FD->isDependentContext()) 10774 return true; 10775 10776 Expr::EvalStatus Status; 10777 Status.Diag = &Diags; 10778 10779 EvalInfo Info(FD->getASTContext(), Status, 10780 EvalInfo::EM_PotentialConstantExpression); 10781 10782 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 10783 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 10784 10785 // Fabricate an arbitrary expression on the stack and pretend that it 10786 // is a temporary being used as the 'this' pointer. 10787 LValue This; 10788 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 10789 This.set(&VIE, Info.CurrentCall->Index); 10790 10791 ArrayRef<const Expr*> Args; 10792 10793 APValue Scratch; 10794 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 10795 // Evaluate the call as a constant initializer, to allow the construction 10796 // of objects of non-literal types. 10797 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 10798 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 10799 } else { 10800 SourceLocation Loc = FD->getLocation(); 10801 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 10802 Args, FD->getBody(), Info, Scratch, nullptr); 10803 } 10804 10805 return Diags.empty(); 10806 } 10807 10808 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 10809 const FunctionDecl *FD, 10810 SmallVectorImpl< 10811 PartialDiagnosticAt> &Diags) { 10812 Expr::EvalStatus Status; 10813 Status.Diag = &Diags; 10814 10815 EvalInfo Info(FD->getASTContext(), Status, 10816 EvalInfo::EM_PotentialConstantExpressionUnevaluated); 10817 10818 // Fabricate a call stack frame to give the arguments a plausible cover story. 10819 ArrayRef<const Expr*> Args; 10820 ArgVector ArgValues(0); 10821 bool Success = EvaluateArgs(Args, ArgValues, Info); 10822 (void)Success; 10823 assert(Success && 10824 "Failed to set up arguments for potential constant evaluation"); 10825 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 10826 10827 APValue ResultScratch; 10828 Evaluate(ResultScratch, Info, E); 10829 return Diags.empty(); 10830 } 10831 10832 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 10833 unsigned Type) const { 10834 if (!getType()->isPointerType()) 10835 return false; 10836 10837 Expr::EvalStatus Status; 10838 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 10839 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 10840 } 10841