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/OSLog.h" 43 #include "clang/AST/RecordLayout.h" 44 #include "clang/AST/StmtVisitor.h" 45 #include "clang/AST/TypeLoc.h" 46 #include "clang/Basic/Builtins.h" 47 #include "clang/Basic/TargetInfo.h" 48 #include "llvm/Support/SaveAndRestore.h" 49 #include "llvm/Support/raw_ostream.h" 50 #include <cstring> 51 #include <functional> 52 53 #define DEBUG_TYPE "exprconstant" 54 55 using namespace clang; 56 using llvm::APSInt; 57 using llvm::APFloat; 58 59 static bool IsGlobalLValue(APValue::LValueBase B); 60 61 namespace { 62 struct LValue; 63 struct CallStackFrame; 64 struct EvalInfo; 65 66 static QualType getType(APValue::LValueBase B) { 67 if (!B) return QualType(); 68 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 69 // FIXME: It's unclear where we're supposed to take the type from, and 70 // this actually matters for arrays of unknown bound. Eg: 71 // 72 // extern int arr[]; void f() { extern int arr[3]; }; 73 // constexpr int *p = &arr[1]; // valid? 74 // 75 // For now, we take the array bound from the most recent declaration. 76 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 77 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 78 QualType T = Redecl->getType(); 79 if (!T->isIncompleteArrayType()) 80 return T; 81 } 82 return D->getType(); 83 } 84 85 const Expr *Base = B.get<const Expr*>(); 86 87 // For a materialized temporary, the type of the temporary we materialized 88 // may not be the type of the expression. 89 if (const MaterializeTemporaryExpr *MTE = 90 dyn_cast<MaterializeTemporaryExpr>(Base)) { 91 SmallVector<const Expr *, 2> CommaLHSs; 92 SmallVector<SubobjectAdjustment, 2> Adjustments; 93 const Expr *Temp = MTE->GetTemporaryExpr(); 94 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 95 Adjustments); 96 // Keep any cv-qualifiers from the reference if we generated a temporary 97 // for it directly. Otherwise use the type after adjustment. 98 if (!Adjustments.empty()) 99 return Inner->getType(); 100 } 101 102 return Base->getType(); 103 } 104 105 /// Get an LValue path entry, which is known to not be an array index, as a 106 /// field or base class. 107 static 108 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) { 109 APValue::BaseOrMemberType Value; 110 Value.setFromOpaqueValue(E.BaseOrMember); 111 return Value; 112 } 113 114 /// Get an LValue path entry, which is known to not be an array index, as a 115 /// field declaration. 116 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 117 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer()); 118 } 119 /// Get an LValue path entry, which is known to not be an array index, as a 120 /// base class declaration. 121 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 122 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer()); 123 } 124 /// Determine whether this LValue path entry for a base class names a virtual 125 /// base class. 126 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 127 return getAsBaseOrMember(E).getInt(); 128 } 129 130 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 131 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 132 const FunctionDecl *Callee = CE->getDirectCallee(); 133 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 134 } 135 136 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 137 /// This will look through a single cast. 138 /// 139 /// Returns null if we couldn't unwrap a function with alloc_size. 140 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 141 if (!E->getType()->isPointerType()) 142 return nullptr; 143 144 E = E->IgnoreParens(); 145 // If we're doing a variable assignment from e.g. malloc(N), there will 146 // probably be a cast of some kind. In exotic cases, we might also see a 147 // top-level ExprWithCleanups. Ignore them either way. 148 if (const auto *FE = dyn_cast<FullExpr>(E)) 149 E = FE->getSubExpr()->IgnoreParens(); 150 151 if (const auto *Cast = dyn_cast<CastExpr>(E)) 152 E = Cast->getSubExpr()->IgnoreParens(); 153 154 if (const auto *CE = dyn_cast<CallExpr>(E)) 155 return getAllocSizeAttr(CE) ? CE : nullptr; 156 return nullptr; 157 } 158 159 /// Determines whether or not the given Base contains a call to a function 160 /// with the alloc_size attribute. 161 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 162 const auto *E = Base.dyn_cast<const Expr *>(); 163 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 164 } 165 166 /// The bound to claim that an array of unknown bound has. 167 /// The value in MostDerivedArraySize is undefined in this case. So, set it 168 /// to an arbitrary value that's likely to loudly break things if it's used. 169 static const uint64_t AssumedSizeForUnsizedArray = 170 std::numeric_limits<uint64_t>::max() / 2; 171 172 /// Determines if an LValue with the given LValueBase will have an unsized 173 /// array in its designator. 174 /// Find the path length and type of the most-derived subobject in the given 175 /// path, and find the size of the containing array, if any. 176 static unsigned 177 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 178 ArrayRef<APValue::LValuePathEntry> Path, 179 uint64_t &ArraySize, QualType &Type, bool &IsArray, 180 bool &FirstEntryIsUnsizedArray) { 181 // This only accepts LValueBases from APValues, and APValues don't support 182 // arrays that lack size info. 183 assert(!isBaseAnAllocSizeCall(Base) && 184 "Unsized arrays shouldn't appear here"); 185 unsigned MostDerivedLength = 0; 186 Type = getType(Base); 187 188 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 189 if (Type->isArrayType()) { 190 const ArrayType *AT = Ctx.getAsArrayType(Type); 191 Type = AT->getElementType(); 192 MostDerivedLength = I + 1; 193 IsArray = true; 194 195 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 196 ArraySize = CAT->getSize().getZExtValue(); 197 } else { 198 assert(I == 0 && "unexpected unsized array designator"); 199 FirstEntryIsUnsizedArray = true; 200 ArraySize = AssumedSizeForUnsizedArray; 201 } 202 } else if (Type->isAnyComplexType()) { 203 const ComplexType *CT = Type->castAs<ComplexType>(); 204 Type = CT->getElementType(); 205 ArraySize = 2; 206 MostDerivedLength = I + 1; 207 IsArray = true; 208 } else if (const FieldDecl *FD = getAsField(Path[I])) { 209 Type = FD->getType(); 210 ArraySize = 0; 211 MostDerivedLength = I + 1; 212 IsArray = false; 213 } else { 214 // Path[I] describes a base class. 215 ArraySize = 0; 216 IsArray = false; 217 } 218 } 219 return MostDerivedLength; 220 } 221 222 // The order of this enum is important for diagnostics. 223 enum CheckSubobjectKind { 224 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 225 CSK_This, CSK_Real, CSK_Imag 226 }; 227 228 /// A path from a glvalue to a subobject of that glvalue. 229 struct SubobjectDesignator { 230 /// True if the subobject was named in a manner not supported by C++11. Such 231 /// lvalues can still be folded, but they are not core constant expressions 232 /// and we cannot perform lvalue-to-rvalue conversions on them. 233 unsigned Invalid : 1; 234 235 /// Is this a pointer one past the end of an object? 236 unsigned IsOnePastTheEnd : 1; 237 238 /// Indicator of whether the first entry is an unsized array. 239 unsigned FirstEntryIsAnUnsizedArray : 1; 240 241 /// Indicator of whether the most-derived object is an array element. 242 unsigned MostDerivedIsArrayElement : 1; 243 244 /// The length of the path to the most-derived object of which this is a 245 /// subobject. 246 unsigned MostDerivedPathLength : 28; 247 248 /// The size of the array of which the most-derived object is an element. 249 /// This will always be 0 if the most-derived object is not an array 250 /// element. 0 is not an indicator of whether or not the most-derived object 251 /// is an array, however, because 0-length arrays are allowed. 252 /// 253 /// If the current array is an unsized array, the value of this is 254 /// undefined. 255 uint64_t MostDerivedArraySize; 256 257 /// The type of the most derived object referred to by this address. 258 QualType MostDerivedType; 259 260 typedef APValue::LValuePathEntry PathEntry; 261 262 /// The entries on the path from the glvalue to the designated subobject. 263 SmallVector<PathEntry, 8> Entries; 264 265 SubobjectDesignator() : Invalid(true) {} 266 267 explicit SubobjectDesignator(QualType T) 268 : Invalid(false), IsOnePastTheEnd(false), 269 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 270 MostDerivedPathLength(0), MostDerivedArraySize(0), 271 MostDerivedType(T) {} 272 273 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 274 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 275 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 276 MostDerivedPathLength(0), MostDerivedArraySize(0) { 277 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 278 if (!Invalid) { 279 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 280 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 281 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 282 if (V.getLValueBase()) { 283 bool IsArray = false; 284 bool FirstIsUnsizedArray = false; 285 MostDerivedPathLength = findMostDerivedSubobject( 286 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 287 MostDerivedType, IsArray, FirstIsUnsizedArray); 288 MostDerivedIsArrayElement = IsArray; 289 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 290 } 291 } 292 } 293 294 void setInvalid() { 295 Invalid = true; 296 Entries.clear(); 297 } 298 299 /// Determine whether the most derived subobject is an array without a 300 /// known bound. 301 bool isMostDerivedAnUnsizedArray() const { 302 assert(!Invalid && "Calling this makes no sense on invalid designators"); 303 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 304 } 305 306 /// Determine what the most derived array's size is. Results in an assertion 307 /// failure if the most derived array lacks a size. 308 uint64_t getMostDerivedArraySize() const { 309 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 310 return MostDerivedArraySize; 311 } 312 313 /// Determine whether this is a one-past-the-end pointer. 314 bool isOnePastTheEnd() const { 315 assert(!Invalid); 316 if (IsOnePastTheEnd) 317 return true; 318 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 319 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize) 320 return true; 321 return false; 322 } 323 324 /// Get the range of valid index adjustments in the form 325 /// {maximum value that can be subtracted from this pointer, 326 /// maximum value that can be added to this pointer} 327 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 328 if (Invalid || isMostDerivedAnUnsizedArray()) 329 return {0, 0}; 330 331 // [expr.add]p4: For the purposes of these operators, a pointer to a 332 // nonarray object behaves the same as a pointer to the first element of 333 // an array of length one with the type of the object as its element type. 334 bool IsArray = MostDerivedPathLength == Entries.size() && 335 MostDerivedIsArrayElement; 336 uint64_t ArrayIndex = 337 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; 338 uint64_t ArraySize = 339 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 340 return {ArrayIndex, ArraySize - ArrayIndex}; 341 } 342 343 /// Check that this refers to a valid subobject. 344 bool isValidSubobject() const { 345 if (Invalid) 346 return false; 347 return !isOnePastTheEnd(); 348 } 349 /// Check that this refers to a valid subobject, and if not, produce a 350 /// relevant diagnostic and set the designator as invalid. 351 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 352 353 /// Get the type of the designated object. 354 QualType getType(ASTContext &Ctx) const { 355 assert(!Invalid && "invalid designator has no subobject type"); 356 return MostDerivedPathLength == Entries.size() 357 ? MostDerivedType 358 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 359 } 360 361 /// Update this designator to refer to the first element within this array. 362 void addArrayUnchecked(const ConstantArrayType *CAT) { 363 PathEntry Entry; 364 Entry.ArrayIndex = 0; 365 Entries.push_back(Entry); 366 367 // This is a most-derived object. 368 MostDerivedType = CAT->getElementType(); 369 MostDerivedIsArrayElement = true; 370 MostDerivedArraySize = CAT->getSize().getZExtValue(); 371 MostDerivedPathLength = Entries.size(); 372 } 373 /// Update this designator to refer to the first element within the array of 374 /// elements of type T. This is an array of unknown size. 375 void addUnsizedArrayUnchecked(QualType ElemTy) { 376 PathEntry Entry; 377 Entry.ArrayIndex = 0; 378 Entries.push_back(Entry); 379 380 MostDerivedType = ElemTy; 381 MostDerivedIsArrayElement = true; 382 // The value in MostDerivedArraySize is undefined in this case. So, set it 383 // to an arbitrary value that's likely to loudly break things if it's 384 // used. 385 MostDerivedArraySize = AssumedSizeForUnsizedArray; 386 MostDerivedPathLength = Entries.size(); 387 } 388 /// Update this designator to refer to the given base or member of this 389 /// object. 390 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 391 PathEntry Entry; 392 APValue::BaseOrMemberType Value(D, Virtual); 393 Entry.BaseOrMember = Value.getOpaqueValue(); 394 Entries.push_back(Entry); 395 396 // If this isn't a base class, it's a new most-derived object. 397 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 398 MostDerivedType = FD->getType(); 399 MostDerivedIsArrayElement = false; 400 MostDerivedArraySize = 0; 401 MostDerivedPathLength = Entries.size(); 402 } 403 } 404 /// Update this designator to refer to the given complex component. 405 void addComplexUnchecked(QualType EltTy, bool Imag) { 406 PathEntry Entry; 407 Entry.ArrayIndex = Imag; 408 Entries.push_back(Entry); 409 410 // This is technically a most-derived object, though in practice this 411 // is unlikely to matter. 412 MostDerivedType = EltTy; 413 MostDerivedIsArrayElement = true; 414 MostDerivedArraySize = 2; 415 MostDerivedPathLength = Entries.size(); 416 } 417 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 418 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 419 const APSInt &N); 420 /// Add N to the address of this subobject. 421 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 422 if (Invalid || !N) return; 423 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 424 if (isMostDerivedAnUnsizedArray()) { 425 diagnoseUnsizedArrayPointerArithmetic(Info, E); 426 // Can't verify -- trust that the user is doing the right thing (or if 427 // not, trust that the caller will catch the bad behavior). 428 // FIXME: Should we reject if this overflows, at least? 429 Entries.back().ArrayIndex += TruncatedN; 430 return; 431 } 432 433 // [expr.add]p4: For the purposes of these operators, a pointer to a 434 // nonarray object behaves the same as a pointer to the first element of 435 // an array of length one with the type of the object as its element type. 436 bool IsArray = MostDerivedPathLength == Entries.size() && 437 MostDerivedIsArrayElement; 438 uint64_t ArrayIndex = 439 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; 440 uint64_t ArraySize = 441 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 442 443 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 444 // Calculate the actual index in a wide enough type, so we can include 445 // it in the note. 446 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 447 (llvm::APInt&)N += ArrayIndex; 448 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 449 diagnosePointerArithmetic(Info, E, N); 450 setInvalid(); 451 return; 452 } 453 454 ArrayIndex += TruncatedN; 455 assert(ArrayIndex <= ArraySize && 456 "bounds check succeeded for out-of-bounds index"); 457 458 if (IsArray) 459 Entries.back().ArrayIndex = ArrayIndex; 460 else 461 IsOnePastTheEnd = (ArrayIndex != 0); 462 } 463 }; 464 465 /// A stack frame in the constexpr call stack. 466 struct CallStackFrame { 467 EvalInfo &Info; 468 469 /// Parent - The caller of this stack frame. 470 CallStackFrame *Caller; 471 472 /// Callee - The function which was called. 473 const FunctionDecl *Callee; 474 475 /// This - The binding for the this pointer in this call, if any. 476 const LValue *This; 477 478 /// Arguments - Parameter bindings for this function call, indexed by 479 /// parameters' function scope indices. 480 APValue *Arguments; 481 482 // Note that we intentionally use std::map here so that references to 483 // values are stable. 484 typedef std::pair<const void *, unsigned> MapKeyTy; 485 typedef std::map<MapKeyTy, APValue> MapTy; 486 /// Temporaries - Temporary lvalues materialized within this stack frame. 487 MapTy Temporaries; 488 489 /// CallLoc - The location of the call expression for this call. 490 SourceLocation CallLoc; 491 492 /// Index - The call index of this call. 493 unsigned Index; 494 495 /// The stack of integers for tracking version numbers for temporaries. 496 SmallVector<unsigned, 2> TempVersionStack = {1}; 497 unsigned CurTempVersion = TempVersionStack.back(); 498 499 unsigned getTempVersion() const { return TempVersionStack.back(); } 500 501 void pushTempVersion() { 502 TempVersionStack.push_back(++CurTempVersion); 503 } 504 505 void popTempVersion() { 506 TempVersionStack.pop_back(); 507 } 508 509 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 510 // on the overall stack usage of deeply-recursing constexpr evaluataions. 511 // (We should cache this map rather than recomputing it repeatedly.) 512 // But let's try this and see how it goes; we can look into caching the map 513 // as a later change. 514 515 /// LambdaCaptureFields - Mapping from captured variables/this to 516 /// corresponding data members in the closure class. 517 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 518 FieldDecl *LambdaThisCaptureField; 519 520 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 521 const FunctionDecl *Callee, const LValue *This, 522 APValue *Arguments); 523 ~CallStackFrame(); 524 525 // Return the temporary for Key whose version number is Version. 526 APValue *getTemporary(const void *Key, unsigned Version) { 527 MapKeyTy KV(Key, Version); 528 auto LB = Temporaries.lower_bound(KV); 529 if (LB != Temporaries.end() && LB->first == KV) 530 return &LB->second; 531 // Pair (Key,Version) wasn't found in the map. Check that no elements 532 // in the map have 'Key' as their key. 533 assert((LB == Temporaries.end() || LB->first.first != Key) && 534 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 535 "Element with key 'Key' found in map"); 536 return nullptr; 537 } 538 539 // Return the current temporary for Key in the map. 540 APValue *getCurrentTemporary(const void *Key) { 541 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 542 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 543 return &std::prev(UB)->second; 544 return nullptr; 545 } 546 547 // Return the version number of the current temporary for Key. 548 unsigned getCurrentTemporaryVersion(const void *Key) const { 549 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 550 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 551 return std::prev(UB)->first.second; 552 return 0; 553 } 554 555 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 556 }; 557 558 /// Temporarily override 'this'. 559 class ThisOverrideRAII { 560 public: 561 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 562 : Frame(Frame), OldThis(Frame.This) { 563 if (Enable) 564 Frame.This = NewThis; 565 } 566 ~ThisOverrideRAII() { 567 Frame.This = OldThis; 568 } 569 private: 570 CallStackFrame &Frame; 571 const LValue *OldThis; 572 }; 573 574 /// A partial diagnostic which we might know in advance that we are not going 575 /// to emit. 576 class OptionalDiagnostic { 577 PartialDiagnostic *Diag; 578 579 public: 580 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr) 581 : Diag(Diag) {} 582 583 template<typename T> 584 OptionalDiagnostic &operator<<(const T &v) { 585 if (Diag) 586 *Diag << v; 587 return *this; 588 } 589 590 OptionalDiagnostic &operator<<(const APSInt &I) { 591 if (Diag) { 592 SmallVector<char, 32> Buffer; 593 I.toString(Buffer); 594 *Diag << StringRef(Buffer.data(), Buffer.size()); 595 } 596 return *this; 597 } 598 599 OptionalDiagnostic &operator<<(const APFloat &F) { 600 if (Diag) { 601 // FIXME: Force the precision of the source value down so we don't 602 // print digits which are usually useless (we don't really care here if 603 // we truncate a digit by accident in edge cases). Ideally, 604 // APFloat::toString would automatically print the shortest 605 // representation which rounds to the correct value, but it's a bit 606 // tricky to implement. 607 unsigned precision = 608 llvm::APFloat::semanticsPrecision(F.getSemantics()); 609 precision = (precision * 59 + 195) / 196; 610 SmallVector<char, 32> Buffer; 611 F.toString(Buffer, precision); 612 *Diag << StringRef(Buffer.data(), Buffer.size()); 613 } 614 return *this; 615 } 616 }; 617 618 /// A cleanup, and a flag indicating whether it is lifetime-extended. 619 class Cleanup { 620 llvm::PointerIntPair<APValue*, 1, bool> Value; 621 622 public: 623 Cleanup(APValue *Val, bool IsLifetimeExtended) 624 : Value(Val, IsLifetimeExtended) {} 625 626 bool isLifetimeExtended() const { return Value.getInt(); } 627 void endLifetime() { 628 *Value.getPointer() = APValue(); 629 } 630 }; 631 632 /// EvalInfo - This is a private struct used by the evaluator to capture 633 /// information about a subexpression as it is folded. It retains information 634 /// about the AST context, but also maintains information about the folded 635 /// expression. 636 /// 637 /// If an expression could be evaluated, it is still possible it is not a C 638 /// "integer constant expression" or constant expression. If not, this struct 639 /// captures information about how and why not. 640 /// 641 /// One bit of information passed *into* the request for constant folding 642 /// indicates whether the subexpression is "evaluated" or not according to C 643 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 644 /// evaluate the expression regardless of what the RHS is, but C only allows 645 /// certain things in certain situations. 646 struct EvalInfo { 647 ASTContext &Ctx; 648 649 /// EvalStatus - Contains information about the evaluation. 650 Expr::EvalStatus &EvalStatus; 651 652 /// CurrentCall - The top of the constexpr call stack. 653 CallStackFrame *CurrentCall; 654 655 /// CallStackDepth - The number of calls in the call stack right now. 656 unsigned CallStackDepth; 657 658 /// NextCallIndex - The next call index to assign. 659 unsigned NextCallIndex; 660 661 /// StepsLeft - The remaining number of evaluation steps we're permitted 662 /// to perform. This is essentially a limit for the number of statements 663 /// we will evaluate. 664 unsigned StepsLeft; 665 666 /// BottomFrame - The frame in which evaluation started. This must be 667 /// initialized after CurrentCall and CallStackDepth. 668 CallStackFrame BottomFrame; 669 670 /// A stack of values whose lifetimes end at the end of some surrounding 671 /// evaluation frame. 672 llvm::SmallVector<Cleanup, 16> CleanupStack; 673 674 /// EvaluatingDecl - This is the declaration whose initializer is being 675 /// evaluated, if any. 676 APValue::LValueBase EvaluatingDecl; 677 678 /// EvaluatingDeclValue - This is the value being constructed for the 679 /// declaration whose initializer is being evaluated, if any. 680 APValue *EvaluatingDeclValue; 681 682 /// EvaluatingObject - Pair of the AST node that an lvalue represents and 683 /// the call index that that lvalue was allocated in. 684 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>> 685 EvaluatingObject; 686 687 /// EvaluatingConstructors - Set of objects that are currently being 688 /// constructed. 689 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors; 690 691 struct EvaluatingConstructorRAII { 692 EvalInfo &EI; 693 EvaluatingObject Object; 694 bool DidInsert; 695 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object) 696 : EI(EI), Object(Object) { 697 DidInsert = EI.EvaluatingConstructors.insert(Object).second; 698 } 699 ~EvaluatingConstructorRAII() { 700 if (DidInsert) EI.EvaluatingConstructors.erase(Object); 701 } 702 }; 703 704 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex, 705 unsigned Version) { 706 return EvaluatingConstructors.count( 707 EvaluatingObject(Decl, {CallIndex, Version})); 708 } 709 710 /// The current array initialization index, if we're performing array 711 /// initialization. 712 uint64_t ArrayInitIndex = -1; 713 714 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 715 /// notes attached to it will also be stored, otherwise they will not be. 716 bool HasActiveDiagnostic; 717 718 /// Have we emitted a diagnostic explaining why we couldn't constant 719 /// fold (not just why it's not strictly a constant expression)? 720 bool HasFoldFailureDiagnostic; 721 722 /// Whether or not we're currently speculatively evaluating. 723 bool IsSpeculativelyEvaluating; 724 725 /// Whether or not we're in a context where the front end requires a 726 /// constant value. 727 bool InConstantContext; 728 729 enum EvaluationMode { 730 /// Evaluate as a constant expression. Stop if we find that the expression 731 /// is not a constant expression. 732 EM_ConstantExpression, 733 734 /// Evaluate as a potential constant expression. Keep going if we hit a 735 /// construct that we can't evaluate yet (because we don't yet know the 736 /// value of something) but stop if we hit something that could never be 737 /// a constant expression. 738 EM_PotentialConstantExpression, 739 740 /// Fold the expression to a constant. Stop if we hit a side-effect that 741 /// we can't model. 742 EM_ConstantFold, 743 744 /// Evaluate the expression looking for integer overflow and similar 745 /// issues. Don't worry about side-effects, and try to visit all 746 /// subexpressions. 747 EM_EvaluateForOverflow, 748 749 /// Evaluate in any way we know how. Don't worry about side-effects that 750 /// can't be modeled. 751 EM_IgnoreSideEffects, 752 753 /// Evaluate as a constant expression. Stop if we find that the expression 754 /// is not a constant expression. Some expressions can be retried in the 755 /// optimizer if we don't constant fold them here, but in an unevaluated 756 /// context we try to fold them immediately since the optimizer never 757 /// gets a chance to look at it. 758 EM_ConstantExpressionUnevaluated, 759 760 /// Evaluate as a potential constant expression. Keep going if we hit a 761 /// construct that we can't evaluate yet (because we don't yet know the 762 /// value of something) but stop if we hit something that could never be 763 /// a constant expression. Some expressions can be retried in the 764 /// optimizer if we don't constant fold them here, but in an unevaluated 765 /// context we try to fold them immediately since the optimizer never 766 /// gets a chance to look at it. 767 EM_PotentialConstantExpressionUnevaluated, 768 } EvalMode; 769 770 /// Are we checking whether the expression is a potential constant 771 /// expression? 772 bool checkingPotentialConstantExpression() const { 773 return EvalMode == EM_PotentialConstantExpression || 774 EvalMode == EM_PotentialConstantExpressionUnevaluated; 775 } 776 777 /// Are we checking an expression for overflow? 778 // FIXME: We should check for any kind of undefined or suspicious behavior 779 // in such constructs, not just overflow. 780 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; } 781 782 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 783 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 784 CallStackDepth(0), NextCallIndex(1), 785 StepsLeft(getLangOpts().ConstexprStepLimit), 786 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 787 EvaluatingDecl((const ValueDecl *)nullptr), 788 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 789 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false), 790 InConstantContext(false), EvalMode(Mode) {} 791 792 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 793 EvaluatingDecl = Base; 794 EvaluatingDeclValue = &Value; 795 EvaluatingConstructors.insert({Base, {0, 0}}); 796 } 797 798 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 799 800 bool CheckCallLimit(SourceLocation Loc) { 801 // Don't perform any constexpr calls (other than the call we're checking) 802 // when checking a potential constant expression. 803 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 804 return false; 805 if (NextCallIndex == 0) { 806 // NextCallIndex has wrapped around. 807 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 808 return false; 809 } 810 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 811 return true; 812 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 813 << getLangOpts().ConstexprCallDepth; 814 return false; 815 } 816 817 CallStackFrame *getCallFrame(unsigned CallIndex) { 818 assert(CallIndex && "no call index in getCallFrame"); 819 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 820 // be null in this loop. 821 CallStackFrame *Frame = CurrentCall; 822 while (Frame->Index > CallIndex) 823 Frame = Frame->Caller; 824 return (Frame->Index == CallIndex) ? Frame : nullptr; 825 } 826 827 bool nextStep(const Stmt *S) { 828 if (!StepsLeft) { 829 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 830 return false; 831 } 832 --StepsLeft; 833 return true; 834 } 835 836 private: 837 /// Add a diagnostic to the diagnostics list. 838 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 839 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 840 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 841 return EvalStatus.Diag->back().second; 842 } 843 844 /// Add notes containing a call stack to the current point of evaluation. 845 void addCallStack(unsigned Limit); 846 847 private: 848 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, 849 unsigned ExtraNotes, bool IsCCEDiag) { 850 851 if (EvalStatus.Diag) { 852 // If we have a prior diagnostic, it will be noting that the expression 853 // isn't a constant expression. This diagnostic is more important, 854 // unless we require this evaluation to produce a constant expression. 855 // 856 // FIXME: We might want to show both diagnostics to the user in 857 // EM_ConstantFold mode. 858 if (!EvalStatus.Diag->empty()) { 859 switch (EvalMode) { 860 case EM_ConstantFold: 861 case EM_IgnoreSideEffects: 862 case EM_EvaluateForOverflow: 863 if (!HasFoldFailureDiagnostic) 864 break; 865 // We've already failed to fold something. Keep that diagnostic. 866 LLVM_FALLTHROUGH; 867 case EM_ConstantExpression: 868 case EM_PotentialConstantExpression: 869 case EM_ConstantExpressionUnevaluated: 870 case EM_PotentialConstantExpressionUnevaluated: 871 HasActiveDiagnostic = false; 872 return OptionalDiagnostic(); 873 } 874 } 875 876 unsigned CallStackNotes = CallStackDepth - 1; 877 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 878 if (Limit) 879 CallStackNotes = std::min(CallStackNotes, Limit + 1); 880 if (checkingPotentialConstantExpression()) 881 CallStackNotes = 0; 882 883 HasActiveDiagnostic = true; 884 HasFoldFailureDiagnostic = !IsCCEDiag; 885 EvalStatus.Diag->clear(); 886 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 887 addDiag(Loc, DiagId); 888 if (!checkingPotentialConstantExpression()) 889 addCallStack(Limit); 890 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 891 } 892 HasActiveDiagnostic = false; 893 return OptionalDiagnostic(); 894 } 895 public: 896 // Diagnose that the evaluation could not be folded (FF => FoldFailure) 897 OptionalDiagnostic 898 FFDiag(SourceLocation Loc, 899 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, 900 unsigned ExtraNotes = 0) { 901 return Diag(Loc, DiagId, ExtraNotes, false); 902 } 903 904 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId 905 = diag::note_invalid_subexpr_in_const_expr, 906 unsigned ExtraNotes = 0) { 907 if (EvalStatus.Diag) 908 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false); 909 HasActiveDiagnostic = false; 910 return OptionalDiagnostic(); 911 } 912 913 /// Diagnose that the evaluation does not produce a C++11 core constant 914 /// expression. 915 /// 916 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or 917 /// EM_PotentialConstantExpression mode and we produce one of these. 918 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 919 = diag::note_invalid_subexpr_in_const_expr, 920 unsigned ExtraNotes = 0) { 921 // Don't override a previous diagnostic. Don't bother collecting 922 // diagnostics if we're evaluating for overflow. 923 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 924 HasActiveDiagnostic = false; 925 return OptionalDiagnostic(); 926 } 927 return Diag(Loc, DiagId, ExtraNotes, true); 928 } 929 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId 930 = diag::note_invalid_subexpr_in_const_expr, 931 unsigned ExtraNotes = 0) { 932 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes); 933 } 934 /// Add a note to a prior diagnostic. 935 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 936 if (!HasActiveDiagnostic) 937 return OptionalDiagnostic(); 938 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 939 } 940 941 /// Add a stack of notes to a prior diagnostic. 942 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 943 if (HasActiveDiagnostic) { 944 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 945 Diags.begin(), Diags.end()); 946 } 947 } 948 949 /// Should we continue evaluation after encountering a side-effect that we 950 /// couldn't model? 951 bool keepEvaluatingAfterSideEffect() { 952 switch (EvalMode) { 953 case EM_PotentialConstantExpression: 954 case EM_PotentialConstantExpressionUnevaluated: 955 case EM_EvaluateForOverflow: 956 case EM_IgnoreSideEffects: 957 return true; 958 959 case EM_ConstantExpression: 960 case EM_ConstantExpressionUnevaluated: 961 case EM_ConstantFold: 962 return false; 963 } 964 llvm_unreachable("Missed EvalMode case"); 965 } 966 967 /// Note that we have had a side-effect, and determine whether we should 968 /// keep evaluating. 969 bool noteSideEffect() { 970 EvalStatus.HasSideEffects = true; 971 return keepEvaluatingAfterSideEffect(); 972 } 973 974 /// Should we continue evaluation after encountering undefined behavior? 975 bool keepEvaluatingAfterUndefinedBehavior() { 976 switch (EvalMode) { 977 case EM_EvaluateForOverflow: 978 case EM_IgnoreSideEffects: 979 case EM_ConstantFold: 980 return true; 981 982 case EM_PotentialConstantExpression: 983 case EM_PotentialConstantExpressionUnevaluated: 984 case EM_ConstantExpression: 985 case EM_ConstantExpressionUnevaluated: 986 return false; 987 } 988 llvm_unreachable("Missed EvalMode case"); 989 } 990 991 /// Note that we hit something that was technically undefined behavior, but 992 /// that we can evaluate past it (such as signed overflow or floating-point 993 /// division by zero.) 994 bool noteUndefinedBehavior() { 995 EvalStatus.HasUndefinedBehavior = true; 996 return keepEvaluatingAfterUndefinedBehavior(); 997 } 998 999 /// Should we continue evaluation as much as possible after encountering a 1000 /// construct which can't be reduced to a value? 1001 bool keepEvaluatingAfterFailure() { 1002 if (!StepsLeft) 1003 return false; 1004 1005 switch (EvalMode) { 1006 case EM_PotentialConstantExpression: 1007 case EM_PotentialConstantExpressionUnevaluated: 1008 case EM_EvaluateForOverflow: 1009 return true; 1010 1011 case EM_ConstantExpression: 1012 case EM_ConstantExpressionUnevaluated: 1013 case EM_ConstantFold: 1014 case EM_IgnoreSideEffects: 1015 return false; 1016 } 1017 llvm_unreachable("Missed EvalMode case"); 1018 } 1019 1020 /// Notes that we failed to evaluate an expression that other expressions 1021 /// directly depend on, and determine if we should keep evaluating. This 1022 /// should only be called if we actually intend to keep evaluating. 1023 /// 1024 /// Call noteSideEffect() instead if we may be able to ignore the value that 1025 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1026 /// 1027 /// (Foo(), 1) // use noteSideEffect 1028 /// (Foo() || true) // use noteSideEffect 1029 /// Foo() + 1 // use noteFailure 1030 LLVM_NODISCARD bool noteFailure() { 1031 // Failure when evaluating some expression often means there is some 1032 // subexpression whose evaluation was skipped. Therefore, (because we 1033 // don't track whether we skipped an expression when unwinding after an 1034 // evaluation failure) every evaluation failure that bubbles up from a 1035 // subexpression implies that a side-effect has potentially happened. We 1036 // skip setting the HasSideEffects flag to true until we decide to 1037 // continue evaluating after that point, which happens here. 1038 bool KeepGoing = keepEvaluatingAfterFailure(); 1039 EvalStatus.HasSideEffects |= KeepGoing; 1040 return KeepGoing; 1041 } 1042 1043 class ArrayInitLoopIndex { 1044 EvalInfo &Info; 1045 uint64_t OuterIndex; 1046 1047 public: 1048 ArrayInitLoopIndex(EvalInfo &Info) 1049 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1050 Info.ArrayInitIndex = 0; 1051 } 1052 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1053 1054 operator uint64_t&() { return Info.ArrayInitIndex; } 1055 }; 1056 }; 1057 1058 /// Object used to treat all foldable expressions as constant expressions. 1059 struct FoldConstant { 1060 EvalInfo &Info; 1061 bool Enabled; 1062 bool HadNoPriorDiags; 1063 EvalInfo::EvaluationMode OldMode; 1064 1065 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1066 : Info(Info), 1067 Enabled(Enabled), 1068 HadNoPriorDiags(Info.EvalStatus.Diag && 1069 Info.EvalStatus.Diag->empty() && 1070 !Info.EvalStatus.HasSideEffects), 1071 OldMode(Info.EvalMode) { 1072 if (Enabled && 1073 (Info.EvalMode == EvalInfo::EM_ConstantExpression || 1074 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated)) 1075 Info.EvalMode = EvalInfo::EM_ConstantFold; 1076 } 1077 void keepDiagnostics() { Enabled = false; } 1078 ~FoldConstant() { 1079 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1080 !Info.EvalStatus.HasSideEffects) 1081 Info.EvalStatus.Diag->clear(); 1082 Info.EvalMode = OldMode; 1083 } 1084 }; 1085 1086 /// RAII object used to set the current evaluation mode to ignore 1087 /// side-effects. 1088 struct IgnoreSideEffectsRAII { 1089 EvalInfo &Info; 1090 EvalInfo::EvaluationMode OldMode; 1091 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1092 : Info(Info), OldMode(Info.EvalMode) { 1093 if (!Info.checkingPotentialConstantExpression()) 1094 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1095 } 1096 1097 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1098 }; 1099 1100 /// RAII object used to optionally suppress diagnostics and side-effects from 1101 /// a speculative evaluation. 1102 class SpeculativeEvaluationRAII { 1103 EvalInfo *Info = nullptr; 1104 Expr::EvalStatus OldStatus; 1105 bool OldIsSpeculativelyEvaluating; 1106 1107 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1108 Info = Other.Info; 1109 OldStatus = Other.OldStatus; 1110 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating; 1111 Other.Info = nullptr; 1112 } 1113 1114 void maybeRestoreState() { 1115 if (!Info) 1116 return; 1117 1118 Info->EvalStatus = OldStatus; 1119 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating; 1120 } 1121 1122 public: 1123 SpeculativeEvaluationRAII() = default; 1124 1125 SpeculativeEvaluationRAII( 1126 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1127 : Info(&Info), OldStatus(Info.EvalStatus), 1128 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) { 1129 Info.EvalStatus.Diag = NewDiag; 1130 Info.IsSpeculativelyEvaluating = true; 1131 } 1132 1133 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1134 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1135 moveFromAndCancel(std::move(Other)); 1136 } 1137 1138 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1139 maybeRestoreState(); 1140 moveFromAndCancel(std::move(Other)); 1141 return *this; 1142 } 1143 1144 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1145 }; 1146 1147 /// RAII object wrapping a full-expression or block scope, and handling 1148 /// the ending of the lifetime of temporaries created within it. 1149 template<bool IsFullExpression> 1150 class ScopeRAII { 1151 EvalInfo &Info; 1152 unsigned OldStackSize; 1153 public: 1154 ScopeRAII(EvalInfo &Info) 1155 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1156 // Push a new temporary version. This is needed to distinguish between 1157 // temporaries created in different iterations of a loop. 1158 Info.CurrentCall->pushTempVersion(); 1159 } 1160 ~ScopeRAII() { 1161 // Body moved to a static method to encourage the compiler to inline away 1162 // instances of this class. 1163 cleanup(Info, OldStackSize); 1164 Info.CurrentCall->popTempVersion(); 1165 } 1166 private: 1167 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 1168 unsigned NewEnd = OldStackSize; 1169 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 1170 I != N; ++I) { 1171 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 1172 // Full-expression cleanup of a lifetime-extended temporary: nothing 1173 // to do, just move this cleanup to the right place in the stack. 1174 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 1175 ++NewEnd; 1176 } else { 1177 // End the lifetime of the object. 1178 Info.CleanupStack[I].endLifetime(); 1179 } 1180 } 1181 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 1182 Info.CleanupStack.end()); 1183 } 1184 }; 1185 typedef ScopeRAII<false> BlockScopeRAII; 1186 typedef ScopeRAII<true> FullExpressionRAII; 1187 } 1188 1189 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1190 CheckSubobjectKind CSK) { 1191 if (Invalid) 1192 return false; 1193 if (isOnePastTheEnd()) { 1194 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1195 << CSK; 1196 setInvalid(); 1197 return false; 1198 } 1199 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1200 // must actually be at least one array element; even a VLA cannot have a 1201 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1202 return true; 1203 } 1204 1205 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1206 const Expr *E) { 1207 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1208 // Do not set the designator as invalid: we can represent this situation, 1209 // and correct handling of __builtin_object_size requires us to do so. 1210 } 1211 1212 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1213 const Expr *E, 1214 const APSInt &N) { 1215 // If we're complaining, we must be able to statically determine the size of 1216 // the most derived array. 1217 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1218 Info.CCEDiag(E, diag::note_constexpr_array_index) 1219 << N << /*array*/ 0 1220 << static_cast<unsigned>(getMostDerivedArraySize()); 1221 else 1222 Info.CCEDiag(E, diag::note_constexpr_array_index) 1223 << N << /*non-array*/ 1; 1224 setInvalid(); 1225 } 1226 1227 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1228 const FunctionDecl *Callee, const LValue *This, 1229 APValue *Arguments) 1230 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1231 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1232 Info.CurrentCall = this; 1233 ++Info.CallStackDepth; 1234 } 1235 1236 CallStackFrame::~CallStackFrame() { 1237 assert(Info.CurrentCall == this && "calls retired out of order"); 1238 --Info.CallStackDepth; 1239 Info.CurrentCall = Caller; 1240 } 1241 1242 APValue &CallStackFrame::createTemporary(const void *Key, 1243 bool IsLifetimeExtended) { 1244 unsigned Version = Info.CurrentCall->getTempVersion(); 1245 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1246 assert(Result.isUninit() && "temporary created multiple times"); 1247 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 1248 return Result; 1249 } 1250 1251 static void describeCall(CallStackFrame *Frame, raw_ostream &Out); 1252 1253 void EvalInfo::addCallStack(unsigned Limit) { 1254 // Determine which calls to skip, if any. 1255 unsigned ActiveCalls = CallStackDepth - 1; 1256 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 1257 if (Limit && Limit < ActiveCalls) { 1258 SkipStart = Limit / 2 + Limit % 2; 1259 SkipEnd = ActiveCalls - Limit / 2; 1260 } 1261 1262 // Walk the call stack and add the diagnostics. 1263 unsigned CallIdx = 0; 1264 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 1265 Frame = Frame->Caller, ++CallIdx) { 1266 // Skip this call? 1267 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 1268 if (CallIdx == SkipStart) { 1269 // Note that we're skipping calls. 1270 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 1271 << unsigned(ActiveCalls - Limit); 1272 } 1273 continue; 1274 } 1275 1276 // Use a different note for an inheriting constructor, because from the 1277 // user's perspective it's not really a function at all. 1278 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) { 1279 if (CD->isInheritingConstructor()) { 1280 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here) 1281 << CD->getParent(); 1282 continue; 1283 } 1284 } 1285 1286 SmallVector<char, 128> Buffer; 1287 llvm::raw_svector_ostream Out(Buffer); 1288 describeCall(Frame, Out); 1289 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 1290 } 1291 } 1292 1293 namespace { 1294 struct ComplexValue { 1295 private: 1296 bool IsInt; 1297 1298 public: 1299 APSInt IntReal, IntImag; 1300 APFloat FloatReal, FloatImag; 1301 1302 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1303 1304 void makeComplexFloat() { IsInt = false; } 1305 bool isComplexFloat() const { return !IsInt; } 1306 APFloat &getComplexFloatReal() { return FloatReal; } 1307 APFloat &getComplexFloatImag() { return FloatImag; } 1308 1309 void makeComplexInt() { IsInt = true; } 1310 bool isComplexInt() const { return IsInt; } 1311 APSInt &getComplexIntReal() { return IntReal; } 1312 APSInt &getComplexIntImag() { return IntImag; } 1313 1314 void moveInto(APValue &v) const { 1315 if (isComplexFloat()) 1316 v = APValue(FloatReal, FloatImag); 1317 else 1318 v = APValue(IntReal, IntImag); 1319 } 1320 void setFrom(const APValue &v) { 1321 assert(v.isComplexFloat() || v.isComplexInt()); 1322 if (v.isComplexFloat()) { 1323 makeComplexFloat(); 1324 FloatReal = v.getComplexFloatReal(); 1325 FloatImag = v.getComplexFloatImag(); 1326 } else { 1327 makeComplexInt(); 1328 IntReal = v.getComplexIntReal(); 1329 IntImag = v.getComplexIntImag(); 1330 } 1331 } 1332 }; 1333 1334 struct LValue { 1335 APValue::LValueBase Base; 1336 CharUnits Offset; 1337 SubobjectDesignator Designator; 1338 bool IsNullPtr : 1; 1339 bool InvalidBase : 1; 1340 1341 const APValue::LValueBase getLValueBase() const { return Base; } 1342 CharUnits &getLValueOffset() { return Offset; } 1343 const CharUnits &getLValueOffset() const { return Offset; } 1344 SubobjectDesignator &getLValueDesignator() { return Designator; } 1345 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1346 bool isNullPointer() const { return IsNullPtr;} 1347 1348 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1349 unsigned getLValueVersion() const { return Base.getVersion(); } 1350 1351 void moveInto(APValue &V) const { 1352 if (Designator.Invalid) 1353 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1354 else { 1355 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1356 V = APValue(Base, Offset, Designator.Entries, 1357 Designator.IsOnePastTheEnd, IsNullPtr); 1358 } 1359 } 1360 void setFrom(ASTContext &Ctx, const APValue &V) { 1361 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1362 Base = V.getLValueBase(); 1363 Offset = V.getLValueOffset(); 1364 InvalidBase = false; 1365 Designator = SubobjectDesignator(Ctx, V); 1366 IsNullPtr = V.isNullPointer(); 1367 } 1368 1369 void set(APValue::LValueBase B, bool BInvalid = false) { 1370 #ifndef NDEBUG 1371 // We only allow a few types of invalid bases. Enforce that here. 1372 if (BInvalid) { 1373 const auto *E = B.get<const Expr *>(); 1374 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1375 "Unexpected type of invalid base"); 1376 } 1377 #endif 1378 1379 Base = B; 1380 Offset = CharUnits::fromQuantity(0); 1381 InvalidBase = BInvalid; 1382 Designator = SubobjectDesignator(getType(B)); 1383 IsNullPtr = false; 1384 } 1385 1386 void setNull(QualType PointerTy, uint64_t TargetVal) { 1387 Base = (Expr *)nullptr; 1388 Offset = CharUnits::fromQuantity(TargetVal); 1389 InvalidBase = false; 1390 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1391 IsNullPtr = true; 1392 } 1393 1394 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1395 set(B, true); 1396 } 1397 1398 // Check that this LValue is not based on a null pointer. If it is, produce 1399 // a diagnostic and mark the designator as invalid. 1400 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1401 CheckSubobjectKind CSK) { 1402 if (Designator.Invalid) 1403 return false; 1404 if (IsNullPtr) { 1405 Info.CCEDiag(E, diag::note_constexpr_null_subobject) 1406 << CSK; 1407 Designator.setInvalid(); 1408 return false; 1409 } 1410 return true; 1411 } 1412 1413 // Check this LValue refers to an object. If not, set the designator to be 1414 // invalid and emit a diagnostic. 1415 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1416 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1417 Designator.checkSubobject(Info, E, CSK); 1418 } 1419 1420 void addDecl(EvalInfo &Info, const Expr *E, 1421 const Decl *D, bool Virtual = false) { 1422 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1423 Designator.addDeclUnchecked(D, Virtual); 1424 } 1425 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1426 if (!Designator.Entries.empty()) { 1427 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1428 Designator.setInvalid(); 1429 return; 1430 } 1431 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1432 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1433 Designator.FirstEntryIsAnUnsizedArray = true; 1434 Designator.addUnsizedArrayUnchecked(ElemTy); 1435 } 1436 } 1437 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1438 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1439 Designator.addArrayUnchecked(CAT); 1440 } 1441 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1442 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1443 Designator.addComplexUnchecked(EltTy, Imag); 1444 } 1445 void clearIsNullPointer() { 1446 IsNullPtr = false; 1447 } 1448 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1449 const APSInt &Index, CharUnits ElementSize) { 1450 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1451 // but we're not required to diagnose it and it's valid in C++.) 1452 if (!Index) 1453 return; 1454 1455 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1456 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1457 // offsets. 1458 uint64_t Offset64 = Offset.getQuantity(); 1459 uint64_t ElemSize64 = ElementSize.getQuantity(); 1460 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1461 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1462 1463 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1464 Designator.adjustIndex(Info, E, Index); 1465 clearIsNullPointer(); 1466 } 1467 void adjustOffset(CharUnits N) { 1468 Offset += N; 1469 if (N.getQuantity()) 1470 clearIsNullPointer(); 1471 } 1472 }; 1473 1474 struct MemberPtr { 1475 MemberPtr() {} 1476 explicit MemberPtr(const ValueDecl *Decl) : 1477 DeclAndIsDerivedMember(Decl, false), Path() {} 1478 1479 /// The member or (direct or indirect) field referred to by this member 1480 /// pointer, or 0 if this is a null member pointer. 1481 const ValueDecl *getDecl() const { 1482 return DeclAndIsDerivedMember.getPointer(); 1483 } 1484 /// Is this actually a member of some type derived from the relevant class? 1485 bool isDerivedMember() const { 1486 return DeclAndIsDerivedMember.getInt(); 1487 } 1488 /// Get the class which the declaration actually lives in. 1489 const CXXRecordDecl *getContainingRecord() const { 1490 return cast<CXXRecordDecl>( 1491 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1492 } 1493 1494 void moveInto(APValue &V) const { 1495 V = APValue(getDecl(), isDerivedMember(), Path); 1496 } 1497 void setFrom(const APValue &V) { 1498 assert(V.isMemberPointer()); 1499 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1500 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1501 Path.clear(); 1502 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1503 Path.insert(Path.end(), P.begin(), P.end()); 1504 } 1505 1506 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1507 /// whether the member is a member of some class derived from the class type 1508 /// of the member pointer. 1509 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1510 /// Path - The path of base/derived classes from the member declaration's 1511 /// class (exclusive) to the class type of the member pointer (inclusive). 1512 SmallVector<const CXXRecordDecl*, 4> Path; 1513 1514 /// Perform a cast towards the class of the Decl (either up or down the 1515 /// hierarchy). 1516 bool castBack(const CXXRecordDecl *Class) { 1517 assert(!Path.empty()); 1518 const CXXRecordDecl *Expected; 1519 if (Path.size() >= 2) 1520 Expected = Path[Path.size() - 2]; 1521 else 1522 Expected = getContainingRecord(); 1523 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1524 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1525 // if B does not contain the original member and is not a base or 1526 // derived class of the class containing the original member, the result 1527 // of the cast is undefined. 1528 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1529 // (D::*). We consider that to be a language defect. 1530 return false; 1531 } 1532 Path.pop_back(); 1533 return true; 1534 } 1535 /// Perform a base-to-derived member pointer cast. 1536 bool castToDerived(const CXXRecordDecl *Derived) { 1537 if (!getDecl()) 1538 return true; 1539 if (!isDerivedMember()) { 1540 Path.push_back(Derived); 1541 return true; 1542 } 1543 if (!castBack(Derived)) 1544 return false; 1545 if (Path.empty()) 1546 DeclAndIsDerivedMember.setInt(false); 1547 return true; 1548 } 1549 /// Perform a derived-to-base member pointer cast. 1550 bool castToBase(const CXXRecordDecl *Base) { 1551 if (!getDecl()) 1552 return true; 1553 if (Path.empty()) 1554 DeclAndIsDerivedMember.setInt(true); 1555 if (isDerivedMember()) { 1556 Path.push_back(Base); 1557 return true; 1558 } 1559 return castBack(Base); 1560 } 1561 }; 1562 1563 /// Compare two member pointers, which are assumed to be of the same type. 1564 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1565 if (!LHS.getDecl() || !RHS.getDecl()) 1566 return !LHS.getDecl() && !RHS.getDecl(); 1567 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1568 return false; 1569 return LHS.Path == RHS.Path; 1570 } 1571 } 1572 1573 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1574 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1575 const LValue &This, const Expr *E, 1576 bool AllowNonLiteralTypes = false); 1577 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1578 bool InvalidBaseOK = false); 1579 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1580 bool InvalidBaseOK = false); 1581 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1582 EvalInfo &Info); 1583 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1584 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1585 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1586 EvalInfo &Info); 1587 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1588 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1589 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1590 EvalInfo &Info); 1591 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1592 1593 //===----------------------------------------------------------------------===// 1594 // Misc utilities 1595 //===----------------------------------------------------------------------===// 1596 1597 /// A helper function to create a temporary and set an LValue. 1598 template <class KeyTy> 1599 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended, 1600 LValue &LV, CallStackFrame &Frame) { 1601 LV.set({Key, Frame.Info.CurrentCall->Index, 1602 Frame.Info.CurrentCall->getTempVersion()}); 1603 return Frame.createTemporary(Key, IsLifetimeExtended); 1604 } 1605 1606 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1607 /// preserving its value (by extending by up to one bit as needed). 1608 static void negateAsSigned(APSInt &Int) { 1609 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1610 Int = Int.extend(Int.getBitWidth() + 1); 1611 Int.setIsSigned(true); 1612 } 1613 Int = -Int; 1614 } 1615 1616 /// Produce a string describing the given constexpr call. 1617 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) { 1618 unsigned ArgIndex = 0; 1619 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 1620 !isa<CXXConstructorDecl>(Frame->Callee) && 1621 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 1622 1623 if (!IsMemberCall) 1624 Out << *Frame->Callee << '('; 1625 1626 if (Frame->This && IsMemberCall) { 1627 APValue Val; 1628 Frame->This->moveInto(Val); 1629 Val.printPretty(Out, Frame->Info.Ctx, 1630 Frame->This->Designator.MostDerivedType); 1631 // FIXME: Add parens around Val if needed. 1632 Out << "->" << *Frame->Callee << '('; 1633 IsMemberCall = false; 1634 } 1635 1636 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 1637 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 1638 if (ArgIndex > (unsigned)IsMemberCall) 1639 Out << ", "; 1640 1641 const ParmVarDecl *Param = *I; 1642 const APValue &Arg = Frame->Arguments[ArgIndex]; 1643 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 1644 1645 if (ArgIndex == 0 && IsMemberCall) 1646 Out << "->" << *Frame->Callee << '('; 1647 } 1648 1649 Out << ')'; 1650 } 1651 1652 /// Evaluate an expression to see if it had side-effects, and discard its 1653 /// result. 1654 /// \return \c true if the caller should keep evaluating. 1655 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1656 APValue Scratch; 1657 if (!Evaluate(Scratch, Info, E)) 1658 // We don't need the value, but we might have skipped a side effect here. 1659 return Info.noteSideEffect(); 1660 return true; 1661 } 1662 1663 /// Should this call expression be treated as a string literal? 1664 static bool IsStringLiteralCall(const CallExpr *E) { 1665 unsigned Builtin = E->getBuiltinCallee(); 1666 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1667 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1668 } 1669 1670 static bool IsGlobalLValue(APValue::LValueBase B) { 1671 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1672 // constant expression of pointer type that evaluates to... 1673 1674 // ... a null pointer value, or a prvalue core constant expression of type 1675 // std::nullptr_t. 1676 if (!B) return true; 1677 1678 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1679 // ... the address of an object with static storage duration, 1680 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1681 return VD->hasGlobalStorage(); 1682 // ... the address of a function, 1683 return isa<FunctionDecl>(D); 1684 } 1685 1686 const Expr *E = B.get<const Expr*>(); 1687 switch (E->getStmtClass()) { 1688 default: 1689 return false; 1690 case Expr::CompoundLiteralExprClass: { 1691 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1692 return CLE->isFileScope() && CLE->isLValue(); 1693 } 1694 case Expr::MaterializeTemporaryExprClass: 1695 // A materialized temporary might have been lifetime-extended to static 1696 // storage duration. 1697 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1698 // A string literal has static storage duration. 1699 case Expr::StringLiteralClass: 1700 case Expr::PredefinedExprClass: 1701 case Expr::ObjCStringLiteralClass: 1702 case Expr::ObjCEncodeExprClass: 1703 case Expr::CXXTypeidExprClass: 1704 case Expr::CXXUuidofExprClass: 1705 return true; 1706 case Expr::CallExprClass: 1707 return IsStringLiteralCall(cast<CallExpr>(E)); 1708 // For GCC compatibility, &&label has static storage duration. 1709 case Expr::AddrLabelExprClass: 1710 return true; 1711 // A Block literal expression may be used as the initialization value for 1712 // Block variables at global or local static scope. 1713 case Expr::BlockExprClass: 1714 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1715 case Expr::ImplicitValueInitExprClass: 1716 // FIXME: 1717 // We can never form an lvalue with an implicit value initialization as its 1718 // base through expression evaluation, so these only appear in one case: the 1719 // implicit variable declaration we invent when checking whether a constexpr 1720 // constructor can produce a constant expression. We must assume that such 1721 // an expression might be a global lvalue. 1722 return true; 1723 } 1724 } 1725 1726 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1727 return LVal.Base.dyn_cast<const ValueDecl*>(); 1728 } 1729 1730 static bool IsLiteralLValue(const LValue &Value) { 1731 if (Value.getLValueCallIndex()) 1732 return false; 1733 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1734 return E && !isa<MaterializeTemporaryExpr>(E); 1735 } 1736 1737 static bool IsWeakLValue(const LValue &Value) { 1738 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1739 return Decl && Decl->isWeak(); 1740 } 1741 1742 static bool isZeroSized(const LValue &Value) { 1743 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1744 if (Decl && isa<VarDecl>(Decl)) { 1745 QualType Ty = Decl->getType(); 1746 if (Ty->isArrayType()) 1747 return Ty->isIncompleteType() || 1748 Decl->getASTContext().getTypeSize(Ty) == 0; 1749 } 1750 return false; 1751 } 1752 1753 static bool HasSameBase(const LValue &A, const LValue &B) { 1754 if (!A.getLValueBase()) 1755 return !B.getLValueBase(); 1756 if (!B.getLValueBase()) 1757 return false; 1758 1759 if (A.getLValueBase().getOpaqueValue() != 1760 B.getLValueBase().getOpaqueValue()) { 1761 const Decl *ADecl = GetLValueBaseDecl(A); 1762 if (!ADecl) 1763 return false; 1764 const Decl *BDecl = GetLValueBaseDecl(B); 1765 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1766 return false; 1767 } 1768 1769 return IsGlobalLValue(A.getLValueBase()) || 1770 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1771 A.getLValueVersion() == B.getLValueVersion()); 1772 } 1773 1774 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1775 assert(Base && "no location for a null lvalue"); 1776 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1777 if (VD) 1778 Info.Note(VD->getLocation(), diag::note_declared_at); 1779 else 1780 Info.Note(Base.get<const Expr*>()->getExprLoc(), 1781 diag::note_constexpr_temporary_here); 1782 } 1783 1784 /// Check that this reference or pointer core constant expression is a valid 1785 /// value for an address or reference constant expression. Return true if we 1786 /// can fold this expression, whether or not it's a constant expression. 1787 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1788 QualType Type, const LValue &LVal, 1789 Expr::ConstExprUsage Usage) { 1790 bool IsReferenceType = Type->isReferenceType(); 1791 1792 APValue::LValueBase Base = LVal.getLValueBase(); 1793 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1794 1795 // Check that the object is a global. Note that the fake 'this' object we 1796 // manufacture when checking potential constant expressions is conservatively 1797 // assumed to be global here. 1798 if (!IsGlobalLValue(Base)) { 1799 if (Info.getLangOpts().CPlusPlus11) { 1800 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1801 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1802 << IsReferenceType << !Designator.Entries.empty() 1803 << !!VD << VD; 1804 NoteLValueLocation(Info, Base); 1805 } else { 1806 Info.FFDiag(Loc); 1807 } 1808 // Don't allow references to temporaries to escape. 1809 return false; 1810 } 1811 assert((Info.checkingPotentialConstantExpression() || 1812 LVal.getLValueCallIndex() == 0) && 1813 "have call index for global lvalue"); 1814 1815 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1816 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1817 // Check if this is a thread-local variable. 1818 if (Var->getTLSKind()) 1819 return false; 1820 1821 // A dllimport variable never acts like a constant. 1822 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 1823 return false; 1824 } 1825 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1826 // __declspec(dllimport) must be handled very carefully: 1827 // We must never initialize an expression with the thunk in C++. 1828 // Doing otherwise would allow the same id-expression to yield 1829 // different addresses for the same function in different translation 1830 // units. However, this means that we must dynamically initialize the 1831 // expression with the contents of the import address table at runtime. 1832 // 1833 // The C language has no notion of ODR; furthermore, it has no notion of 1834 // dynamic initialization. This means that we are permitted to 1835 // perform initialization with the address of the thunk. 1836 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 1837 FD->hasAttr<DLLImportAttr>()) 1838 return false; 1839 } 1840 } 1841 1842 // Allow address constant expressions to be past-the-end pointers. This is 1843 // an extension: the standard requires them to point to an object. 1844 if (!IsReferenceType) 1845 return true; 1846 1847 // A reference constant expression must refer to an object. 1848 if (!Base) { 1849 // FIXME: diagnostic 1850 Info.CCEDiag(Loc); 1851 return true; 1852 } 1853 1854 // Does this refer one past the end of some object? 1855 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1856 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1857 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1858 << !Designator.Entries.empty() << !!VD << VD; 1859 NoteLValueLocation(Info, Base); 1860 } 1861 1862 return true; 1863 } 1864 1865 /// Member pointers are constant expressions unless they point to a 1866 /// non-virtual dllimport member function. 1867 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 1868 SourceLocation Loc, 1869 QualType Type, 1870 const APValue &Value, 1871 Expr::ConstExprUsage Usage) { 1872 const ValueDecl *Member = Value.getMemberPointerDecl(); 1873 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 1874 if (!FD) 1875 return true; 1876 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 1877 !FD->hasAttr<DLLImportAttr>(); 1878 } 1879 1880 /// Check that this core constant expression is of literal type, and if not, 1881 /// produce an appropriate diagnostic. 1882 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 1883 const LValue *This = nullptr) { 1884 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 1885 return true; 1886 1887 // C++1y: A constant initializer for an object o [...] may also invoke 1888 // constexpr constructors for o and its subobjects even if those objects 1889 // are of non-literal class types. 1890 // 1891 // C++11 missed this detail for aggregates, so classes like this: 1892 // struct foo_t { union { int i; volatile int j; } u; }; 1893 // are not (obviously) initializable like so: 1894 // __attribute__((__require_constant_initialization__)) 1895 // static const foo_t x = {{0}}; 1896 // because "i" is a subobject with non-literal initialization (due to the 1897 // volatile member of the union). See: 1898 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 1899 // Therefore, we use the C++1y behavior. 1900 if (This && Info.EvaluatingDecl == This->getLValueBase()) 1901 return true; 1902 1903 // Prvalue constant expressions must be of literal types. 1904 if (Info.getLangOpts().CPlusPlus11) 1905 Info.FFDiag(E, diag::note_constexpr_nonliteral) 1906 << E->getType(); 1907 else 1908 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1909 return false; 1910 } 1911 1912 /// Check that this core constant expression value is a valid value for a 1913 /// constant expression. If not, report an appropriate diagnostic. Does not 1914 /// check that the expression is of literal type. 1915 static bool 1916 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 1917 const APValue &Value, 1918 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 1919 if (Value.isUninit()) { 1920 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 1921 << true << Type; 1922 return false; 1923 } 1924 1925 // We allow _Atomic(T) to be initialized from anything that T can be 1926 // initialized from. 1927 if (const AtomicType *AT = Type->getAs<AtomicType>()) 1928 Type = AT->getValueType(); 1929 1930 // Core issue 1454: For a literal constant expression of array or class type, 1931 // each subobject of its value shall have been initialized by a constant 1932 // expression. 1933 if (Value.isArray()) { 1934 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 1935 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 1936 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 1937 Value.getArrayInitializedElt(I), Usage)) 1938 return false; 1939 } 1940 if (!Value.hasArrayFiller()) 1941 return true; 1942 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(), 1943 Usage); 1944 } 1945 if (Value.isUnion() && Value.getUnionField()) { 1946 return CheckConstantExpression(Info, DiagLoc, 1947 Value.getUnionField()->getType(), 1948 Value.getUnionValue(), Usage); 1949 } 1950 if (Value.isStruct()) { 1951 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 1952 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 1953 unsigned BaseIndex = 0; 1954 for (const CXXBaseSpecifier &BS : CD->bases()) { 1955 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(), 1956 Value.getStructBase(BaseIndex), Usage)) 1957 return false; 1958 ++BaseIndex; 1959 } 1960 } 1961 for (const auto *I : RD->fields()) { 1962 if (I->isUnnamedBitfield()) 1963 continue; 1964 1965 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1966 Value.getStructField(I->getFieldIndex()), 1967 Usage)) 1968 return false; 1969 } 1970 } 1971 1972 if (Value.isLValue()) { 1973 LValue LVal; 1974 LVal.setFrom(Info.Ctx, Value); 1975 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage); 1976 } 1977 1978 if (Value.isMemberPointer()) 1979 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 1980 1981 // Everything else is fine. 1982 return true; 1983 } 1984 1985 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 1986 // A null base expression indicates a null pointer. These are always 1987 // evaluatable, and they are false unless the offset is zero. 1988 if (!Value.getLValueBase()) { 1989 Result = !Value.getLValueOffset().isZero(); 1990 return true; 1991 } 1992 1993 // We have a non-null base. These are generally known to be true, but if it's 1994 // a weak declaration it can be null at runtime. 1995 Result = true; 1996 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 1997 return !Decl || !Decl->isWeak(); 1998 } 1999 2000 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2001 switch (Val.getKind()) { 2002 case APValue::Uninitialized: 2003 return false; 2004 case APValue::Int: 2005 Result = Val.getInt().getBoolValue(); 2006 return true; 2007 case APValue::Float: 2008 Result = !Val.getFloat().isZero(); 2009 return true; 2010 case APValue::ComplexInt: 2011 Result = Val.getComplexIntReal().getBoolValue() || 2012 Val.getComplexIntImag().getBoolValue(); 2013 return true; 2014 case APValue::ComplexFloat: 2015 Result = !Val.getComplexFloatReal().isZero() || 2016 !Val.getComplexFloatImag().isZero(); 2017 return true; 2018 case APValue::LValue: 2019 return EvalPointerValueAsBool(Val, Result); 2020 case APValue::MemberPointer: 2021 Result = Val.getMemberPointerDecl(); 2022 return true; 2023 case APValue::Vector: 2024 case APValue::Array: 2025 case APValue::Struct: 2026 case APValue::Union: 2027 case APValue::AddrLabelDiff: 2028 return false; 2029 } 2030 2031 llvm_unreachable("unknown APValue kind"); 2032 } 2033 2034 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2035 EvalInfo &Info) { 2036 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2037 APValue Val; 2038 if (!Evaluate(Val, Info, E)) 2039 return false; 2040 return HandleConversionToBool(Val, Result); 2041 } 2042 2043 template<typename T> 2044 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2045 const T &SrcValue, QualType DestType) { 2046 Info.CCEDiag(E, diag::note_constexpr_overflow) 2047 << SrcValue << DestType; 2048 return Info.noteUndefinedBehavior(); 2049 } 2050 2051 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2052 QualType SrcType, const APFloat &Value, 2053 QualType DestType, APSInt &Result) { 2054 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2055 // Determine whether we are converting to unsigned or signed. 2056 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2057 2058 Result = APSInt(DestWidth, !DestSigned); 2059 bool ignored; 2060 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2061 & APFloat::opInvalidOp) 2062 return HandleOverflow(Info, E, Value, DestType); 2063 return true; 2064 } 2065 2066 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2067 QualType SrcType, QualType DestType, 2068 APFloat &Result) { 2069 APFloat Value = Result; 2070 bool ignored; 2071 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2072 APFloat::rmNearestTiesToEven, &ignored) 2073 & APFloat::opOverflow) 2074 return HandleOverflow(Info, E, Value, DestType); 2075 return true; 2076 } 2077 2078 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2079 QualType DestType, QualType SrcType, 2080 const APSInt &Value) { 2081 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2082 // Figure out if this is a truncate, extend or noop cast. 2083 // If the input is signed, do a sign extend, noop, or truncate. 2084 APSInt Result = Value.extOrTrunc(DestWidth); 2085 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2086 if (DestType->isBooleanType()) 2087 Result = Value.getBoolValue(); 2088 return Result; 2089 } 2090 2091 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2092 QualType SrcType, const APSInt &Value, 2093 QualType DestType, APFloat &Result) { 2094 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2095 if (Result.convertFromAPInt(Value, Value.isSigned(), 2096 APFloat::rmNearestTiesToEven) 2097 & APFloat::opOverflow) 2098 return HandleOverflow(Info, E, Value, DestType); 2099 return true; 2100 } 2101 2102 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2103 APValue &Value, const FieldDecl *FD) { 2104 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2105 2106 if (!Value.isInt()) { 2107 // Trying to store a pointer-cast-to-integer into a bitfield. 2108 // FIXME: In this case, we should provide the diagnostic for casting 2109 // a pointer to an integer. 2110 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2111 Info.FFDiag(E); 2112 return false; 2113 } 2114 2115 APSInt &Int = Value.getInt(); 2116 unsigned OldBitWidth = Int.getBitWidth(); 2117 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2118 if (NewBitWidth < OldBitWidth) 2119 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2120 return true; 2121 } 2122 2123 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2124 llvm::APInt &Res) { 2125 APValue SVal; 2126 if (!Evaluate(SVal, Info, E)) 2127 return false; 2128 if (SVal.isInt()) { 2129 Res = SVal.getInt(); 2130 return true; 2131 } 2132 if (SVal.isFloat()) { 2133 Res = SVal.getFloat().bitcastToAPInt(); 2134 return true; 2135 } 2136 if (SVal.isVector()) { 2137 QualType VecTy = E->getType(); 2138 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2139 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2140 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2141 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2142 Res = llvm::APInt::getNullValue(VecSize); 2143 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2144 APValue &Elt = SVal.getVectorElt(i); 2145 llvm::APInt EltAsInt; 2146 if (Elt.isInt()) { 2147 EltAsInt = Elt.getInt(); 2148 } else if (Elt.isFloat()) { 2149 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2150 } else { 2151 // Don't try to handle vectors of anything other than int or float 2152 // (not sure if it's possible to hit this case). 2153 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2154 return false; 2155 } 2156 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2157 if (BigEndian) 2158 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2159 else 2160 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2161 } 2162 return true; 2163 } 2164 // Give up if the input isn't an int, float, or vector. For example, we 2165 // reject "(v4i16)(intptr_t)&a". 2166 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2167 return false; 2168 } 2169 2170 /// Perform the given integer operation, which is known to need at most BitWidth 2171 /// bits, and check for overflow in the original type (if that type was not an 2172 /// unsigned type). 2173 template<typename Operation> 2174 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2175 const APSInt &LHS, const APSInt &RHS, 2176 unsigned BitWidth, Operation Op, 2177 APSInt &Result) { 2178 if (LHS.isUnsigned()) { 2179 Result = Op(LHS, RHS); 2180 return true; 2181 } 2182 2183 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2184 Result = Value.trunc(LHS.getBitWidth()); 2185 if (Result.extend(BitWidth) != Value) { 2186 if (Info.checkingForOverflow()) 2187 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2188 diag::warn_integer_constant_overflow) 2189 << Result.toString(10) << E->getType(); 2190 else 2191 return HandleOverflow(Info, E, Value, E->getType()); 2192 } 2193 return true; 2194 } 2195 2196 /// Perform the given binary integer operation. 2197 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2198 BinaryOperatorKind Opcode, APSInt RHS, 2199 APSInt &Result) { 2200 switch (Opcode) { 2201 default: 2202 Info.FFDiag(E); 2203 return false; 2204 case BO_Mul: 2205 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2206 std::multiplies<APSInt>(), Result); 2207 case BO_Add: 2208 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2209 std::plus<APSInt>(), Result); 2210 case BO_Sub: 2211 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2212 std::minus<APSInt>(), Result); 2213 case BO_And: Result = LHS & RHS; return true; 2214 case BO_Xor: Result = LHS ^ RHS; return true; 2215 case BO_Or: Result = LHS | RHS; return true; 2216 case BO_Div: 2217 case BO_Rem: 2218 if (RHS == 0) { 2219 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2220 return false; 2221 } 2222 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2223 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2224 // this operation and gives the two's complement result. 2225 if (RHS.isNegative() && RHS.isAllOnesValue() && 2226 LHS.isSigned() && LHS.isMinSignedValue()) 2227 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2228 E->getType()); 2229 return true; 2230 case BO_Shl: { 2231 if (Info.getLangOpts().OpenCL) 2232 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2233 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2234 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2235 RHS.isUnsigned()); 2236 else if (RHS.isSigned() && RHS.isNegative()) { 2237 // During constant-folding, a negative shift is an opposite shift. Such 2238 // a shift is not a constant expression. 2239 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2240 RHS = -RHS; 2241 goto shift_right; 2242 } 2243 shift_left: 2244 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2245 // the shifted type. 2246 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2247 if (SA != RHS) { 2248 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2249 << RHS << E->getType() << LHS.getBitWidth(); 2250 } else if (LHS.isSigned()) { 2251 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2252 // operand, and must not overflow the corresponding unsigned type. 2253 if (LHS.isNegative()) 2254 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2255 else if (LHS.countLeadingZeros() < SA) 2256 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2257 } 2258 Result = LHS << SA; 2259 return true; 2260 } 2261 case BO_Shr: { 2262 if (Info.getLangOpts().OpenCL) 2263 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2264 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2265 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2266 RHS.isUnsigned()); 2267 else if (RHS.isSigned() && RHS.isNegative()) { 2268 // During constant-folding, a negative shift is an opposite shift. Such a 2269 // shift is not a constant expression. 2270 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2271 RHS = -RHS; 2272 goto shift_left; 2273 } 2274 shift_right: 2275 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2276 // shifted type. 2277 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2278 if (SA != RHS) 2279 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2280 << RHS << E->getType() << LHS.getBitWidth(); 2281 Result = LHS >> SA; 2282 return true; 2283 } 2284 2285 case BO_LT: Result = LHS < RHS; return true; 2286 case BO_GT: Result = LHS > RHS; return true; 2287 case BO_LE: Result = LHS <= RHS; return true; 2288 case BO_GE: Result = LHS >= RHS; return true; 2289 case BO_EQ: Result = LHS == RHS; return true; 2290 case BO_NE: Result = LHS != RHS; return true; 2291 case BO_Cmp: 2292 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2293 } 2294 } 2295 2296 /// Perform the given binary floating-point operation, in-place, on LHS. 2297 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2298 APFloat &LHS, BinaryOperatorKind Opcode, 2299 const APFloat &RHS) { 2300 switch (Opcode) { 2301 default: 2302 Info.FFDiag(E); 2303 return false; 2304 case BO_Mul: 2305 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2306 break; 2307 case BO_Add: 2308 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2309 break; 2310 case BO_Sub: 2311 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2312 break; 2313 case BO_Div: 2314 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2315 break; 2316 } 2317 2318 if (LHS.isInfinity() || LHS.isNaN()) { 2319 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2320 return Info.noteUndefinedBehavior(); 2321 } 2322 return true; 2323 } 2324 2325 /// Cast an lvalue referring to a base subobject to a derived class, by 2326 /// truncating the lvalue's path to the given length. 2327 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2328 const RecordDecl *TruncatedType, 2329 unsigned TruncatedElements) { 2330 SubobjectDesignator &D = Result.Designator; 2331 2332 // Check we actually point to a derived class object. 2333 if (TruncatedElements == D.Entries.size()) 2334 return true; 2335 assert(TruncatedElements >= D.MostDerivedPathLength && 2336 "not casting to a derived class"); 2337 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2338 return false; 2339 2340 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2341 const RecordDecl *RD = TruncatedType; 2342 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2343 if (RD->isInvalidDecl()) return false; 2344 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2345 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2346 if (isVirtualBaseClass(D.Entries[I])) 2347 Result.Offset -= Layout.getVBaseClassOffset(Base); 2348 else 2349 Result.Offset -= Layout.getBaseClassOffset(Base); 2350 RD = Base; 2351 } 2352 D.Entries.resize(TruncatedElements); 2353 return true; 2354 } 2355 2356 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2357 const CXXRecordDecl *Derived, 2358 const CXXRecordDecl *Base, 2359 const ASTRecordLayout *RL = nullptr) { 2360 if (!RL) { 2361 if (Derived->isInvalidDecl()) return false; 2362 RL = &Info.Ctx.getASTRecordLayout(Derived); 2363 } 2364 2365 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2366 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2367 return true; 2368 } 2369 2370 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2371 const CXXRecordDecl *DerivedDecl, 2372 const CXXBaseSpecifier *Base) { 2373 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2374 2375 if (!Base->isVirtual()) 2376 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2377 2378 SubobjectDesignator &D = Obj.Designator; 2379 if (D.Invalid) 2380 return false; 2381 2382 // Extract most-derived object and corresponding type. 2383 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2384 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2385 return false; 2386 2387 // Find the virtual base class. 2388 if (DerivedDecl->isInvalidDecl()) return false; 2389 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2390 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2391 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2392 return true; 2393 } 2394 2395 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2396 QualType Type, LValue &Result) { 2397 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2398 PathE = E->path_end(); 2399 PathI != PathE; ++PathI) { 2400 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2401 *PathI)) 2402 return false; 2403 Type = (*PathI)->getType(); 2404 } 2405 return true; 2406 } 2407 2408 /// Update LVal to refer to the given field, which must be a member of the type 2409 /// currently described by LVal. 2410 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2411 const FieldDecl *FD, 2412 const ASTRecordLayout *RL = nullptr) { 2413 if (!RL) { 2414 if (FD->getParent()->isInvalidDecl()) return false; 2415 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2416 } 2417 2418 unsigned I = FD->getFieldIndex(); 2419 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2420 LVal.addDecl(Info, E, FD); 2421 return true; 2422 } 2423 2424 /// Update LVal to refer to the given indirect field. 2425 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2426 LValue &LVal, 2427 const IndirectFieldDecl *IFD) { 2428 for (const auto *C : IFD->chain()) 2429 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2430 return false; 2431 return true; 2432 } 2433 2434 /// Get the size of the given type in char units. 2435 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2436 QualType Type, CharUnits &Size) { 2437 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2438 // extension. 2439 if (Type->isVoidType() || Type->isFunctionType()) { 2440 Size = CharUnits::One(); 2441 return true; 2442 } 2443 2444 if (Type->isDependentType()) { 2445 Info.FFDiag(Loc); 2446 return false; 2447 } 2448 2449 if (!Type->isConstantSizeType()) { 2450 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2451 // FIXME: Better diagnostic. 2452 Info.FFDiag(Loc); 2453 return false; 2454 } 2455 2456 Size = Info.Ctx.getTypeSizeInChars(Type); 2457 return true; 2458 } 2459 2460 /// Update a pointer value to model pointer arithmetic. 2461 /// \param Info - Information about the ongoing evaluation. 2462 /// \param E - The expression being evaluated, for diagnostic purposes. 2463 /// \param LVal - The pointer value to be updated. 2464 /// \param EltTy - The pointee type represented by LVal. 2465 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2466 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2467 LValue &LVal, QualType EltTy, 2468 APSInt Adjustment) { 2469 CharUnits SizeOfPointee; 2470 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2471 return false; 2472 2473 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2474 return true; 2475 } 2476 2477 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2478 LValue &LVal, QualType EltTy, 2479 int64_t Adjustment) { 2480 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2481 APSInt::get(Adjustment)); 2482 } 2483 2484 /// Update an lvalue to refer to a component of a complex number. 2485 /// \param Info - Information about the ongoing evaluation. 2486 /// \param LVal - The lvalue to be updated. 2487 /// \param EltTy - The complex number's component type. 2488 /// \param Imag - False for the real component, true for the imaginary. 2489 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2490 LValue &LVal, QualType EltTy, 2491 bool Imag) { 2492 if (Imag) { 2493 CharUnits SizeOfComponent; 2494 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2495 return false; 2496 LVal.Offset += SizeOfComponent; 2497 } 2498 LVal.addComplex(Info, E, EltTy, Imag); 2499 return true; 2500 } 2501 2502 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 2503 QualType Type, const LValue &LVal, 2504 APValue &RVal); 2505 2506 /// Try to evaluate the initializer for a variable declaration. 2507 /// 2508 /// \param Info Information about the ongoing evaluation. 2509 /// \param E An expression to be used when printing diagnostics. 2510 /// \param VD The variable whose initializer should be obtained. 2511 /// \param Frame The frame in which the variable was created. Must be null 2512 /// if this variable is not local to the evaluation. 2513 /// \param Result Filled in with a pointer to the value of the variable. 2514 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2515 const VarDecl *VD, CallStackFrame *Frame, 2516 APValue *&Result, const LValue *LVal) { 2517 2518 // If this is a parameter to an active constexpr function call, perform 2519 // argument substitution. 2520 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2521 // Assume arguments of a potential constant expression are unknown 2522 // constant expressions. 2523 if (Info.checkingPotentialConstantExpression()) 2524 return false; 2525 if (!Frame || !Frame->Arguments) { 2526 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2527 return false; 2528 } 2529 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2530 return true; 2531 } 2532 2533 // If this is a local variable, dig out its value. 2534 if (Frame) { 2535 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 2536 : Frame->getCurrentTemporary(VD); 2537 if (!Result) { 2538 // Assume variables referenced within a lambda's call operator that were 2539 // not declared within the call operator are captures and during checking 2540 // of a potential constant expression, assume they are unknown constant 2541 // expressions. 2542 assert(isLambdaCallOperator(Frame->Callee) && 2543 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2544 "missing value for local variable"); 2545 if (Info.checkingPotentialConstantExpression()) 2546 return false; 2547 // FIXME: implement capture evaluation during constant expr evaluation. 2548 Info.FFDiag(E->getBeginLoc(), 2549 diag::note_unimplemented_constexpr_lambda_feature_ast) 2550 << "captures not currently allowed"; 2551 return false; 2552 } 2553 return true; 2554 } 2555 2556 // Dig out the initializer, and use the declaration which it's attached to. 2557 const Expr *Init = VD->getAnyInitializer(VD); 2558 if (!Init || Init->isValueDependent()) { 2559 // If we're checking a potential constant expression, the variable could be 2560 // initialized later. 2561 if (!Info.checkingPotentialConstantExpression()) 2562 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2563 return false; 2564 } 2565 2566 // If we're currently evaluating the initializer of this declaration, use that 2567 // in-flight value. 2568 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2569 Result = Info.EvaluatingDeclValue; 2570 return true; 2571 } 2572 2573 // Never evaluate the initializer of a weak variable. We can't be sure that 2574 // this is the definition which will be used. 2575 if (VD->isWeak()) { 2576 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2577 return false; 2578 } 2579 2580 // Check that we can fold the initializer. In C++, we will have already done 2581 // this in the cases where it matters for conformance. 2582 SmallVector<PartialDiagnosticAt, 8> Notes; 2583 if (!VD->evaluateValue(Notes)) { 2584 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2585 Notes.size() + 1) << VD; 2586 Info.Note(VD->getLocation(), diag::note_declared_at); 2587 Info.addNotes(Notes); 2588 return false; 2589 } else if (!VD->checkInitIsICE()) { 2590 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2591 Notes.size() + 1) << VD; 2592 Info.Note(VD->getLocation(), diag::note_declared_at); 2593 Info.addNotes(Notes); 2594 } 2595 2596 Result = VD->getEvaluatedValue(); 2597 return true; 2598 } 2599 2600 static bool IsConstNonVolatile(QualType T) { 2601 Qualifiers Quals = T.getQualifiers(); 2602 return Quals.hasConst() && !Quals.hasVolatile(); 2603 } 2604 2605 /// Get the base index of the given base class within an APValue representing 2606 /// the given derived class. 2607 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2608 const CXXRecordDecl *Base) { 2609 Base = Base->getCanonicalDecl(); 2610 unsigned Index = 0; 2611 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2612 E = Derived->bases_end(); I != E; ++I, ++Index) { 2613 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2614 return Index; 2615 } 2616 2617 llvm_unreachable("base class missing from derived class's bases list"); 2618 } 2619 2620 /// Extract the value of a character from a string literal. 2621 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2622 uint64_t Index) { 2623 // FIXME: Support MakeStringConstant 2624 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2625 std::string Str; 2626 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2627 assert(Index <= Str.size() && "Index too large"); 2628 return APSInt::getUnsigned(Str.c_str()[Index]); 2629 } 2630 2631 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2632 Lit = PE->getFunctionName(); 2633 const StringLiteral *S = cast<StringLiteral>(Lit); 2634 const ConstantArrayType *CAT = 2635 Info.Ctx.getAsConstantArrayType(S->getType()); 2636 assert(CAT && "string literal isn't an array"); 2637 QualType CharType = CAT->getElementType(); 2638 assert(CharType->isIntegerType() && "unexpected character type"); 2639 2640 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2641 CharType->isUnsignedIntegerType()); 2642 if (Index < S->getLength()) 2643 Value = S->getCodeUnit(Index); 2644 return Value; 2645 } 2646 2647 // Expand a string literal into an array of characters. 2648 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit, 2649 APValue &Result) { 2650 const StringLiteral *S = cast<StringLiteral>(Lit); 2651 const ConstantArrayType *CAT = 2652 Info.Ctx.getAsConstantArrayType(S->getType()); 2653 assert(CAT && "string literal isn't an array"); 2654 QualType CharType = CAT->getElementType(); 2655 assert(CharType->isIntegerType() && "unexpected character type"); 2656 2657 unsigned Elts = CAT->getSize().getZExtValue(); 2658 Result = APValue(APValue::UninitArray(), 2659 std::min(S->getLength(), Elts), Elts); 2660 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2661 CharType->isUnsignedIntegerType()); 2662 if (Result.hasArrayFiller()) 2663 Result.getArrayFiller() = APValue(Value); 2664 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2665 Value = S->getCodeUnit(I); 2666 Result.getArrayInitializedElt(I) = APValue(Value); 2667 } 2668 } 2669 2670 // Expand an array so that it has more than Index filled elements. 2671 static void expandArray(APValue &Array, unsigned Index) { 2672 unsigned Size = Array.getArraySize(); 2673 assert(Index < Size); 2674 2675 // Always at least double the number of elements for which we store a value. 2676 unsigned OldElts = Array.getArrayInitializedElts(); 2677 unsigned NewElts = std::max(Index+1, OldElts * 2); 2678 NewElts = std::min(Size, std::max(NewElts, 8u)); 2679 2680 // Copy the data across. 2681 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2682 for (unsigned I = 0; I != OldElts; ++I) 2683 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2684 for (unsigned I = OldElts; I != NewElts; ++I) 2685 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2686 if (NewValue.hasArrayFiller()) 2687 NewValue.getArrayFiller() = Array.getArrayFiller(); 2688 Array.swap(NewValue); 2689 } 2690 2691 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2692 /// conversion. If it's of class type, we may assume that the copy operation 2693 /// is trivial. Note that this is never true for a union type with fields 2694 /// (because the copy always "reads" the active member) and always true for 2695 /// a non-class type. 2696 static bool isReadByLvalueToRvalueConversion(QualType T) { 2697 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2698 if (!RD || (RD->isUnion() && !RD->field_empty())) 2699 return true; 2700 if (RD->isEmpty()) 2701 return false; 2702 2703 for (auto *Field : RD->fields()) 2704 if (isReadByLvalueToRvalueConversion(Field->getType())) 2705 return true; 2706 2707 for (auto &BaseSpec : RD->bases()) 2708 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2709 return true; 2710 2711 return false; 2712 } 2713 2714 /// Diagnose an attempt to read from any unreadable field within the specified 2715 /// type, which might be a class type. 2716 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2717 QualType T) { 2718 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2719 if (!RD) 2720 return false; 2721 2722 if (!RD->hasMutableFields()) 2723 return false; 2724 2725 for (auto *Field : RD->fields()) { 2726 // If we're actually going to read this field in some way, then it can't 2727 // be mutable. If we're in a union, then assigning to a mutable field 2728 // (even an empty one) can change the active member, so that's not OK. 2729 // FIXME: Add core issue number for the union case. 2730 if (Field->isMutable() && 2731 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2732 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2733 Info.Note(Field->getLocation(), diag::note_declared_at); 2734 return true; 2735 } 2736 2737 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2738 return true; 2739 } 2740 2741 for (auto &BaseSpec : RD->bases()) 2742 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2743 return true; 2744 2745 // All mutable fields were empty, and thus not actually read. 2746 return false; 2747 } 2748 2749 /// Kinds of access we can perform on an object, for diagnostics. 2750 enum AccessKinds { 2751 AK_Read, 2752 AK_Assign, 2753 AK_Increment, 2754 AK_Decrement 2755 }; 2756 2757 namespace { 2758 /// A handle to a complete object (an object that is not a subobject of 2759 /// another object). 2760 struct CompleteObject { 2761 /// The value of the complete object. 2762 APValue *Value; 2763 /// The type of the complete object. 2764 QualType Type; 2765 bool LifetimeStartedInEvaluation; 2766 2767 CompleteObject() : Value(nullptr) {} 2768 CompleteObject(APValue *Value, QualType Type, 2769 bool LifetimeStartedInEvaluation) 2770 : Value(Value), Type(Type), 2771 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) { 2772 assert(Value && "missing value for complete object"); 2773 } 2774 2775 explicit operator bool() const { return Value; } 2776 }; 2777 } // end anonymous namespace 2778 2779 /// Find the designated sub-object of an rvalue. 2780 template<typename SubobjectHandler> 2781 typename SubobjectHandler::result_type 2782 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2783 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2784 if (Sub.Invalid) 2785 // A diagnostic will have already been produced. 2786 return handler.failed(); 2787 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 2788 if (Info.getLangOpts().CPlusPlus11) 2789 Info.FFDiag(E, Sub.isOnePastTheEnd() 2790 ? diag::note_constexpr_access_past_end 2791 : diag::note_constexpr_access_unsized_array) 2792 << handler.AccessKind; 2793 else 2794 Info.FFDiag(E); 2795 return handler.failed(); 2796 } 2797 2798 APValue *O = Obj.Value; 2799 QualType ObjType = Obj.Type; 2800 const FieldDecl *LastField = nullptr; 2801 const bool MayReadMutableMembers = 2802 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14; 2803 2804 // Walk the designator's path to find the subobject. 2805 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 2806 if (O->isUninit()) { 2807 if (!Info.checkingPotentialConstantExpression()) 2808 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind; 2809 return handler.failed(); 2810 } 2811 2812 if (I == N) { 2813 // If we are reading an object of class type, there may still be more 2814 // things we need to check: if there are any mutable subobjects, we 2815 // cannot perform this read. (This only happens when performing a trivial 2816 // copy or assignment.) 2817 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 2818 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType)) 2819 return handler.failed(); 2820 2821 if (!handler.found(*O, ObjType)) 2822 return false; 2823 2824 // If we modified a bit-field, truncate it to the right width. 2825 if (handler.AccessKind != AK_Read && 2826 LastField && LastField->isBitField() && 2827 !truncateBitfieldValue(Info, E, *O, LastField)) 2828 return false; 2829 2830 return true; 2831 } 2832 2833 LastField = nullptr; 2834 if (ObjType->isArrayType()) { 2835 // Next subobject is an array element. 2836 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 2837 assert(CAT && "vla in literal type?"); 2838 uint64_t Index = Sub.Entries[I].ArrayIndex; 2839 if (CAT->getSize().ule(Index)) { 2840 // Note, it should not be possible to form a pointer with a valid 2841 // designator which points more than one past the end of the array. 2842 if (Info.getLangOpts().CPlusPlus11) 2843 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2844 << handler.AccessKind; 2845 else 2846 Info.FFDiag(E); 2847 return handler.failed(); 2848 } 2849 2850 ObjType = CAT->getElementType(); 2851 2852 // An array object is represented as either an Array APValue or as an 2853 // LValue which refers to a string literal. 2854 if (O->isLValue()) { 2855 assert(I == N - 1 && "extracting subobject of character?"); 2856 assert(!O->hasLValuePath() || O->getLValuePath().empty()); 2857 if (handler.AccessKind != AK_Read) 2858 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(), 2859 *O); 2860 else 2861 return handler.foundString(*O, ObjType, Index); 2862 } 2863 2864 if (O->getArrayInitializedElts() > Index) 2865 O = &O->getArrayInitializedElt(Index); 2866 else if (handler.AccessKind != AK_Read) { 2867 expandArray(*O, Index); 2868 O = &O->getArrayInitializedElt(Index); 2869 } else 2870 O = &O->getArrayFiller(); 2871 } else if (ObjType->isAnyComplexType()) { 2872 // Next subobject is a complex number. 2873 uint64_t Index = Sub.Entries[I].ArrayIndex; 2874 if (Index > 1) { 2875 if (Info.getLangOpts().CPlusPlus11) 2876 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2877 << handler.AccessKind; 2878 else 2879 Info.FFDiag(E); 2880 return handler.failed(); 2881 } 2882 2883 bool WasConstQualified = ObjType.isConstQualified(); 2884 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2885 if (WasConstQualified) 2886 ObjType.addConst(); 2887 2888 assert(I == N - 1 && "extracting subobject of scalar?"); 2889 if (O->isComplexInt()) { 2890 return handler.found(Index ? O->getComplexIntImag() 2891 : O->getComplexIntReal(), ObjType); 2892 } else { 2893 assert(O->isComplexFloat()); 2894 return handler.found(Index ? O->getComplexFloatImag() 2895 : O->getComplexFloatReal(), ObjType); 2896 } 2897 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 2898 // In C++14 onwards, it is permitted to read a mutable member whose 2899 // lifetime began within the evaluation. 2900 // FIXME: Should we also allow this in C++11? 2901 if (Field->isMutable() && handler.AccessKind == AK_Read && 2902 !MayReadMutableMembers) { 2903 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 2904 << Field; 2905 Info.Note(Field->getLocation(), diag::note_declared_at); 2906 return handler.failed(); 2907 } 2908 2909 // Next subobject is a class, struct or union field. 2910 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 2911 if (RD->isUnion()) { 2912 const FieldDecl *UnionField = O->getUnionField(); 2913 if (!UnionField || 2914 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 2915 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 2916 << handler.AccessKind << Field << !UnionField << UnionField; 2917 return handler.failed(); 2918 } 2919 O = &O->getUnionValue(); 2920 } else 2921 O = &O->getStructField(Field->getFieldIndex()); 2922 2923 bool WasConstQualified = ObjType.isConstQualified(); 2924 ObjType = Field->getType(); 2925 if (WasConstQualified && !Field->isMutable()) 2926 ObjType.addConst(); 2927 2928 if (ObjType.isVolatileQualified()) { 2929 if (Info.getLangOpts().CPlusPlus) { 2930 // FIXME: Include a description of the path to the volatile subobject. 2931 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2932 << handler.AccessKind << 2 << Field; 2933 Info.Note(Field->getLocation(), diag::note_declared_at); 2934 } else { 2935 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2936 } 2937 return handler.failed(); 2938 } 2939 2940 LastField = Field; 2941 } else { 2942 // Next subobject is a base class. 2943 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 2944 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 2945 O = &O->getStructBase(getBaseIndex(Derived, Base)); 2946 2947 bool WasConstQualified = ObjType.isConstQualified(); 2948 ObjType = Info.Ctx.getRecordType(Base); 2949 if (WasConstQualified) 2950 ObjType.addConst(); 2951 } 2952 } 2953 } 2954 2955 namespace { 2956 struct ExtractSubobjectHandler { 2957 EvalInfo &Info; 2958 APValue &Result; 2959 2960 static const AccessKinds AccessKind = AK_Read; 2961 2962 typedef bool result_type; 2963 bool failed() { return false; } 2964 bool found(APValue &Subobj, QualType SubobjType) { 2965 Result = Subobj; 2966 return true; 2967 } 2968 bool found(APSInt &Value, QualType SubobjType) { 2969 Result = APValue(Value); 2970 return true; 2971 } 2972 bool found(APFloat &Value, QualType SubobjType) { 2973 Result = APValue(Value); 2974 return true; 2975 } 2976 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2977 Result = APValue(extractStringLiteralCharacter( 2978 Info, Subobj.getLValueBase().get<const Expr *>(), Character)); 2979 return true; 2980 } 2981 }; 2982 } // end anonymous namespace 2983 2984 const AccessKinds ExtractSubobjectHandler::AccessKind; 2985 2986 /// Extract the designated sub-object of an rvalue. 2987 static bool extractSubobject(EvalInfo &Info, const Expr *E, 2988 const CompleteObject &Obj, 2989 const SubobjectDesignator &Sub, 2990 APValue &Result) { 2991 ExtractSubobjectHandler Handler = { Info, Result }; 2992 return findSubobject(Info, E, Obj, Sub, Handler); 2993 } 2994 2995 namespace { 2996 struct ModifySubobjectHandler { 2997 EvalInfo &Info; 2998 APValue &NewVal; 2999 const Expr *E; 3000 3001 typedef bool result_type; 3002 static const AccessKinds AccessKind = AK_Assign; 3003 3004 bool checkConst(QualType QT) { 3005 // Assigning to a const object has undefined behavior. 3006 if (QT.isConstQualified()) { 3007 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3008 return false; 3009 } 3010 return true; 3011 } 3012 3013 bool failed() { return false; } 3014 bool found(APValue &Subobj, QualType SubobjType) { 3015 if (!checkConst(SubobjType)) 3016 return false; 3017 // We've been given ownership of NewVal, so just swap it in. 3018 Subobj.swap(NewVal); 3019 return true; 3020 } 3021 bool found(APSInt &Value, QualType SubobjType) { 3022 if (!checkConst(SubobjType)) 3023 return false; 3024 if (!NewVal.isInt()) { 3025 // Maybe trying to write a cast pointer value into a complex? 3026 Info.FFDiag(E); 3027 return false; 3028 } 3029 Value = NewVal.getInt(); 3030 return true; 3031 } 3032 bool found(APFloat &Value, QualType SubobjType) { 3033 if (!checkConst(SubobjType)) 3034 return false; 3035 Value = NewVal.getFloat(); 3036 return true; 3037 } 3038 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3039 llvm_unreachable("shouldn't encounter string elements with ExpandArrays"); 3040 } 3041 }; 3042 } // end anonymous namespace 3043 3044 const AccessKinds ModifySubobjectHandler::AccessKind; 3045 3046 /// Update the designated sub-object of an rvalue to the given value. 3047 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3048 const CompleteObject &Obj, 3049 const SubobjectDesignator &Sub, 3050 APValue &NewVal) { 3051 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3052 return findSubobject(Info, E, Obj, Sub, Handler); 3053 } 3054 3055 /// Find the position where two subobject designators diverge, or equivalently 3056 /// the length of the common initial subsequence. 3057 static unsigned FindDesignatorMismatch(QualType ObjType, 3058 const SubobjectDesignator &A, 3059 const SubobjectDesignator &B, 3060 bool &WasArrayIndex) { 3061 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3062 for (/**/; I != N; ++I) { 3063 if (!ObjType.isNull() && 3064 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3065 // Next subobject is an array element. 3066 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) { 3067 WasArrayIndex = true; 3068 return I; 3069 } 3070 if (ObjType->isAnyComplexType()) 3071 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3072 else 3073 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3074 } else { 3075 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) { 3076 WasArrayIndex = false; 3077 return I; 3078 } 3079 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3080 // Next subobject is a field. 3081 ObjType = FD->getType(); 3082 else 3083 // Next subobject is a base class. 3084 ObjType = QualType(); 3085 } 3086 } 3087 WasArrayIndex = false; 3088 return I; 3089 } 3090 3091 /// Determine whether the given subobject designators refer to elements of the 3092 /// same array object. 3093 static bool AreElementsOfSameArray(QualType ObjType, 3094 const SubobjectDesignator &A, 3095 const SubobjectDesignator &B) { 3096 if (A.Entries.size() != B.Entries.size()) 3097 return false; 3098 3099 bool IsArray = A.MostDerivedIsArrayElement; 3100 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3101 // A is a subobject of the array element. 3102 return false; 3103 3104 // If A (and B) designates an array element, the last entry will be the array 3105 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3106 // of length 1' case, and the entire path must match. 3107 bool WasArrayIndex; 3108 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3109 return CommonLength >= A.Entries.size() - IsArray; 3110 } 3111 3112 /// Find the complete object to which an LValue refers. 3113 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3114 AccessKinds AK, const LValue &LVal, 3115 QualType LValType) { 3116 if (!LVal.Base) { 3117 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3118 return CompleteObject(); 3119 } 3120 3121 CallStackFrame *Frame = nullptr; 3122 if (LVal.getLValueCallIndex()) { 3123 Frame = Info.getCallFrame(LVal.getLValueCallIndex()); 3124 if (!Frame) { 3125 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3126 << AK << LVal.Base.is<const ValueDecl*>(); 3127 NoteLValueLocation(Info, LVal.Base); 3128 return CompleteObject(); 3129 } 3130 } 3131 3132 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3133 // is not a constant expression (even if the object is non-volatile). We also 3134 // apply this rule to C++98, in order to conform to the expected 'volatile' 3135 // semantics. 3136 if (LValType.isVolatileQualified()) { 3137 if (Info.getLangOpts().CPlusPlus) 3138 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3139 << AK << LValType; 3140 else 3141 Info.FFDiag(E); 3142 return CompleteObject(); 3143 } 3144 3145 // Compute value storage location and type of base object. 3146 APValue *BaseVal = nullptr; 3147 QualType BaseType = getType(LVal.Base); 3148 bool LifetimeStartedInEvaluation = Frame; 3149 3150 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3151 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3152 // In C++11, constexpr, non-volatile variables initialized with constant 3153 // expressions are constant expressions too. Inside constexpr functions, 3154 // parameters are constant expressions even if they're non-const. 3155 // In C++1y, objects local to a constant expression (those with a Frame) are 3156 // both readable and writable inside constant expressions. 3157 // In C, such things can also be folded, although they are not ICEs. 3158 const VarDecl *VD = dyn_cast<VarDecl>(D); 3159 if (VD) { 3160 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3161 VD = VDef; 3162 } 3163 if (!VD || VD->isInvalidDecl()) { 3164 Info.FFDiag(E); 3165 return CompleteObject(); 3166 } 3167 3168 // Accesses of volatile-qualified objects are not allowed. 3169 if (BaseType.isVolatileQualified()) { 3170 if (Info.getLangOpts().CPlusPlus) { 3171 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3172 << AK << 1 << VD; 3173 Info.Note(VD->getLocation(), diag::note_declared_at); 3174 } else { 3175 Info.FFDiag(E); 3176 } 3177 return CompleteObject(); 3178 } 3179 3180 // Unless we're looking at a local variable or argument in a constexpr call, 3181 // the variable we're reading must be const. 3182 if (!Frame) { 3183 if (Info.getLangOpts().CPlusPlus14 && 3184 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) { 3185 // OK, we can read and modify an object if we're in the process of 3186 // evaluating its initializer, because its lifetime began in this 3187 // evaluation. 3188 } else if (AK != AK_Read) { 3189 // All the remaining cases only permit reading. 3190 Info.FFDiag(E, diag::note_constexpr_modify_global); 3191 return CompleteObject(); 3192 } else if (VD->isConstexpr()) { 3193 // OK, we can read this variable. 3194 } else if (BaseType->isIntegralOrEnumerationType()) { 3195 // In OpenCL if a variable is in constant address space it is a const value. 3196 if (!(BaseType.isConstQualified() || 3197 (Info.getLangOpts().OpenCL && 3198 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3199 if (Info.getLangOpts().CPlusPlus) { 3200 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3201 Info.Note(VD->getLocation(), diag::note_declared_at); 3202 } else { 3203 Info.FFDiag(E); 3204 } 3205 return CompleteObject(); 3206 } 3207 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3208 // We support folding of const floating-point types, in order to make 3209 // static const data members of such types (supported as an extension) 3210 // more useful. 3211 if (Info.getLangOpts().CPlusPlus11) { 3212 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3213 Info.Note(VD->getLocation(), diag::note_declared_at); 3214 } else { 3215 Info.CCEDiag(E); 3216 } 3217 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3218 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3219 // Keep evaluating to see what we can do. 3220 } else { 3221 // FIXME: Allow folding of values of any literal type in all languages. 3222 if (Info.checkingPotentialConstantExpression() && 3223 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3224 // The definition of this variable could be constexpr. We can't 3225 // access it right now, but may be able to in future. 3226 } else if (Info.getLangOpts().CPlusPlus11) { 3227 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3228 Info.Note(VD->getLocation(), diag::note_declared_at); 3229 } else { 3230 Info.FFDiag(E); 3231 } 3232 return CompleteObject(); 3233 } 3234 } 3235 3236 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3237 return CompleteObject(); 3238 } else { 3239 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3240 3241 if (!Frame) { 3242 if (const MaterializeTemporaryExpr *MTE = 3243 dyn_cast<MaterializeTemporaryExpr>(Base)) { 3244 assert(MTE->getStorageDuration() == SD_Static && 3245 "should have a frame for a non-global materialized temporary"); 3246 3247 // Per C++1y [expr.const]p2: 3248 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3249 // - a [...] glvalue of integral or enumeration type that refers to 3250 // a non-volatile const object [...] 3251 // [...] 3252 // - a [...] glvalue of literal type that refers to a non-volatile 3253 // object whose lifetime began within the evaluation of e. 3254 // 3255 // C++11 misses the 'began within the evaluation of e' check and 3256 // instead allows all temporaries, including things like: 3257 // int &&r = 1; 3258 // int x = ++r; 3259 // constexpr int k = r; 3260 // Therefore we use the C++14 rules in C++11 too. 3261 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3262 const ValueDecl *ED = MTE->getExtendingDecl(); 3263 if (!(BaseType.isConstQualified() && 3264 BaseType->isIntegralOrEnumerationType()) && 3265 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 3266 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3267 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3268 return CompleteObject(); 3269 } 3270 3271 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3272 assert(BaseVal && "got reference to unevaluated temporary"); 3273 LifetimeStartedInEvaluation = true; 3274 } else { 3275 Info.FFDiag(E); 3276 return CompleteObject(); 3277 } 3278 } else { 3279 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3280 assert(BaseVal && "missing value for temporary"); 3281 } 3282 3283 // Volatile temporary objects cannot be accessed in constant expressions. 3284 if (BaseType.isVolatileQualified()) { 3285 if (Info.getLangOpts().CPlusPlus) { 3286 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3287 << AK << 0; 3288 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here); 3289 } else { 3290 Info.FFDiag(E); 3291 } 3292 return CompleteObject(); 3293 } 3294 } 3295 3296 // During the construction of an object, it is not yet 'const'. 3297 // FIXME: This doesn't do quite the right thing for const subobjects of the 3298 // object under construction. 3299 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), 3300 LVal.getLValueCallIndex(), 3301 LVal.getLValueVersion())) { 3302 BaseType = Info.Ctx.getCanonicalType(BaseType); 3303 BaseType.removeLocalConst(); 3304 LifetimeStartedInEvaluation = true; 3305 } 3306 3307 // In C++14, we can't safely access any mutable state when we might be 3308 // evaluating after an unmodeled side effect. 3309 // 3310 // FIXME: Not all local state is mutable. Allow local constant subobjects 3311 // to be read here (but take care with 'mutable' fields). 3312 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3313 Info.EvalStatus.HasSideEffects) || 3314 (AK != AK_Read && Info.IsSpeculativelyEvaluating)) 3315 return CompleteObject(); 3316 3317 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation); 3318 } 3319 3320 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3321 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3322 /// glvalue referred to by an entity of reference type. 3323 /// 3324 /// \param Info - Information about the ongoing evaluation. 3325 /// \param Conv - The expression for which we are performing the conversion. 3326 /// Used for diagnostics. 3327 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3328 /// case of a non-class type). 3329 /// \param LVal - The glvalue on which we are attempting to perform this action. 3330 /// \param RVal - The produced value will be placed here. 3331 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 3332 QualType Type, 3333 const LValue &LVal, APValue &RVal) { 3334 if (LVal.Designator.Invalid) 3335 return false; 3336 3337 // Check for special cases where there is no existing APValue to look at. 3338 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3339 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 3340 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3341 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3342 // initializer until now for such expressions. Such an expression can't be 3343 // an ICE in C, so this only matters for fold. 3344 if (Type.isVolatileQualified()) { 3345 Info.FFDiag(Conv); 3346 return false; 3347 } 3348 APValue Lit; 3349 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3350 return false; 3351 CompleteObject LitObj(&Lit, Base->getType(), false); 3352 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 3353 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3354 // We represent a string literal array as an lvalue pointing at the 3355 // corresponding expression, rather than building an array of chars. 3356 // FIXME: Support ObjCEncodeExpr, MakeStringConstant 3357 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0); 3358 CompleteObject StrObj(&Str, Base->getType(), false); 3359 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal); 3360 } 3361 } 3362 3363 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 3364 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 3365 } 3366 3367 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3368 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3369 QualType LValType, APValue &Val) { 3370 if (LVal.Designator.Invalid) 3371 return false; 3372 3373 if (!Info.getLangOpts().CPlusPlus14) { 3374 Info.FFDiag(E); 3375 return false; 3376 } 3377 3378 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3379 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3380 } 3381 3382 namespace { 3383 struct CompoundAssignSubobjectHandler { 3384 EvalInfo &Info; 3385 const Expr *E; 3386 QualType PromotedLHSType; 3387 BinaryOperatorKind Opcode; 3388 const APValue &RHS; 3389 3390 static const AccessKinds AccessKind = AK_Assign; 3391 3392 typedef bool result_type; 3393 3394 bool checkConst(QualType QT) { 3395 // Assigning to a const object has undefined behavior. 3396 if (QT.isConstQualified()) { 3397 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3398 return false; 3399 } 3400 return true; 3401 } 3402 3403 bool failed() { return false; } 3404 bool found(APValue &Subobj, QualType SubobjType) { 3405 switch (Subobj.getKind()) { 3406 case APValue::Int: 3407 return found(Subobj.getInt(), SubobjType); 3408 case APValue::Float: 3409 return found(Subobj.getFloat(), SubobjType); 3410 case APValue::ComplexInt: 3411 case APValue::ComplexFloat: 3412 // FIXME: Implement complex compound assignment. 3413 Info.FFDiag(E); 3414 return false; 3415 case APValue::LValue: 3416 return foundPointer(Subobj, SubobjType); 3417 default: 3418 // FIXME: can this happen? 3419 Info.FFDiag(E); 3420 return false; 3421 } 3422 } 3423 bool found(APSInt &Value, QualType SubobjType) { 3424 if (!checkConst(SubobjType)) 3425 return false; 3426 3427 if (!SubobjType->isIntegerType() || !RHS.isInt()) { 3428 // We don't support compound assignment on integer-cast-to-pointer 3429 // values. 3430 Info.FFDiag(E); 3431 return false; 3432 } 3433 3434 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType, 3435 SubobjType, Value); 3436 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3437 return false; 3438 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3439 return true; 3440 } 3441 bool found(APFloat &Value, QualType SubobjType) { 3442 return checkConst(SubobjType) && 3443 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3444 Value) && 3445 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3446 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3447 } 3448 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3449 if (!checkConst(SubobjType)) 3450 return false; 3451 3452 QualType PointeeType; 3453 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3454 PointeeType = PT->getPointeeType(); 3455 3456 if (PointeeType.isNull() || !RHS.isInt() || 3457 (Opcode != BO_Add && Opcode != BO_Sub)) { 3458 Info.FFDiag(E); 3459 return false; 3460 } 3461 3462 APSInt Offset = RHS.getInt(); 3463 if (Opcode == BO_Sub) 3464 negateAsSigned(Offset); 3465 3466 LValue LVal; 3467 LVal.setFrom(Info.Ctx, Subobj); 3468 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3469 return false; 3470 LVal.moveInto(Subobj); 3471 return true; 3472 } 3473 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3474 llvm_unreachable("shouldn't encounter string elements here"); 3475 } 3476 }; 3477 } // end anonymous namespace 3478 3479 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3480 3481 /// Perform a compound assignment of LVal <op>= RVal. 3482 static bool handleCompoundAssignment( 3483 EvalInfo &Info, const Expr *E, 3484 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3485 BinaryOperatorKind Opcode, const APValue &RVal) { 3486 if (LVal.Designator.Invalid) 3487 return false; 3488 3489 if (!Info.getLangOpts().CPlusPlus14) { 3490 Info.FFDiag(E); 3491 return false; 3492 } 3493 3494 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3495 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3496 RVal }; 3497 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3498 } 3499 3500 namespace { 3501 struct IncDecSubobjectHandler { 3502 EvalInfo &Info; 3503 const UnaryOperator *E; 3504 AccessKinds AccessKind; 3505 APValue *Old; 3506 3507 typedef bool result_type; 3508 3509 bool checkConst(QualType QT) { 3510 // Assigning to a const object has undefined behavior. 3511 if (QT.isConstQualified()) { 3512 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3513 return false; 3514 } 3515 return true; 3516 } 3517 3518 bool failed() { return false; } 3519 bool found(APValue &Subobj, QualType SubobjType) { 3520 // Stash the old value. Also clear Old, so we don't clobber it later 3521 // if we're post-incrementing a complex. 3522 if (Old) { 3523 *Old = Subobj; 3524 Old = nullptr; 3525 } 3526 3527 switch (Subobj.getKind()) { 3528 case APValue::Int: 3529 return found(Subobj.getInt(), SubobjType); 3530 case APValue::Float: 3531 return found(Subobj.getFloat(), SubobjType); 3532 case APValue::ComplexInt: 3533 return found(Subobj.getComplexIntReal(), 3534 SubobjType->castAs<ComplexType>()->getElementType() 3535 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3536 case APValue::ComplexFloat: 3537 return found(Subobj.getComplexFloatReal(), 3538 SubobjType->castAs<ComplexType>()->getElementType() 3539 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3540 case APValue::LValue: 3541 return foundPointer(Subobj, SubobjType); 3542 default: 3543 // FIXME: can this happen? 3544 Info.FFDiag(E); 3545 return false; 3546 } 3547 } 3548 bool found(APSInt &Value, QualType SubobjType) { 3549 if (!checkConst(SubobjType)) 3550 return false; 3551 3552 if (!SubobjType->isIntegerType()) { 3553 // We don't support increment / decrement on integer-cast-to-pointer 3554 // values. 3555 Info.FFDiag(E); 3556 return false; 3557 } 3558 3559 if (Old) *Old = APValue(Value); 3560 3561 // bool arithmetic promotes to int, and the conversion back to bool 3562 // doesn't reduce mod 2^n, so special-case it. 3563 if (SubobjType->isBooleanType()) { 3564 if (AccessKind == AK_Increment) 3565 Value = 1; 3566 else 3567 Value = !Value; 3568 return true; 3569 } 3570 3571 bool WasNegative = Value.isNegative(); 3572 if (AccessKind == AK_Increment) { 3573 ++Value; 3574 3575 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 3576 APSInt ActualValue(Value, /*IsUnsigned*/true); 3577 return HandleOverflow(Info, E, ActualValue, SubobjType); 3578 } 3579 } else { 3580 --Value; 3581 3582 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 3583 unsigned BitWidth = Value.getBitWidth(); 3584 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3585 ActualValue.setBit(BitWidth); 3586 return HandleOverflow(Info, E, ActualValue, SubobjType); 3587 } 3588 } 3589 return true; 3590 } 3591 bool found(APFloat &Value, QualType SubobjType) { 3592 if (!checkConst(SubobjType)) 3593 return false; 3594 3595 if (Old) *Old = APValue(Value); 3596 3597 APFloat One(Value.getSemantics(), 1); 3598 if (AccessKind == AK_Increment) 3599 Value.add(One, APFloat::rmNearestTiesToEven); 3600 else 3601 Value.subtract(One, APFloat::rmNearestTiesToEven); 3602 return true; 3603 } 3604 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3605 if (!checkConst(SubobjType)) 3606 return false; 3607 3608 QualType PointeeType; 3609 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3610 PointeeType = PT->getPointeeType(); 3611 else { 3612 Info.FFDiag(E); 3613 return false; 3614 } 3615 3616 LValue LVal; 3617 LVal.setFrom(Info.Ctx, Subobj); 3618 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3619 AccessKind == AK_Increment ? 1 : -1)) 3620 return false; 3621 LVal.moveInto(Subobj); 3622 return true; 3623 } 3624 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3625 llvm_unreachable("shouldn't encounter string elements here"); 3626 } 3627 }; 3628 } // end anonymous namespace 3629 3630 /// Perform an increment or decrement on LVal. 3631 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3632 QualType LValType, bool IsIncrement, APValue *Old) { 3633 if (LVal.Designator.Invalid) 3634 return false; 3635 3636 if (!Info.getLangOpts().CPlusPlus14) { 3637 Info.FFDiag(E); 3638 return false; 3639 } 3640 3641 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3642 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3643 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 3644 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3645 } 3646 3647 /// Build an lvalue for the object argument of a member function call. 3648 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3649 LValue &This) { 3650 if (Object->getType()->isPointerType()) 3651 return EvaluatePointer(Object, This, Info); 3652 3653 if (Object->isGLValue()) 3654 return EvaluateLValue(Object, This, Info); 3655 3656 if (Object->getType()->isLiteralType(Info.Ctx)) 3657 return EvaluateTemporary(Object, This, Info); 3658 3659 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3660 return false; 3661 } 3662 3663 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3664 /// lvalue referring to the result. 3665 /// 3666 /// \param Info - Information about the ongoing evaluation. 3667 /// \param LV - An lvalue referring to the base of the member pointer. 3668 /// \param RHS - The member pointer expression. 3669 /// \param IncludeMember - Specifies whether the member itself is included in 3670 /// the resulting LValue subobject designator. This is not possible when 3671 /// creating a bound member function. 3672 /// \return The field or method declaration to which the member pointer refers, 3673 /// or 0 if evaluation fails. 3674 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3675 QualType LVType, 3676 LValue &LV, 3677 const Expr *RHS, 3678 bool IncludeMember = true) { 3679 MemberPtr MemPtr; 3680 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3681 return nullptr; 3682 3683 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3684 // member value, the behavior is undefined. 3685 if (!MemPtr.getDecl()) { 3686 // FIXME: Specific diagnostic. 3687 Info.FFDiag(RHS); 3688 return nullptr; 3689 } 3690 3691 if (MemPtr.isDerivedMember()) { 3692 // This is a member of some derived class. Truncate LV appropriately. 3693 // The end of the derived-to-base path for the base object must match the 3694 // derived-to-base path for the member pointer. 3695 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3696 LV.Designator.Entries.size()) { 3697 Info.FFDiag(RHS); 3698 return nullptr; 3699 } 3700 unsigned PathLengthToMember = 3701 LV.Designator.Entries.size() - MemPtr.Path.size(); 3702 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3703 const CXXRecordDecl *LVDecl = getAsBaseClass( 3704 LV.Designator.Entries[PathLengthToMember + I]); 3705 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3706 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3707 Info.FFDiag(RHS); 3708 return nullptr; 3709 } 3710 } 3711 3712 // Truncate the lvalue to the appropriate derived class. 3713 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3714 PathLengthToMember)) 3715 return nullptr; 3716 } else if (!MemPtr.Path.empty()) { 3717 // Extend the LValue path with the member pointer's path. 3718 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3719 MemPtr.Path.size() + IncludeMember); 3720 3721 // Walk down to the appropriate base class. 3722 if (const PointerType *PT = LVType->getAs<PointerType>()) 3723 LVType = PT->getPointeeType(); 3724 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3725 assert(RD && "member pointer access on non-class-type expression"); 3726 // The first class in the path is that of the lvalue. 3727 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3728 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3729 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3730 return nullptr; 3731 RD = Base; 3732 } 3733 // Finally cast to the class containing the member. 3734 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3735 MemPtr.getContainingRecord())) 3736 return nullptr; 3737 } 3738 3739 // Add the member. Note that we cannot build bound member functions here. 3740 if (IncludeMember) { 3741 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3742 if (!HandleLValueMember(Info, RHS, LV, FD)) 3743 return nullptr; 3744 } else if (const IndirectFieldDecl *IFD = 3745 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3746 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3747 return nullptr; 3748 } else { 3749 llvm_unreachable("can't construct reference to bound member function"); 3750 } 3751 } 3752 3753 return MemPtr.getDecl(); 3754 } 3755 3756 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3757 const BinaryOperator *BO, 3758 LValue &LV, 3759 bool IncludeMember = true) { 3760 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3761 3762 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3763 if (Info.noteFailure()) { 3764 MemberPtr MemPtr; 3765 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3766 } 3767 return nullptr; 3768 } 3769 3770 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3771 BO->getRHS(), IncludeMember); 3772 } 3773 3774 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3775 /// the provided lvalue, which currently refers to the base object. 3776 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3777 LValue &Result) { 3778 SubobjectDesignator &D = Result.Designator; 3779 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3780 return false; 3781 3782 QualType TargetQT = E->getType(); 3783 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 3784 TargetQT = PT->getPointeeType(); 3785 3786 // Check this cast lands within the final derived-to-base subobject path. 3787 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 3788 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3789 << D.MostDerivedType << TargetQT; 3790 return false; 3791 } 3792 3793 // Check the type of the final cast. We don't need to check the path, 3794 // since a cast can only be formed if the path is unique. 3795 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 3796 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 3797 const CXXRecordDecl *FinalType; 3798 if (NewEntriesSize == D.MostDerivedPathLength) 3799 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 3800 else 3801 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 3802 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 3803 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3804 << D.MostDerivedType << TargetQT; 3805 return false; 3806 } 3807 3808 // Truncate the lvalue to the appropriate derived class. 3809 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 3810 } 3811 3812 namespace { 3813 enum EvalStmtResult { 3814 /// Evaluation failed. 3815 ESR_Failed, 3816 /// Hit a 'return' statement. 3817 ESR_Returned, 3818 /// Evaluation succeeded. 3819 ESR_Succeeded, 3820 /// Hit a 'continue' statement. 3821 ESR_Continue, 3822 /// Hit a 'break' statement. 3823 ESR_Break, 3824 /// Still scanning for 'case' or 'default' statement. 3825 ESR_CaseNotFound 3826 }; 3827 } 3828 3829 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 3830 // We don't need to evaluate the initializer for a static local. 3831 if (!VD->hasLocalStorage()) 3832 return true; 3833 3834 LValue Result; 3835 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall); 3836 3837 const Expr *InitE = VD->getInit(); 3838 if (!InitE) { 3839 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized) 3840 << false << VD->getType(); 3841 Val = APValue(); 3842 return false; 3843 } 3844 3845 if (InitE->isValueDependent()) 3846 return false; 3847 3848 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 3849 // Wipe out any partially-computed value, to allow tracking that this 3850 // evaluation failed. 3851 Val = APValue(); 3852 return false; 3853 } 3854 3855 return true; 3856 } 3857 3858 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 3859 bool OK = true; 3860 3861 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 3862 OK &= EvaluateVarDecl(Info, VD); 3863 3864 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 3865 for (auto *BD : DD->bindings()) 3866 if (auto *VD = BD->getHoldingVar()) 3867 OK &= EvaluateDecl(Info, VD); 3868 3869 return OK; 3870 } 3871 3872 3873 /// Evaluate a condition (either a variable declaration or an expression). 3874 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 3875 const Expr *Cond, bool &Result) { 3876 FullExpressionRAII Scope(Info); 3877 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 3878 return false; 3879 return EvaluateAsBooleanCondition(Cond, Result, Info); 3880 } 3881 3882 namespace { 3883 /// A location where the result (returned value) of evaluating a 3884 /// statement should be stored. 3885 struct StmtResult { 3886 /// The APValue that should be filled in with the returned value. 3887 APValue &Value; 3888 /// The location containing the result, if any (used to support RVO). 3889 const LValue *Slot; 3890 }; 3891 3892 struct TempVersionRAII { 3893 CallStackFrame &Frame; 3894 3895 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 3896 Frame.pushTempVersion(); 3897 } 3898 3899 ~TempVersionRAII() { 3900 Frame.popTempVersion(); 3901 } 3902 }; 3903 3904 } 3905 3906 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3907 const Stmt *S, 3908 const SwitchCase *SC = nullptr); 3909 3910 /// Evaluate the body of a loop, and translate the result as appropriate. 3911 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 3912 const Stmt *Body, 3913 const SwitchCase *Case = nullptr) { 3914 BlockScopeRAII Scope(Info); 3915 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 3916 case ESR_Break: 3917 return ESR_Succeeded; 3918 case ESR_Succeeded: 3919 case ESR_Continue: 3920 return ESR_Continue; 3921 case ESR_Failed: 3922 case ESR_Returned: 3923 case ESR_CaseNotFound: 3924 return ESR; 3925 } 3926 llvm_unreachable("Invalid EvalStmtResult!"); 3927 } 3928 3929 /// Evaluate a switch statement. 3930 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 3931 const SwitchStmt *SS) { 3932 BlockScopeRAII Scope(Info); 3933 3934 // Evaluate the switch condition. 3935 APSInt Value; 3936 { 3937 FullExpressionRAII Scope(Info); 3938 if (const Stmt *Init = SS->getInit()) { 3939 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3940 if (ESR != ESR_Succeeded) 3941 return ESR; 3942 } 3943 if (SS->getConditionVariable() && 3944 !EvaluateDecl(Info, SS->getConditionVariable())) 3945 return ESR_Failed; 3946 if (!EvaluateInteger(SS->getCond(), Value, Info)) 3947 return ESR_Failed; 3948 } 3949 3950 // Find the switch case corresponding to the value of the condition. 3951 // FIXME: Cache this lookup. 3952 const SwitchCase *Found = nullptr; 3953 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 3954 SC = SC->getNextSwitchCase()) { 3955 if (isa<DefaultStmt>(SC)) { 3956 Found = SC; 3957 continue; 3958 } 3959 3960 const CaseStmt *CS = cast<CaseStmt>(SC); 3961 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 3962 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 3963 : LHS; 3964 if (LHS <= Value && Value <= RHS) { 3965 Found = SC; 3966 break; 3967 } 3968 } 3969 3970 if (!Found) 3971 return ESR_Succeeded; 3972 3973 // Search the switch body for the switch case and evaluate it from there. 3974 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 3975 case ESR_Break: 3976 return ESR_Succeeded; 3977 case ESR_Succeeded: 3978 case ESR_Continue: 3979 case ESR_Failed: 3980 case ESR_Returned: 3981 return ESR; 3982 case ESR_CaseNotFound: 3983 // This can only happen if the switch case is nested within a statement 3984 // expression. We have no intention of supporting that. 3985 Info.FFDiag(Found->getBeginLoc(), 3986 diag::note_constexpr_stmt_expr_unsupported); 3987 return ESR_Failed; 3988 } 3989 llvm_unreachable("Invalid EvalStmtResult!"); 3990 } 3991 3992 // Evaluate a statement. 3993 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3994 const Stmt *S, const SwitchCase *Case) { 3995 if (!Info.nextStep(S)) 3996 return ESR_Failed; 3997 3998 // If we're hunting down a 'case' or 'default' label, recurse through 3999 // substatements until we hit the label. 4000 if (Case) { 4001 // FIXME: We don't start the lifetime of objects whose initialization we 4002 // jump over. However, such objects must be of class type with a trivial 4003 // default constructor that initialize all subobjects, so must be empty, 4004 // so this almost never matters. 4005 switch (S->getStmtClass()) { 4006 case Stmt::CompoundStmtClass: 4007 // FIXME: Precompute which substatement of a compound statement we 4008 // would jump to, and go straight there rather than performing a 4009 // linear scan each time. 4010 case Stmt::LabelStmtClass: 4011 case Stmt::AttributedStmtClass: 4012 case Stmt::DoStmtClass: 4013 break; 4014 4015 case Stmt::CaseStmtClass: 4016 case Stmt::DefaultStmtClass: 4017 if (Case == S) 4018 Case = nullptr; 4019 break; 4020 4021 case Stmt::IfStmtClass: { 4022 // FIXME: Precompute which side of an 'if' we would jump to, and go 4023 // straight there rather than scanning both sides. 4024 const IfStmt *IS = cast<IfStmt>(S); 4025 4026 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4027 // preceded by our switch label. 4028 BlockScopeRAII Scope(Info); 4029 4030 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4031 if (ESR != ESR_CaseNotFound || !IS->getElse()) 4032 return ESR; 4033 return EvaluateStmt(Result, Info, IS->getElse(), Case); 4034 } 4035 4036 case Stmt::WhileStmtClass: { 4037 EvalStmtResult ESR = 4038 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4039 if (ESR != ESR_Continue) 4040 return ESR; 4041 break; 4042 } 4043 4044 case Stmt::ForStmtClass: { 4045 const ForStmt *FS = cast<ForStmt>(S); 4046 EvalStmtResult ESR = 4047 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4048 if (ESR != ESR_Continue) 4049 return ESR; 4050 if (FS->getInc()) { 4051 FullExpressionRAII IncScope(Info); 4052 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4053 return ESR_Failed; 4054 } 4055 break; 4056 } 4057 4058 case Stmt::DeclStmtClass: 4059 // FIXME: If the variable has initialization that can't be jumped over, 4060 // bail out of any immediately-surrounding compound-statement too. 4061 default: 4062 return ESR_CaseNotFound; 4063 } 4064 } 4065 4066 switch (S->getStmtClass()) { 4067 default: 4068 if (const Expr *E = dyn_cast<Expr>(S)) { 4069 // Don't bother evaluating beyond an expression-statement which couldn't 4070 // be evaluated. 4071 FullExpressionRAII Scope(Info); 4072 if (!EvaluateIgnoredValue(Info, E)) 4073 return ESR_Failed; 4074 return ESR_Succeeded; 4075 } 4076 4077 Info.FFDiag(S->getBeginLoc()); 4078 return ESR_Failed; 4079 4080 case Stmt::NullStmtClass: 4081 return ESR_Succeeded; 4082 4083 case Stmt::DeclStmtClass: { 4084 const DeclStmt *DS = cast<DeclStmt>(S); 4085 for (const auto *DclIt : DS->decls()) { 4086 // Each declaration initialization is its own full-expression. 4087 // FIXME: This isn't quite right; if we're performing aggregate 4088 // initialization, each braced subexpression is its own full-expression. 4089 FullExpressionRAII Scope(Info); 4090 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 4091 return ESR_Failed; 4092 } 4093 return ESR_Succeeded; 4094 } 4095 4096 case Stmt::ReturnStmtClass: { 4097 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4098 FullExpressionRAII Scope(Info); 4099 if (RetExpr && 4100 !(Result.Slot 4101 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4102 : Evaluate(Result.Value, Info, RetExpr))) 4103 return ESR_Failed; 4104 return ESR_Returned; 4105 } 4106 4107 case Stmt::CompoundStmtClass: { 4108 BlockScopeRAII Scope(Info); 4109 4110 const CompoundStmt *CS = cast<CompoundStmt>(S); 4111 for (const auto *BI : CS->body()) { 4112 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4113 if (ESR == ESR_Succeeded) 4114 Case = nullptr; 4115 else if (ESR != ESR_CaseNotFound) 4116 return ESR; 4117 } 4118 return Case ? ESR_CaseNotFound : ESR_Succeeded; 4119 } 4120 4121 case Stmt::IfStmtClass: { 4122 const IfStmt *IS = cast<IfStmt>(S); 4123 4124 // Evaluate the condition, as either a var decl or as an expression. 4125 BlockScopeRAII Scope(Info); 4126 if (const Stmt *Init = IS->getInit()) { 4127 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4128 if (ESR != ESR_Succeeded) 4129 return ESR; 4130 } 4131 bool Cond; 4132 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4133 return ESR_Failed; 4134 4135 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4136 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4137 if (ESR != ESR_Succeeded) 4138 return ESR; 4139 } 4140 return ESR_Succeeded; 4141 } 4142 4143 case Stmt::WhileStmtClass: { 4144 const WhileStmt *WS = cast<WhileStmt>(S); 4145 while (true) { 4146 BlockScopeRAII Scope(Info); 4147 bool Continue; 4148 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4149 Continue)) 4150 return ESR_Failed; 4151 if (!Continue) 4152 break; 4153 4154 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4155 if (ESR != ESR_Continue) 4156 return ESR; 4157 } 4158 return ESR_Succeeded; 4159 } 4160 4161 case Stmt::DoStmtClass: { 4162 const DoStmt *DS = cast<DoStmt>(S); 4163 bool Continue; 4164 do { 4165 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4166 if (ESR != ESR_Continue) 4167 return ESR; 4168 Case = nullptr; 4169 4170 FullExpressionRAII CondScope(Info); 4171 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 4172 return ESR_Failed; 4173 } while (Continue); 4174 return ESR_Succeeded; 4175 } 4176 4177 case Stmt::ForStmtClass: { 4178 const ForStmt *FS = cast<ForStmt>(S); 4179 BlockScopeRAII Scope(Info); 4180 if (FS->getInit()) { 4181 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4182 if (ESR != ESR_Succeeded) 4183 return ESR; 4184 } 4185 while (true) { 4186 BlockScopeRAII Scope(Info); 4187 bool Continue = true; 4188 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4189 FS->getCond(), Continue)) 4190 return ESR_Failed; 4191 if (!Continue) 4192 break; 4193 4194 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4195 if (ESR != ESR_Continue) 4196 return ESR; 4197 4198 if (FS->getInc()) { 4199 FullExpressionRAII IncScope(Info); 4200 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4201 return ESR_Failed; 4202 } 4203 } 4204 return ESR_Succeeded; 4205 } 4206 4207 case Stmt::CXXForRangeStmtClass: { 4208 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4209 BlockScopeRAII Scope(Info); 4210 4211 // Evaluate the init-statement if present. 4212 if (FS->getInit()) { 4213 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4214 if (ESR != ESR_Succeeded) 4215 return ESR; 4216 } 4217 4218 // Initialize the __range variable. 4219 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4220 if (ESR != ESR_Succeeded) 4221 return ESR; 4222 4223 // Create the __begin and __end iterators. 4224 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4225 if (ESR != ESR_Succeeded) 4226 return ESR; 4227 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4228 if (ESR != ESR_Succeeded) 4229 return ESR; 4230 4231 while (true) { 4232 // Condition: __begin != __end. 4233 { 4234 bool Continue = true; 4235 FullExpressionRAII CondExpr(Info); 4236 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4237 return ESR_Failed; 4238 if (!Continue) 4239 break; 4240 } 4241 4242 // User's variable declaration, initialized by *__begin. 4243 BlockScopeRAII InnerScope(Info); 4244 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4245 if (ESR != ESR_Succeeded) 4246 return ESR; 4247 4248 // Loop body. 4249 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4250 if (ESR != ESR_Continue) 4251 return ESR; 4252 4253 // Increment: ++__begin 4254 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4255 return ESR_Failed; 4256 } 4257 4258 return ESR_Succeeded; 4259 } 4260 4261 case Stmt::SwitchStmtClass: 4262 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4263 4264 case Stmt::ContinueStmtClass: 4265 return ESR_Continue; 4266 4267 case Stmt::BreakStmtClass: 4268 return ESR_Break; 4269 4270 case Stmt::LabelStmtClass: 4271 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4272 4273 case Stmt::AttributedStmtClass: 4274 // As a general principle, C++11 attributes can be ignored without 4275 // any semantic impact. 4276 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4277 Case); 4278 4279 case Stmt::CaseStmtClass: 4280 case Stmt::DefaultStmtClass: 4281 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4282 } 4283 } 4284 4285 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4286 /// default constructor. If so, we'll fold it whether or not it's marked as 4287 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4288 /// so we need special handling. 4289 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4290 const CXXConstructorDecl *CD, 4291 bool IsValueInitialization) { 4292 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4293 return false; 4294 4295 // Value-initialization does not call a trivial default constructor, so such a 4296 // call is a core constant expression whether or not the constructor is 4297 // constexpr. 4298 if (!CD->isConstexpr() && !IsValueInitialization) { 4299 if (Info.getLangOpts().CPlusPlus11) { 4300 // FIXME: If DiagDecl is an implicitly-declared special member function, 4301 // we should be much more explicit about why it's not constexpr. 4302 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4303 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4304 Info.Note(CD->getLocation(), diag::note_declared_at); 4305 } else { 4306 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4307 } 4308 } 4309 return true; 4310 } 4311 4312 /// CheckConstexprFunction - Check that a function can be called in a constant 4313 /// expression. 4314 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4315 const FunctionDecl *Declaration, 4316 const FunctionDecl *Definition, 4317 const Stmt *Body) { 4318 // Potential constant expressions can contain calls to declared, but not yet 4319 // defined, constexpr functions. 4320 if (Info.checkingPotentialConstantExpression() && !Definition && 4321 Declaration->isConstexpr()) 4322 return false; 4323 4324 // Bail out if the function declaration itself is invalid. We will 4325 // have produced a relevant diagnostic while parsing it, so just 4326 // note the problematic sub-expression. 4327 if (Declaration->isInvalidDecl()) { 4328 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4329 return false; 4330 } 4331 4332 // Can we evaluate this function call? 4333 if (Definition && Definition->isConstexpr() && 4334 !Definition->isInvalidDecl() && Body) 4335 return true; 4336 4337 if (Info.getLangOpts().CPlusPlus11) { 4338 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4339 4340 // If this function is not constexpr because it is an inherited 4341 // non-constexpr constructor, diagnose that directly. 4342 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4343 if (CD && CD->isInheritingConstructor()) { 4344 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4345 if (!Inherited->isConstexpr()) 4346 DiagDecl = CD = Inherited; 4347 } 4348 4349 // FIXME: If DiagDecl is an implicitly-declared special member function 4350 // or an inheriting constructor, we should be much more explicit about why 4351 // it's not constexpr. 4352 if (CD && CD->isInheritingConstructor()) 4353 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4354 << CD->getInheritedConstructor().getConstructor()->getParent(); 4355 else 4356 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4357 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4358 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4359 } else { 4360 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4361 } 4362 return false; 4363 } 4364 4365 /// Determine if a class has any fields that might need to be copied by a 4366 /// trivial copy or move operation. 4367 static bool hasFields(const CXXRecordDecl *RD) { 4368 if (!RD || RD->isEmpty()) 4369 return false; 4370 for (auto *FD : RD->fields()) { 4371 if (FD->isUnnamedBitfield()) 4372 continue; 4373 return true; 4374 } 4375 for (auto &Base : RD->bases()) 4376 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 4377 return true; 4378 return false; 4379 } 4380 4381 namespace { 4382 typedef SmallVector<APValue, 8> ArgVector; 4383 } 4384 4385 /// EvaluateArgs - Evaluate the arguments to a function call. 4386 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 4387 EvalInfo &Info) { 4388 bool Success = true; 4389 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 4390 I != E; ++I) { 4391 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 4392 // If we're checking for a potential constant expression, evaluate all 4393 // initializers even if some of them fail. 4394 if (!Info.noteFailure()) 4395 return false; 4396 Success = false; 4397 } 4398 } 4399 return Success; 4400 } 4401 4402 /// Evaluate a function call. 4403 static bool HandleFunctionCall(SourceLocation CallLoc, 4404 const FunctionDecl *Callee, const LValue *This, 4405 ArrayRef<const Expr*> Args, const Stmt *Body, 4406 EvalInfo &Info, APValue &Result, 4407 const LValue *ResultSlot) { 4408 ArgVector ArgValues(Args.size()); 4409 if (!EvaluateArgs(Args, ArgValues, Info)) 4410 return false; 4411 4412 if (!Info.CheckCallLimit(CallLoc)) 4413 return false; 4414 4415 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 4416 4417 // For a trivial copy or move assignment, perform an APValue copy. This is 4418 // essential for unions, where the operations performed by the assignment 4419 // operator cannot be represented as statements. 4420 // 4421 // Skip this for non-union classes with no fields; in that case, the defaulted 4422 // copy/move does not actually read the object. 4423 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 4424 if (MD && MD->isDefaulted() && 4425 (MD->getParent()->isUnion() || 4426 (MD->isTrivial() && hasFields(MD->getParent())))) { 4427 assert(This && 4428 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 4429 LValue RHS; 4430 RHS.setFrom(Info.Ctx, ArgValues[0]); 4431 APValue RHSValue; 4432 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 4433 RHS, RHSValue)) 4434 return false; 4435 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx), 4436 RHSValue)) 4437 return false; 4438 This->moveInto(Result); 4439 return true; 4440 } else if (MD && isLambdaCallOperator(MD)) { 4441 // We're in a lambda; determine the lambda capture field maps unless we're 4442 // just constexpr checking a lambda's call operator. constexpr checking is 4443 // done before the captures have been added to the closure object (unless 4444 // we're inferring constexpr-ness), so we don't have access to them in this 4445 // case. But since we don't need the captures to constexpr check, we can 4446 // just ignore them. 4447 if (!Info.checkingPotentialConstantExpression()) 4448 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 4449 Frame.LambdaThisCaptureField); 4450 } 4451 4452 StmtResult Ret = {Result, ResultSlot}; 4453 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 4454 if (ESR == ESR_Succeeded) { 4455 if (Callee->getReturnType()->isVoidType()) 4456 return true; 4457 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 4458 } 4459 return ESR == ESR_Returned; 4460 } 4461 4462 /// Evaluate a constructor call. 4463 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4464 APValue *ArgValues, 4465 const CXXConstructorDecl *Definition, 4466 EvalInfo &Info, APValue &Result) { 4467 SourceLocation CallLoc = E->getExprLoc(); 4468 if (!Info.CheckCallLimit(CallLoc)) 4469 return false; 4470 4471 const CXXRecordDecl *RD = Definition->getParent(); 4472 if (RD->getNumVBases()) { 4473 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 4474 return false; 4475 } 4476 4477 EvalInfo::EvaluatingConstructorRAII EvalObj( 4478 Info, {This.getLValueBase(), 4479 {This.getLValueCallIndex(), This.getLValueVersion()}}); 4480 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 4481 4482 // FIXME: Creating an APValue just to hold a nonexistent return value is 4483 // wasteful. 4484 APValue RetVal; 4485 StmtResult Ret = {RetVal, nullptr}; 4486 4487 // If it's a delegating constructor, delegate. 4488 if (Definition->isDelegatingConstructor()) { 4489 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 4490 { 4491 FullExpressionRAII InitScope(Info); 4492 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 4493 return false; 4494 } 4495 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4496 } 4497 4498 // For a trivial copy or move constructor, perform an APValue copy. This is 4499 // essential for unions (or classes with anonymous union members), where the 4500 // operations performed by the constructor cannot be represented by 4501 // ctor-initializers. 4502 // 4503 // Skip this for empty non-union classes; we should not perform an 4504 // lvalue-to-rvalue conversion on them because their copy constructor does not 4505 // actually read them. 4506 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 4507 (Definition->getParent()->isUnion() || 4508 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 4509 LValue RHS; 4510 RHS.setFrom(Info.Ctx, ArgValues[0]); 4511 return handleLValueToRValueConversion( 4512 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 4513 RHS, Result); 4514 } 4515 4516 // Reserve space for the struct members. 4517 if (!RD->isUnion() && Result.isUninit()) 4518 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4519 std::distance(RD->field_begin(), RD->field_end())); 4520 4521 if (RD->isInvalidDecl()) return false; 4522 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 4523 4524 // A scope for temporaries lifetime-extended by reference members. 4525 BlockScopeRAII LifetimeExtendedScope(Info); 4526 4527 bool Success = true; 4528 unsigned BasesSeen = 0; 4529 #ifndef NDEBUG 4530 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 4531 #endif 4532 for (const auto *I : Definition->inits()) { 4533 LValue Subobject = This; 4534 LValue SubobjectParent = This; 4535 APValue *Value = &Result; 4536 4537 // Determine the subobject to initialize. 4538 FieldDecl *FD = nullptr; 4539 if (I->isBaseInitializer()) { 4540 QualType BaseType(I->getBaseClass(), 0); 4541 #ifndef NDEBUG 4542 // Non-virtual base classes are initialized in the order in the class 4543 // definition. We have already checked for virtual base classes. 4544 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 4545 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 4546 "base class initializers not in expected order"); 4547 ++BaseIt; 4548 #endif 4549 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 4550 BaseType->getAsCXXRecordDecl(), &Layout)) 4551 return false; 4552 Value = &Result.getStructBase(BasesSeen++); 4553 } else if ((FD = I->getMember())) { 4554 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 4555 return false; 4556 if (RD->isUnion()) { 4557 Result = APValue(FD); 4558 Value = &Result.getUnionValue(); 4559 } else { 4560 Value = &Result.getStructField(FD->getFieldIndex()); 4561 } 4562 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 4563 // Walk the indirect field decl's chain to find the object to initialize, 4564 // and make sure we've initialized every step along it. 4565 auto IndirectFieldChain = IFD->chain(); 4566 for (auto *C : IndirectFieldChain) { 4567 FD = cast<FieldDecl>(C); 4568 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 4569 // Switch the union field if it differs. This happens if we had 4570 // preceding zero-initialization, and we're now initializing a union 4571 // subobject other than the first. 4572 // FIXME: In this case, the values of the other subobjects are 4573 // specified, since zero-initialization sets all padding bits to zero. 4574 if (Value->isUninit() || 4575 (Value->isUnion() && Value->getUnionField() != FD)) { 4576 if (CD->isUnion()) 4577 *Value = APValue(FD); 4578 else 4579 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 4580 std::distance(CD->field_begin(), CD->field_end())); 4581 } 4582 // Store Subobject as its parent before updating it for the last element 4583 // in the chain. 4584 if (C == IndirectFieldChain.back()) 4585 SubobjectParent = Subobject; 4586 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 4587 return false; 4588 if (CD->isUnion()) 4589 Value = &Value->getUnionValue(); 4590 else 4591 Value = &Value->getStructField(FD->getFieldIndex()); 4592 } 4593 } else { 4594 llvm_unreachable("unknown base initializer kind"); 4595 } 4596 4597 // Need to override This for implicit field initializers as in this case 4598 // This refers to innermost anonymous struct/union containing initializer, 4599 // not to currently constructed class. 4600 const Expr *Init = I->getInit(); 4601 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 4602 isa<CXXDefaultInitExpr>(Init)); 4603 FullExpressionRAII InitScope(Info); 4604 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 4605 (FD && FD->isBitField() && 4606 !truncateBitfieldValue(Info, Init, *Value, FD))) { 4607 // If we're checking for a potential constant expression, evaluate all 4608 // initializers even if some of them fail. 4609 if (!Info.noteFailure()) 4610 return false; 4611 Success = false; 4612 } 4613 } 4614 4615 return Success && 4616 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4617 } 4618 4619 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4620 ArrayRef<const Expr*> Args, 4621 const CXXConstructorDecl *Definition, 4622 EvalInfo &Info, APValue &Result) { 4623 ArgVector ArgValues(Args.size()); 4624 if (!EvaluateArgs(Args, ArgValues, Info)) 4625 return false; 4626 4627 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 4628 Info, Result); 4629 } 4630 4631 //===----------------------------------------------------------------------===// 4632 // Generic Evaluation 4633 //===----------------------------------------------------------------------===// 4634 namespace { 4635 4636 template <class Derived> 4637 class ExprEvaluatorBase 4638 : public ConstStmtVisitor<Derived, bool> { 4639 private: 4640 Derived &getDerived() { return static_cast<Derived&>(*this); } 4641 bool DerivedSuccess(const APValue &V, const Expr *E) { 4642 return getDerived().Success(V, E); 4643 } 4644 bool DerivedZeroInitialization(const Expr *E) { 4645 return getDerived().ZeroInitialization(E); 4646 } 4647 4648 // Check whether a conditional operator with a non-constant condition is a 4649 // potential constant expression. If neither arm is a potential constant 4650 // expression, then the conditional operator is not either. 4651 template<typename ConditionalOperator> 4652 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 4653 assert(Info.checkingPotentialConstantExpression()); 4654 4655 // Speculatively evaluate both arms. 4656 SmallVector<PartialDiagnosticAt, 8> Diag; 4657 { 4658 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4659 StmtVisitorTy::Visit(E->getFalseExpr()); 4660 if (Diag.empty()) 4661 return; 4662 } 4663 4664 { 4665 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4666 Diag.clear(); 4667 StmtVisitorTy::Visit(E->getTrueExpr()); 4668 if (Diag.empty()) 4669 return; 4670 } 4671 4672 Error(E, diag::note_constexpr_conditional_never_const); 4673 } 4674 4675 4676 template<typename ConditionalOperator> 4677 bool HandleConditionalOperator(const ConditionalOperator *E) { 4678 bool BoolResult; 4679 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 4680 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 4681 CheckPotentialConstantConditional(E); 4682 return false; 4683 } 4684 if (Info.noteFailure()) { 4685 StmtVisitorTy::Visit(E->getTrueExpr()); 4686 StmtVisitorTy::Visit(E->getFalseExpr()); 4687 } 4688 return false; 4689 } 4690 4691 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 4692 return StmtVisitorTy::Visit(EvalExpr); 4693 } 4694 4695 protected: 4696 EvalInfo &Info; 4697 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 4698 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 4699 4700 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 4701 return Info.CCEDiag(E, D); 4702 } 4703 4704 bool ZeroInitialization(const Expr *E) { return Error(E); } 4705 4706 public: 4707 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 4708 4709 EvalInfo &getEvalInfo() { return Info; } 4710 4711 /// Report an evaluation error. This should only be called when an error is 4712 /// first discovered. When propagating an error, just return false. 4713 bool Error(const Expr *E, diag::kind D) { 4714 Info.FFDiag(E, D); 4715 return false; 4716 } 4717 bool Error(const Expr *E) { 4718 return Error(E, diag::note_invalid_subexpr_in_const_expr); 4719 } 4720 4721 bool VisitStmt(const Stmt *) { 4722 llvm_unreachable("Expression evaluator should not be called on stmts"); 4723 } 4724 bool VisitExpr(const Expr *E) { 4725 return Error(E); 4726 } 4727 4728 bool VisitConstantExpr(const ConstantExpr *E) 4729 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4730 bool VisitParenExpr(const ParenExpr *E) 4731 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4732 bool VisitUnaryExtension(const UnaryOperator *E) 4733 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4734 bool VisitUnaryPlus(const UnaryOperator *E) 4735 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4736 bool VisitChooseExpr(const ChooseExpr *E) 4737 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 4738 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 4739 { return StmtVisitorTy::Visit(E->getResultExpr()); } 4740 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 4741 { return StmtVisitorTy::Visit(E->getReplacement()); } 4742 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 4743 TempVersionRAII RAII(*Info.CurrentCall); 4744 return StmtVisitorTy::Visit(E->getExpr()); 4745 } 4746 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 4747 TempVersionRAII RAII(*Info.CurrentCall); 4748 // The initializer may not have been parsed yet, or might be erroneous. 4749 if (!E->getExpr()) 4750 return Error(E); 4751 return StmtVisitorTy::Visit(E->getExpr()); 4752 } 4753 // We cannot create any objects for which cleanups are required, so there is 4754 // nothing to do here; all cleanups must come from unevaluated subexpressions. 4755 bool VisitExprWithCleanups(const ExprWithCleanups *E) 4756 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4757 4758 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 4759 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 4760 return static_cast<Derived*>(this)->VisitCastExpr(E); 4761 } 4762 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 4763 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 4764 return static_cast<Derived*>(this)->VisitCastExpr(E); 4765 } 4766 4767 bool VisitBinaryOperator(const BinaryOperator *E) { 4768 switch (E->getOpcode()) { 4769 default: 4770 return Error(E); 4771 4772 case BO_Comma: 4773 VisitIgnoredValue(E->getLHS()); 4774 return StmtVisitorTy::Visit(E->getRHS()); 4775 4776 case BO_PtrMemD: 4777 case BO_PtrMemI: { 4778 LValue Obj; 4779 if (!HandleMemberPointerAccess(Info, E, Obj)) 4780 return false; 4781 APValue Result; 4782 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 4783 return false; 4784 return DerivedSuccess(Result, E); 4785 } 4786 } 4787 } 4788 4789 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 4790 // Evaluate and cache the common expression. We treat it as a temporary, 4791 // even though it's not quite the same thing. 4792 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 4793 Info, E->getCommon())) 4794 return false; 4795 4796 return HandleConditionalOperator(E); 4797 } 4798 4799 bool VisitConditionalOperator(const ConditionalOperator *E) { 4800 bool IsBcpCall = false; 4801 // If the condition (ignoring parens) is a __builtin_constant_p call, 4802 // the result is a constant expression if it can be folded without 4803 // side-effects. This is an important GNU extension. See GCC PR38377 4804 // for discussion. 4805 if (const CallExpr *CallCE = 4806 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 4807 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 4808 IsBcpCall = true; 4809 4810 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 4811 // constant expression; we can't check whether it's potentially foldable. 4812 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 4813 return false; 4814 4815 FoldConstant Fold(Info, IsBcpCall); 4816 if (!HandleConditionalOperator(E)) { 4817 Fold.keepDiagnostics(); 4818 return false; 4819 } 4820 4821 return true; 4822 } 4823 4824 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 4825 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 4826 return DerivedSuccess(*Value, E); 4827 4828 const Expr *Source = E->getSourceExpr(); 4829 if (!Source) 4830 return Error(E); 4831 if (Source == E) { // sanity checking. 4832 assert(0 && "OpaqueValueExpr recursively refers to itself"); 4833 return Error(E); 4834 } 4835 return StmtVisitorTy::Visit(Source); 4836 } 4837 4838 bool VisitCallExpr(const CallExpr *E) { 4839 APValue Result; 4840 if (!handleCallExpr(E, Result, nullptr)) 4841 return false; 4842 return DerivedSuccess(Result, E); 4843 } 4844 4845 bool handleCallExpr(const CallExpr *E, APValue &Result, 4846 const LValue *ResultSlot) { 4847 const Expr *Callee = E->getCallee()->IgnoreParens(); 4848 QualType CalleeType = Callee->getType(); 4849 4850 const FunctionDecl *FD = nullptr; 4851 LValue *This = nullptr, ThisVal; 4852 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 4853 bool HasQualifier = false; 4854 4855 // Extract function decl and 'this' pointer from the callee. 4856 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 4857 const ValueDecl *Member = nullptr; 4858 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 4859 // Explicit bound member calls, such as x.f() or p->g(); 4860 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 4861 return false; 4862 Member = ME->getMemberDecl(); 4863 This = &ThisVal; 4864 HasQualifier = ME->hasQualifier(); 4865 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 4866 // Indirect bound member calls ('.*' or '->*'). 4867 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false); 4868 if (!Member) return false; 4869 This = &ThisVal; 4870 } else 4871 return Error(Callee); 4872 4873 FD = dyn_cast<FunctionDecl>(Member); 4874 if (!FD) 4875 return Error(Callee); 4876 } else if (CalleeType->isFunctionPointerType()) { 4877 LValue Call; 4878 if (!EvaluatePointer(Callee, Call, Info)) 4879 return false; 4880 4881 if (!Call.getLValueOffset().isZero()) 4882 return Error(Callee); 4883 FD = dyn_cast_or_null<FunctionDecl>( 4884 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 4885 if (!FD) 4886 return Error(Callee); 4887 // Don't call function pointers which have been cast to some other type. 4888 // Per DR (no number yet), the caller and callee can differ in noexcept. 4889 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 4890 CalleeType->getPointeeType(), FD->getType())) { 4891 return Error(E); 4892 } 4893 4894 // Overloaded operator calls to member functions are represented as normal 4895 // calls with '*this' as the first argument. 4896 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 4897 if (MD && !MD->isStatic()) { 4898 // FIXME: When selecting an implicit conversion for an overloaded 4899 // operator delete, we sometimes try to evaluate calls to conversion 4900 // operators without a 'this' parameter! 4901 if (Args.empty()) 4902 return Error(E); 4903 4904 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 4905 return false; 4906 This = &ThisVal; 4907 Args = Args.slice(1); 4908 } else if (MD && MD->isLambdaStaticInvoker()) { 4909 // Map the static invoker for the lambda back to the call operator. 4910 // Conveniently, we don't have to slice out the 'this' argument (as is 4911 // being done for the non-static case), since a static member function 4912 // doesn't have an implicit argument passed in. 4913 const CXXRecordDecl *ClosureClass = MD->getParent(); 4914 assert( 4915 ClosureClass->captures_begin() == ClosureClass->captures_end() && 4916 "Number of captures must be zero for conversion to function-ptr"); 4917 4918 const CXXMethodDecl *LambdaCallOp = 4919 ClosureClass->getLambdaCallOperator(); 4920 4921 // Set 'FD', the function that will be called below, to the call 4922 // operator. If the closure object represents a generic lambda, find 4923 // the corresponding specialization of the call operator. 4924 4925 if (ClosureClass->isGenericLambda()) { 4926 assert(MD->isFunctionTemplateSpecialization() && 4927 "A generic lambda's static-invoker function must be a " 4928 "template specialization"); 4929 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 4930 FunctionTemplateDecl *CallOpTemplate = 4931 LambdaCallOp->getDescribedFunctionTemplate(); 4932 void *InsertPos = nullptr; 4933 FunctionDecl *CorrespondingCallOpSpecialization = 4934 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 4935 assert(CorrespondingCallOpSpecialization && 4936 "We must always have a function call operator specialization " 4937 "that corresponds to our static invoker specialization"); 4938 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 4939 } else 4940 FD = LambdaCallOp; 4941 } 4942 4943 4944 } else 4945 return Error(E); 4946 4947 if (This && !This->checkSubobject(Info, E, CSK_This)) 4948 return false; 4949 4950 // DR1358 allows virtual constexpr functions in some cases. Don't allow 4951 // calls to such functions in constant expressions. 4952 if (This && !HasQualifier && 4953 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual()) 4954 return Error(E, diag::note_constexpr_virtual_call); 4955 4956 const FunctionDecl *Definition = nullptr; 4957 Stmt *Body = FD->getBody(Definition); 4958 4959 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 4960 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 4961 Result, ResultSlot)) 4962 return false; 4963 4964 return true; 4965 } 4966 4967 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 4968 return StmtVisitorTy::Visit(E->getInitializer()); 4969 } 4970 bool VisitInitListExpr(const InitListExpr *E) { 4971 if (E->getNumInits() == 0) 4972 return DerivedZeroInitialization(E); 4973 if (E->getNumInits() == 1) 4974 return StmtVisitorTy::Visit(E->getInit(0)); 4975 return Error(E); 4976 } 4977 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 4978 return DerivedZeroInitialization(E); 4979 } 4980 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 4981 return DerivedZeroInitialization(E); 4982 } 4983 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 4984 return DerivedZeroInitialization(E); 4985 } 4986 4987 /// A member expression where the object is a prvalue is itself a prvalue. 4988 bool VisitMemberExpr(const MemberExpr *E) { 4989 assert(!E->isArrow() && "missing call to bound member function?"); 4990 4991 APValue Val; 4992 if (!Evaluate(Val, Info, E->getBase())) 4993 return false; 4994 4995 QualType BaseTy = E->getBase()->getType(); 4996 4997 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 4998 if (!FD) return Error(E); 4999 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 5000 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 5001 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 5002 5003 CompleteObject Obj(&Val, BaseTy, true); 5004 SubobjectDesignator Designator(BaseTy); 5005 Designator.addDeclUnchecked(FD); 5006 5007 APValue Result; 5008 return extractSubobject(Info, E, Obj, Designator, Result) && 5009 DerivedSuccess(Result, E); 5010 } 5011 5012 bool VisitCastExpr(const CastExpr *E) { 5013 switch (E->getCastKind()) { 5014 default: 5015 break; 5016 5017 case CK_AtomicToNonAtomic: { 5018 APValue AtomicVal; 5019 // This does not need to be done in place even for class/array types: 5020 // atomic-to-non-atomic conversion implies copying the object 5021 // representation. 5022 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 5023 return false; 5024 return DerivedSuccess(AtomicVal, E); 5025 } 5026 5027 case CK_NoOp: 5028 case CK_UserDefinedConversion: 5029 return StmtVisitorTy::Visit(E->getSubExpr()); 5030 5031 case CK_LValueToRValue: { 5032 LValue LVal; 5033 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 5034 return false; 5035 APValue RVal; 5036 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5037 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5038 LVal, RVal)) 5039 return false; 5040 return DerivedSuccess(RVal, E); 5041 } 5042 } 5043 5044 return Error(E); 5045 } 5046 5047 bool VisitUnaryPostInc(const UnaryOperator *UO) { 5048 return VisitUnaryPostIncDec(UO); 5049 } 5050 bool VisitUnaryPostDec(const UnaryOperator *UO) { 5051 return VisitUnaryPostIncDec(UO); 5052 } 5053 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 5054 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5055 return Error(UO); 5056 5057 LValue LVal; 5058 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 5059 return false; 5060 APValue RVal; 5061 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 5062 UO->isIncrementOp(), &RVal)) 5063 return false; 5064 return DerivedSuccess(RVal, UO); 5065 } 5066 5067 bool VisitStmtExpr(const StmtExpr *E) { 5068 // We will have checked the full-expressions inside the statement expression 5069 // when they were completed, and don't need to check them again now. 5070 if (Info.checkingForOverflow()) 5071 return Error(E); 5072 5073 BlockScopeRAII Scope(Info); 5074 const CompoundStmt *CS = E->getSubStmt(); 5075 if (CS->body_empty()) 5076 return true; 5077 5078 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 5079 BE = CS->body_end(); 5080 /**/; ++BI) { 5081 if (BI + 1 == BE) { 5082 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 5083 if (!FinalExpr) { 5084 Info.FFDiag((*BI)->getBeginLoc(), 5085 diag::note_constexpr_stmt_expr_unsupported); 5086 return false; 5087 } 5088 return this->Visit(FinalExpr); 5089 } 5090 5091 APValue ReturnValue; 5092 StmtResult Result = { ReturnValue, nullptr }; 5093 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 5094 if (ESR != ESR_Succeeded) { 5095 // FIXME: If the statement-expression terminated due to 'return', 5096 // 'break', or 'continue', it would be nice to propagate that to 5097 // the outer statement evaluation rather than bailing out. 5098 if (ESR != ESR_Failed) 5099 Info.FFDiag((*BI)->getBeginLoc(), 5100 diag::note_constexpr_stmt_expr_unsupported); 5101 return false; 5102 } 5103 } 5104 5105 llvm_unreachable("Return from function from the loop above."); 5106 } 5107 5108 /// Visit a value which is evaluated, but whose value is ignored. 5109 void VisitIgnoredValue(const Expr *E) { 5110 EvaluateIgnoredValue(Info, E); 5111 } 5112 5113 /// Potentially visit a MemberExpr's base expression. 5114 void VisitIgnoredBaseExpression(const Expr *E) { 5115 // While MSVC doesn't evaluate the base expression, it does diagnose the 5116 // presence of side-effecting behavior. 5117 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 5118 return; 5119 VisitIgnoredValue(E); 5120 } 5121 }; 5122 5123 } // namespace 5124 5125 //===----------------------------------------------------------------------===// 5126 // Common base class for lvalue and temporary evaluation. 5127 //===----------------------------------------------------------------------===// 5128 namespace { 5129 template<class Derived> 5130 class LValueExprEvaluatorBase 5131 : public ExprEvaluatorBase<Derived> { 5132 protected: 5133 LValue &Result; 5134 bool InvalidBaseOK; 5135 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 5136 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 5137 5138 bool Success(APValue::LValueBase B) { 5139 Result.set(B); 5140 return true; 5141 } 5142 5143 bool evaluatePointer(const Expr *E, LValue &Result) { 5144 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 5145 } 5146 5147 public: 5148 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 5149 : ExprEvaluatorBaseTy(Info), Result(Result), 5150 InvalidBaseOK(InvalidBaseOK) {} 5151 5152 bool Success(const APValue &V, const Expr *E) { 5153 Result.setFrom(this->Info.Ctx, V); 5154 return true; 5155 } 5156 5157 bool VisitMemberExpr(const MemberExpr *E) { 5158 // Handle non-static data members. 5159 QualType BaseTy; 5160 bool EvalOK; 5161 if (E->isArrow()) { 5162 EvalOK = evaluatePointer(E->getBase(), Result); 5163 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 5164 } else if (E->getBase()->isRValue()) { 5165 assert(E->getBase()->getType()->isRecordType()); 5166 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 5167 BaseTy = E->getBase()->getType(); 5168 } else { 5169 EvalOK = this->Visit(E->getBase()); 5170 BaseTy = E->getBase()->getType(); 5171 } 5172 if (!EvalOK) { 5173 if (!InvalidBaseOK) 5174 return false; 5175 Result.setInvalid(E); 5176 return true; 5177 } 5178 5179 const ValueDecl *MD = E->getMemberDecl(); 5180 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 5181 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 5182 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 5183 (void)BaseTy; 5184 if (!HandleLValueMember(this->Info, E, Result, FD)) 5185 return false; 5186 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 5187 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 5188 return false; 5189 } else 5190 return this->Error(E); 5191 5192 if (MD->getType()->isReferenceType()) { 5193 APValue RefValue; 5194 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 5195 RefValue)) 5196 return false; 5197 return Success(RefValue, E); 5198 } 5199 return true; 5200 } 5201 5202 bool VisitBinaryOperator(const BinaryOperator *E) { 5203 switch (E->getOpcode()) { 5204 default: 5205 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5206 5207 case BO_PtrMemD: 5208 case BO_PtrMemI: 5209 return HandleMemberPointerAccess(this->Info, E, Result); 5210 } 5211 } 5212 5213 bool VisitCastExpr(const CastExpr *E) { 5214 switch (E->getCastKind()) { 5215 default: 5216 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5217 5218 case CK_DerivedToBase: 5219 case CK_UncheckedDerivedToBase: 5220 if (!this->Visit(E->getSubExpr())) 5221 return false; 5222 5223 // Now figure out the necessary offset to add to the base LV to get from 5224 // the derived class to the base class. 5225 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 5226 Result); 5227 } 5228 } 5229 }; 5230 } 5231 5232 //===----------------------------------------------------------------------===// 5233 // LValue Evaluation 5234 // 5235 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 5236 // function designators (in C), decl references to void objects (in C), and 5237 // temporaries (if building with -Wno-address-of-temporary). 5238 // 5239 // LValue evaluation produces values comprising a base expression of one of the 5240 // following types: 5241 // - Declarations 5242 // * VarDecl 5243 // * FunctionDecl 5244 // - Literals 5245 // * CompoundLiteralExpr in C (and in global scope in C++) 5246 // * StringLiteral 5247 // * CXXTypeidExpr 5248 // * PredefinedExpr 5249 // * ObjCStringLiteralExpr 5250 // * ObjCEncodeExpr 5251 // * AddrLabelExpr 5252 // * BlockExpr 5253 // * CallExpr for a MakeStringConstant builtin 5254 // - Locals and temporaries 5255 // * MaterializeTemporaryExpr 5256 // * Any Expr, with a CallIndex indicating the function in which the temporary 5257 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 5258 // from the AST (FIXME). 5259 // * A MaterializeTemporaryExpr that has static storage duration, with no 5260 // CallIndex, for a lifetime-extended temporary. 5261 // plus an offset in bytes. 5262 //===----------------------------------------------------------------------===// 5263 namespace { 5264 class LValueExprEvaluator 5265 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 5266 public: 5267 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 5268 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 5269 5270 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 5271 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 5272 5273 bool VisitDeclRefExpr(const DeclRefExpr *E); 5274 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 5275 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 5276 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 5277 bool VisitMemberExpr(const MemberExpr *E); 5278 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 5279 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 5280 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 5281 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 5282 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 5283 bool VisitUnaryDeref(const UnaryOperator *E); 5284 bool VisitUnaryReal(const UnaryOperator *E); 5285 bool VisitUnaryImag(const UnaryOperator *E); 5286 bool VisitUnaryPreInc(const UnaryOperator *UO) { 5287 return VisitUnaryPreIncDec(UO); 5288 } 5289 bool VisitUnaryPreDec(const UnaryOperator *UO) { 5290 return VisitUnaryPreIncDec(UO); 5291 } 5292 bool VisitBinAssign(const BinaryOperator *BO); 5293 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 5294 5295 bool VisitCastExpr(const CastExpr *E) { 5296 switch (E->getCastKind()) { 5297 default: 5298 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 5299 5300 case CK_LValueBitCast: 5301 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5302 if (!Visit(E->getSubExpr())) 5303 return false; 5304 Result.Designator.setInvalid(); 5305 return true; 5306 5307 case CK_BaseToDerived: 5308 if (!Visit(E->getSubExpr())) 5309 return false; 5310 return HandleBaseToDerivedCast(Info, E, Result); 5311 } 5312 } 5313 }; 5314 } // end anonymous namespace 5315 5316 /// Evaluate an expression as an lvalue. This can be legitimately called on 5317 /// expressions which are not glvalues, in three cases: 5318 /// * function designators in C, and 5319 /// * "extern void" objects 5320 /// * @selector() expressions in Objective-C 5321 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 5322 bool InvalidBaseOK) { 5323 assert(E->isGLValue() || E->getType()->isFunctionType() || 5324 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 5325 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5326 } 5327 5328 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 5329 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 5330 return Success(FD); 5331 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 5332 return VisitVarDecl(E, VD); 5333 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 5334 return Visit(BD->getBinding()); 5335 return Error(E); 5336 } 5337 5338 5339 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 5340 5341 // If we are within a lambda's call operator, check whether the 'VD' referred 5342 // to within 'E' actually represents a lambda-capture that maps to a 5343 // data-member/field within the closure object, and if so, evaluate to the 5344 // field or what the field refers to. 5345 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 5346 isa<DeclRefExpr>(E) && 5347 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 5348 // We don't always have a complete capture-map when checking or inferring if 5349 // the function call operator meets the requirements of a constexpr function 5350 // - but we don't need to evaluate the captures to determine constexprness 5351 // (dcl.constexpr C++17). 5352 if (Info.checkingPotentialConstantExpression()) 5353 return false; 5354 5355 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 5356 // Start with 'Result' referring to the complete closure object... 5357 Result = *Info.CurrentCall->This; 5358 // ... then update it to refer to the field of the closure object 5359 // that represents the capture. 5360 if (!HandleLValueMember(Info, E, Result, FD)) 5361 return false; 5362 // And if the field is of reference type, update 'Result' to refer to what 5363 // the field refers to. 5364 if (FD->getType()->isReferenceType()) { 5365 APValue RVal; 5366 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 5367 RVal)) 5368 return false; 5369 Result.setFrom(Info.Ctx, RVal); 5370 } 5371 return true; 5372 } 5373 } 5374 CallStackFrame *Frame = nullptr; 5375 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 5376 // Only if a local variable was declared in the function currently being 5377 // evaluated, do we expect to be able to find its value in the current 5378 // frame. (Otherwise it was likely declared in an enclosing context and 5379 // could either have a valid evaluatable value (for e.g. a constexpr 5380 // variable) or be ill-formed (and trigger an appropriate evaluation 5381 // diagnostic)). 5382 if (Info.CurrentCall->Callee && 5383 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 5384 Frame = Info.CurrentCall; 5385 } 5386 } 5387 5388 if (!VD->getType()->isReferenceType()) { 5389 if (Frame) { 5390 Result.set({VD, Frame->Index, 5391 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 5392 return true; 5393 } 5394 return Success(VD); 5395 } 5396 5397 APValue *V; 5398 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 5399 return false; 5400 if (V->isUninit()) { 5401 if (!Info.checkingPotentialConstantExpression()) 5402 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 5403 return false; 5404 } 5405 return Success(*V, E); 5406 } 5407 5408 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 5409 const MaterializeTemporaryExpr *E) { 5410 // Walk through the expression to find the materialized temporary itself. 5411 SmallVector<const Expr *, 2> CommaLHSs; 5412 SmallVector<SubobjectAdjustment, 2> Adjustments; 5413 const Expr *Inner = E->GetTemporaryExpr()-> 5414 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 5415 5416 // If we passed any comma operators, evaluate their LHSs. 5417 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 5418 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 5419 return false; 5420 5421 // A materialized temporary with static storage duration can appear within the 5422 // result of a constant expression evaluation, so we need to preserve its 5423 // value for use outside this evaluation. 5424 APValue *Value; 5425 if (E->getStorageDuration() == SD_Static) { 5426 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 5427 *Value = APValue(); 5428 Result.set(E); 5429 } else { 5430 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result, 5431 *Info.CurrentCall); 5432 } 5433 5434 QualType Type = Inner->getType(); 5435 5436 // Materialize the temporary itself. 5437 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 5438 (E->getStorageDuration() == SD_Static && 5439 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 5440 *Value = APValue(); 5441 return false; 5442 } 5443 5444 // Adjust our lvalue to refer to the desired subobject. 5445 for (unsigned I = Adjustments.size(); I != 0; /**/) { 5446 --I; 5447 switch (Adjustments[I].Kind) { 5448 case SubobjectAdjustment::DerivedToBaseAdjustment: 5449 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 5450 Type, Result)) 5451 return false; 5452 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 5453 break; 5454 5455 case SubobjectAdjustment::FieldAdjustment: 5456 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 5457 return false; 5458 Type = Adjustments[I].Field->getType(); 5459 break; 5460 5461 case SubobjectAdjustment::MemberPointerAdjustment: 5462 if (!HandleMemberPointerAccess(this->Info, Type, Result, 5463 Adjustments[I].Ptr.RHS)) 5464 return false; 5465 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 5466 break; 5467 } 5468 } 5469 5470 return true; 5471 } 5472 5473 bool 5474 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 5475 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 5476 "lvalue compound literal in c++?"); 5477 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 5478 // only see this when folding in C, so there's no standard to follow here. 5479 return Success(E); 5480 } 5481 5482 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 5483 if (!E->isPotentiallyEvaluated()) 5484 return Success(E); 5485 5486 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic) 5487 << E->getExprOperand()->getType() 5488 << E->getExprOperand()->getSourceRange(); 5489 return false; 5490 } 5491 5492 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 5493 return Success(E); 5494 } 5495 5496 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 5497 // Handle static data members. 5498 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 5499 VisitIgnoredBaseExpression(E->getBase()); 5500 return VisitVarDecl(E, VD); 5501 } 5502 5503 // Handle static member functions. 5504 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 5505 if (MD->isStatic()) { 5506 VisitIgnoredBaseExpression(E->getBase()); 5507 return Success(MD); 5508 } 5509 } 5510 5511 // Handle non-static data members. 5512 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 5513 } 5514 5515 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 5516 // FIXME: Deal with vectors as array subscript bases. 5517 if (E->getBase()->getType()->isVectorType()) 5518 return Error(E); 5519 5520 bool Success = true; 5521 if (!evaluatePointer(E->getBase(), Result)) { 5522 if (!Info.noteFailure()) 5523 return false; 5524 Success = false; 5525 } 5526 5527 APSInt Index; 5528 if (!EvaluateInteger(E->getIdx(), Index, Info)) 5529 return false; 5530 5531 return Success && 5532 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 5533 } 5534 5535 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 5536 return evaluatePointer(E->getSubExpr(), Result); 5537 } 5538 5539 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 5540 if (!Visit(E->getSubExpr())) 5541 return false; 5542 // __real is a no-op on scalar lvalues. 5543 if (E->getSubExpr()->getType()->isAnyComplexType()) 5544 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 5545 return true; 5546 } 5547 5548 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 5549 assert(E->getSubExpr()->getType()->isAnyComplexType() && 5550 "lvalue __imag__ on scalar?"); 5551 if (!Visit(E->getSubExpr())) 5552 return false; 5553 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 5554 return true; 5555 } 5556 5557 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 5558 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5559 return Error(UO); 5560 5561 if (!this->Visit(UO->getSubExpr())) 5562 return false; 5563 5564 return handleIncDec( 5565 this->Info, UO, Result, UO->getSubExpr()->getType(), 5566 UO->isIncrementOp(), nullptr); 5567 } 5568 5569 bool LValueExprEvaluator::VisitCompoundAssignOperator( 5570 const CompoundAssignOperator *CAO) { 5571 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5572 return Error(CAO); 5573 5574 APValue RHS; 5575 5576 // The overall lvalue result is the result of evaluating the LHS. 5577 if (!this->Visit(CAO->getLHS())) { 5578 if (Info.noteFailure()) 5579 Evaluate(RHS, this->Info, CAO->getRHS()); 5580 return false; 5581 } 5582 5583 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 5584 return false; 5585 5586 return handleCompoundAssignment( 5587 this->Info, CAO, 5588 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 5589 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 5590 } 5591 5592 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 5593 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5594 return Error(E); 5595 5596 APValue NewVal; 5597 5598 if (!this->Visit(E->getLHS())) { 5599 if (Info.noteFailure()) 5600 Evaluate(NewVal, this->Info, E->getRHS()); 5601 return false; 5602 } 5603 5604 if (!Evaluate(NewVal, this->Info, E->getRHS())) 5605 return false; 5606 5607 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 5608 NewVal); 5609 } 5610 5611 //===----------------------------------------------------------------------===// 5612 // Pointer Evaluation 5613 //===----------------------------------------------------------------------===// 5614 5615 /// Attempts to compute the number of bytes available at the pointer 5616 /// returned by a function with the alloc_size attribute. Returns true if we 5617 /// were successful. Places an unsigned number into `Result`. 5618 /// 5619 /// This expects the given CallExpr to be a call to a function with an 5620 /// alloc_size attribute. 5621 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5622 const CallExpr *Call, 5623 llvm::APInt &Result) { 5624 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 5625 5626 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 5627 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 5628 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 5629 if (Call->getNumArgs() <= SizeArgNo) 5630 return false; 5631 5632 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 5633 Expr::EvalResult ExprResult; 5634 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 5635 return false; 5636 Into = ExprResult.Val.getInt(); 5637 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 5638 return false; 5639 Into = Into.zextOrSelf(BitsInSizeT); 5640 return true; 5641 }; 5642 5643 APSInt SizeOfElem; 5644 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 5645 return false; 5646 5647 if (!AllocSize->getNumElemsParam().isValid()) { 5648 Result = std::move(SizeOfElem); 5649 return true; 5650 } 5651 5652 APSInt NumberOfElems; 5653 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 5654 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 5655 return false; 5656 5657 bool Overflow; 5658 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 5659 if (Overflow) 5660 return false; 5661 5662 Result = std::move(BytesAvailable); 5663 return true; 5664 } 5665 5666 /// Convenience function. LVal's base must be a call to an alloc_size 5667 /// function. 5668 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5669 const LValue &LVal, 5670 llvm::APInt &Result) { 5671 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 5672 "Can't get the size of a non alloc_size function"); 5673 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 5674 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 5675 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 5676 } 5677 5678 /// Attempts to evaluate the given LValueBase as the result of a call to 5679 /// a function with the alloc_size attribute. If it was possible to do so, this 5680 /// function will return true, make Result's Base point to said function call, 5681 /// and mark Result's Base as invalid. 5682 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 5683 LValue &Result) { 5684 if (Base.isNull()) 5685 return false; 5686 5687 // Because we do no form of static analysis, we only support const variables. 5688 // 5689 // Additionally, we can't support parameters, nor can we support static 5690 // variables (in the latter case, use-before-assign isn't UB; in the former, 5691 // we have no clue what they'll be assigned to). 5692 const auto *VD = 5693 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 5694 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 5695 return false; 5696 5697 const Expr *Init = VD->getAnyInitializer(); 5698 if (!Init) 5699 return false; 5700 5701 const Expr *E = Init->IgnoreParens(); 5702 if (!tryUnwrapAllocSizeCall(E)) 5703 return false; 5704 5705 // Store E instead of E unwrapped so that the type of the LValue's base is 5706 // what the user wanted. 5707 Result.setInvalid(E); 5708 5709 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 5710 Result.addUnsizedArray(Info, E, Pointee); 5711 return true; 5712 } 5713 5714 namespace { 5715 class PointerExprEvaluator 5716 : public ExprEvaluatorBase<PointerExprEvaluator> { 5717 LValue &Result; 5718 bool InvalidBaseOK; 5719 5720 bool Success(const Expr *E) { 5721 Result.set(E); 5722 return true; 5723 } 5724 5725 bool evaluateLValue(const Expr *E, LValue &Result) { 5726 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 5727 } 5728 5729 bool evaluatePointer(const Expr *E, LValue &Result) { 5730 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 5731 } 5732 5733 bool visitNonBuiltinCallExpr(const CallExpr *E); 5734 public: 5735 5736 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 5737 : ExprEvaluatorBaseTy(info), Result(Result), 5738 InvalidBaseOK(InvalidBaseOK) {} 5739 5740 bool Success(const APValue &V, const Expr *E) { 5741 Result.setFrom(Info.Ctx, V); 5742 return true; 5743 } 5744 bool ZeroInitialization(const Expr *E) { 5745 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 5746 Result.setNull(E->getType(), TargetVal); 5747 return true; 5748 } 5749 5750 bool VisitBinaryOperator(const BinaryOperator *E); 5751 bool VisitCastExpr(const CastExpr* E); 5752 bool VisitUnaryAddrOf(const UnaryOperator *E); 5753 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 5754 { return Success(E); } 5755 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 5756 if (Info.noteFailure()) 5757 EvaluateIgnoredValue(Info, E->getSubExpr()); 5758 return Error(E); 5759 } 5760 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 5761 { return Success(E); } 5762 bool VisitCallExpr(const CallExpr *E); 5763 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 5764 bool VisitBlockExpr(const BlockExpr *E) { 5765 if (!E->getBlockDecl()->hasCaptures()) 5766 return Success(E); 5767 return Error(E); 5768 } 5769 bool VisitCXXThisExpr(const CXXThisExpr *E) { 5770 // Can't look at 'this' when checking a potential constant expression. 5771 if (Info.checkingPotentialConstantExpression()) 5772 return false; 5773 if (!Info.CurrentCall->This) { 5774 if (Info.getLangOpts().CPlusPlus11) 5775 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 5776 else 5777 Info.FFDiag(E); 5778 return false; 5779 } 5780 Result = *Info.CurrentCall->This; 5781 // If we are inside a lambda's call operator, the 'this' expression refers 5782 // to the enclosing '*this' object (either by value or reference) which is 5783 // either copied into the closure object's field that represents the '*this' 5784 // or refers to '*this'. 5785 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 5786 // Update 'Result' to refer to the data member/field of the closure object 5787 // that represents the '*this' capture. 5788 if (!HandleLValueMember(Info, E, Result, 5789 Info.CurrentCall->LambdaThisCaptureField)) 5790 return false; 5791 // If we captured '*this' by reference, replace the field with its referent. 5792 if (Info.CurrentCall->LambdaThisCaptureField->getType() 5793 ->isPointerType()) { 5794 APValue RVal; 5795 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 5796 RVal)) 5797 return false; 5798 5799 Result.setFrom(Info.Ctx, RVal); 5800 } 5801 } 5802 return true; 5803 } 5804 5805 // FIXME: Missing: @protocol, @selector 5806 }; 5807 } // end anonymous namespace 5808 5809 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 5810 bool InvalidBaseOK) { 5811 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 5812 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5813 } 5814 5815 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 5816 if (E->getOpcode() != BO_Add && 5817 E->getOpcode() != BO_Sub) 5818 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5819 5820 const Expr *PExp = E->getLHS(); 5821 const Expr *IExp = E->getRHS(); 5822 if (IExp->getType()->isPointerType()) 5823 std::swap(PExp, IExp); 5824 5825 bool EvalPtrOK = evaluatePointer(PExp, Result); 5826 if (!EvalPtrOK && !Info.noteFailure()) 5827 return false; 5828 5829 llvm::APSInt Offset; 5830 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 5831 return false; 5832 5833 if (E->getOpcode() == BO_Sub) 5834 negateAsSigned(Offset); 5835 5836 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 5837 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 5838 } 5839 5840 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 5841 return evaluateLValue(E->getSubExpr(), Result); 5842 } 5843 5844 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 5845 const Expr *SubExpr = E->getSubExpr(); 5846 5847 switch (E->getCastKind()) { 5848 default: 5849 break; 5850 5851 case CK_BitCast: 5852 case CK_CPointerToObjCPointerCast: 5853 case CK_BlockPointerToObjCPointerCast: 5854 case CK_AnyPointerToBlockPointerCast: 5855 case CK_AddressSpaceConversion: 5856 if (!Visit(SubExpr)) 5857 return false; 5858 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 5859 // permitted in constant expressions in C++11. Bitcasts from cv void* are 5860 // also static_casts, but we disallow them as a resolution to DR1312. 5861 if (!E->getType()->isVoidPointerType()) { 5862 Result.Designator.setInvalid(); 5863 if (SubExpr->getType()->isVoidPointerType()) 5864 CCEDiag(E, diag::note_constexpr_invalid_cast) 5865 << 3 << SubExpr->getType(); 5866 else 5867 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5868 } 5869 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 5870 ZeroInitialization(E); 5871 return true; 5872 5873 case CK_DerivedToBase: 5874 case CK_UncheckedDerivedToBase: 5875 if (!evaluatePointer(E->getSubExpr(), Result)) 5876 return false; 5877 if (!Result.Base && Result.Offset.isZero()) 5878 return true; 5879 5880 // Now figure out the necessary offset to add to the base LV to get from 5881 // the derived class to the base class. 5882 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 5883 castAs<PointerType>()->getPointeeType(), 5884 Result); 5885 5886 case CK_BaseToDerived: 5887 if (!Visit(E->getSubExpr())) 5888 return false; 5889 if (!Result.Base && Result.Offset.isZero()) 5890 return true; 5891 return HandleBaseToDerivedCast(Info, E, Result); 5892 5893 case CK_NullToPointer: 5894 VisitIgnoredValue(E->getSubExpr()); 5895 return ZeroInitialization(E); 5896 5897 case CK_IntegralToPointer: { 5898 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5899 5900 APValue Value; 5901 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 5902 break; 5903 5904 if (Value.isInt()) { 5905 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 5906 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 5907 Result.Base = (Expr*)nullptr; 5908 Result.InvalidBase = false; 5909 Result.Offset = CharUnits::fromQuantity(N); 5910 Result.Designator.setInvalid(); 5911 Result.IsNullPtr = false; 5912 return true; 5913 } else { 5914 // Cast is of an lvalue, no need to change value. 5915 Result.setFrom(Info.Ctx, Value); 5916 return true; 5917 } 5918 } 5919 5920 case CK_ArrayToPointerDecay: { 5921 if (SubExpr->isGLValue()) { 5922 if (!evaluateLValue(SubExpr, Result)) 5923 return false; 5924 } else { 5925 APValue &Value = createTemporary(SubExpr, false, Result, 5926 *Info.CurrentCall); 5927 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 5928 return false; 5929 } 5930 // The result is a pointer to the first element of the array. 5931 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 5932 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 5933 Result.addArray(Info, E, CAT); 5934 else 5935 Result.addUnsizedArray(Info, E, AT->getElementType()); 5936 return true; 5937 } 5938 5939 case CK_FunctionToPointerDecay: 5940 return evaluateLValue(SubExpr, Result); 5941 5942 case CK_LValueToRValue: { 5943 LValue LVal; 5944 if (!evaluateLValue(E->getSubExpr(), LVal)) 5945 return false; 5946 5947 APValue RVal; 5948 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5949 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5950 LVal, RVal)) 5951 return InvalidBaseOK && 5952 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 5953 return Success(RVal, E); 5954 } 5955 } 5956 5957 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5958 } 5959 5960 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 5961 UnaryExprOrTypeTrait ExprKind) { 5962 // C++ [expr.alignof]p3: 5963 // When alignof is applied to a reference type, the result is the 5964 // alignment of the referenced type. 5965 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 5966 T = Ref->getPointeeType(); 5967 5968 if (T.getQualifiers().hasUnaligned()) 5969 return CharUnits::One(); 5970 5971 const bool AlignOfReturnsPreferred = 5972 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 5973 5974 // __alignof is defined to return the preferred alignment. 5975 // Before 8, clang returned the preferred alignment for alignof and _Alignof 5976 // as well. 5977 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 5978 return Info.Ctx.toCharUnitsFromBits( 5979 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 5980 // alignof and _Alignof are defined to return the ABI alignment. 5981 else if (ExprKind == UETT_AlignOf) 5982 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 5983 else 5984 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 5985 } 5986 5987 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 5988 UnaryExprOrTypeTrait ExprKind) { 5989 E = E->IgnoreParens(); 5990 5991 // The kinds of expressions that we have special-case logic here for 5992 // should be kept up to date with the special checks for those 5993 // expressions in Sema. 5994 5995 // alignof decl is always accepted, even if it doesn't make sense: we default 5996 // to 1 in those cases. 5997 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5998 return Info.Ctx.getDeclAlign(DRE->getDecl(), 5999 /*RefAsPointee*/true); 6000 6001 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 6002 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 6003 /*RefAsPointee*/true); 6004 6005 return GetAlignOfType(Info, E->getType(), ExprKind); 6006 } 6007 6008 // To be clear: this happily visits unsupported builtins. Better name welcomed. 6009 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 6010 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 6011 return true; 6012 6013 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 6014 return false; 6015 6016 Result.setInvalid(E); 6017 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 6018 Result.addUnsizedArray(Info, E, PointeeTy); 6019 return true; 6020 } 6021 6022 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 6023 if (IsStringLiteralCall(E)) 6024 return Success(E); 6025 6026 if (unsigned BuiltinOp = E->getBuiltinCallee()) 6027 return VisitBuiltinCallExpr(E, BuiltinOp); 6028 6029 return visitNonBuiltinCallExpr(E); 6030 } 6031 6032 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 6033 unsigned BuiltinOp) { 6034 switch (BuiltinOp) { 6035 case Builtin::BI__builtin_addressof: 6036 return evaluateLValue(E->getArg(0), Result); 6037 case Builtin::BI__builtin_assume_aligned: { 6038 // We need to be very careful here because: if the pointer does not have the 6039 // asserted alignment, then the behavior is undefined, and undefined 6040 // behavior is non-constant. 6041 if (!evaluatePointer(E->getArg(0), Result)) 6042 return false; 6043 6044 LValue OffsetResult(Result); 6045 APSInt Alignment; 6046 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 6047 return false; 6048 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 6049 6050 if (E->getNumArgs() > 2) { 6051 APSInt Offset; 6052 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 6053 return false; 6054 6055 int64_t AdditionalOffset = -Offset.getZExtValue(); 6056 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 6057 } 6058 6059 // If there is a base object, then it must have the correct alignment. 6060 if (OffsetResult.Base) { 6061 CharUnits BaseAlignment; 6062 if (const ValueDecl *VD = 6063 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 6064 BaseAlignment = Info.Ctx.getDeclAlign(VD); 6065 } else { 6066 BaseAlignment = GetAlignOfExpr( 6067 Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf); 6068 } 6069 6070 if (BaseAlignment < Align) { 6071 Result.Designator.setInvalid(); 6072 // FIXME: Add support to Diagnostic for long / long long. 6073 CCEDiag(E->getArg(0), 6074 diag::note_constexpr_baa_insufficient_alignment) << 0 6075 << (unsigned)BaseAlignment.getQuantity() 6076 << (unsigned)Align.getQuantity(); 6077 return false; 6078 } 6079 } 6080 6081 // The offset must also have the correct alignment. 6082 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 6083 Result.Designator.setInvalid(); 6084 6085 (OffsetResult.Base 6086 ? CCEDiag(E->getArg(0), 6087 diag::note_constexpr_baa_insufficient_alignment) << 1 6088 : CCEDiag(E->getArg(0), 6089 diag::note_constexpr_baa_value_insufficient_alignment)) 6090 << (int)OffsetResult.Offset.getQuantity() 6091 << (unsigned)Align.getQuantity(); 6092 return false; 6093 } 6094 6095 return true; 6096 } 6097 6098 case Builtin::BIstrchr: 6099 case Builtin::BIwcschr: 6100 case Builtin::BImemchr: 6101 case Builtin::BIwmemchr: 6102 if (Info.getLangOpts().CPlusPlus11) 6103 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6104 << /*isConstexpr*/0 << /*isConstructor*/0 6105 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 6106 else 6107 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6108 LLVM_FALLTHROUGH; 6109 case Builtin::BI__builtin_strchr: 6110 case Builtin::BI__builtin_wcschr: 6111 case Builtin::BI__builtin_memchr: 6112 case Builtin::BI__builtin_char_memchr: 6113 case Builtin::BI__builtin_wmemchr: { 6114 if (!Visit(E->getArg(0))) 6115 return false; 6116 APSInt Desired; 6117 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 6118 return false; 6119 uint64_t MaxLength = uint64_t(-1); 6120 if (BuiltinOp != Builtin::BIstrchr && 6121 BuiltinOp != Builtin::BIwcschr && 6122 BuiltinOp != Builtin::BI__builtin_strchr && 6123 BuiltinOp != Builtin::BI__builtin_wcschr) { 6124 APSInt N; 6125 if (!EvaluateInteger(E->getArg(2), N, Info)) 6126 return false; 6127 MaxLength = N.getExtValue(); 6128 } 6129 6130 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 6131 6132 // Figure out what value we're actually looking for (after converting to 6133 // the corresponding unsigned type if necessary). 6134 uint64_t DesiredVal; 6135 bool StopAtNull = false; 6136 switch (BuiltinOp) { 6137 case Builtin::BIstrchr: 6138 case Builtin::BI__builtin_strchr: 6139 // strchr compares directly to the passed integer, and therefore 6140 // always fails if given an int that is not a char. 6141 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 6142 E->getArg(1)->getType(), 6143 Desired), 6144 Desired)) 6145 return ZeroInitialization(E); 6146 StopAtNull = true; 6147 LLVM_FALLTHROUGH; 6148 case Builtin::BImemchr: 6149 case Builtin::BI__builtin_memchr: 6150 case Builtin::BI__builtin_char_memchr: 6151 // memchr compares by converting both sides to unsigned char. That's also 6152 // correct for strchr if we get this far (to cope with plain char being 6153 // unsigned in the strchr case). 6154 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 6155 break; 6156 6157 case Builtin::BIwcschr: 6158 case Builtin::BI__builtin_wcschr: 6159 StopAtNull = true; 6160 LLVM_FALLTHROUGH; 6161 case Builtin::BIwmemchr: 6162 case Builtin::BI__builtin_wmemchr: 6163 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 6164 DesiredVal = Desired.getZExtValue(); 6165 break; 6166 } 6167 6168 for (; MaxLength; --MaxLength) { 6169 APValue Char; 6170 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 6171 !Char.isInt()) 6172 return false; 6173 if (Char.getInt().getZExtValue() == DesiredVal) 6174 return true; 6175 if (StopAtNull && !Char.getInt()) 6176 break; 6177 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 6178 return false; 6179 } 6180 // Not found: return nullptr. 6181 return ZeroInitialization(E); 6182 } 6183 6184 case Builtin::BImemcpy: 6185 case Builtin::BImemmove: 6186 case Builtin::BIwmemcpy: 6187 case Builtin::BIwmemmove: 6188 if (Info.getLangOpts().CPlusPlus11) 6189 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6190 << /*isConstexpr*/0 << /*isConstructor*/0 6191 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 6192 else 6193 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6194 LLVM_FALLTHROUGH; 6195 case Builtin::BI__builtin_memcpy: 6196 case Builtin::BI__builtin_memmove: 6197 case Builtin::BI__builtin_wmemcpy: 6198 case Builtin::BI__builtin_wmemmove: { 6199 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 6200 BuiltinOp == Builtin::BIwmemmove || 6201 BuiltinOp == Builtin::BI__builtin_wmemcpy || 6202 BuiltinOp == Builtin::BI__builtin_wmemmove; 6203 bool Move = BuiltinOp == Builtin::BImemmove || 6204 BuiltinOp == Builtin::BIwmemmove || 6205 BuiltinOp == Builtin::BI__builtin_memmove || 6206 BuiltinOp == Builtin::BI__builtin_wmemmove; 6207 6208 // The result of mem* is the first argument. 6209 if (!Visit(E->getArg(0))) 6210 return false; 6211 LValue Dest = Result; 6212 6213 LValue Src; 6214 if (!EvaluatePointer(E->getArg(1), Src, Info)) 6215 return false; 6216 6217 APSInt N; 6218 if (!EvaluateInteger(E->getArg(2), N, Info)) 6219 return false; 6220 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 6221 6222 // If the size is zero, we treat this as always being a valid no-op. 6223 // (Even if one of the src and dest pointers is null.) 6224 if (!N) 6225 return true; 6226 6227 // Otherwise, if either of the operands is null, we can't proceed. Don't 6228 // try to determine the type of the copied objects, because there aren't 6229 // any. 6230 if (!Src.Base || !Dest.Base) { 6231 APValue Val; 6232 (!Src.Base ? Src : Dest).moveInto(Val); 6233 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 6234 << Move << WChar << !!Src.Base 6235 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 6236 return false; 6237 } 6238 if (Src.Designator.Invalid || Dest.Designator.Invalid) 6239 return false; 6240 6241 // We require that Src and Dest are both pointers to arrays of 6242 // trivially-copyable type. (For the wide version, the designator will be 6243 // invalid if the designated object is not a wchar_t.) 6244 QualType T = Dest.Designator.getType(Info.Ctx); 6245 QualType SrcT = Src.Designator.getType(Info.Ctx); 6246 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 6247 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 6248 return false; 6249 } 6250 if (T->isIncompleteType()) { 6251 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 6252 return false; 6253 } 6254 if (!T.isTriviallyCopyableType(Info.Ctx)) { 6255 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 6256 return false; 6257 } 6258 6259 // Figure out how many T's we're copying. 6260 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 6261 if (!WChar) { 6262 uint64_t Remainder; 6263 llvm::APInt OrigN = N; 6264 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 6265 if (Remainder) { 6266 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 6267 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 6268 << (unsigned)TSize; 6269 return false; 6270 } 6271 } 6272 6273 // Check that the copying will remain within the arrays, just so that we 6274 // can give a more meaningful diagnostic. This implicitly also checks that 6275 // N fits into 64 bits. 6276 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 6277 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 6278 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 6279 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 6280 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 6281 << N.toString(10, /*Signed*/false); 6282 return false; 6283 } 6284 uint64_t NElems = N.getZExtValue(); 6285 uint64_t NBytes = NElems * TSize; 6286 6287 // Check for overlap. 6288 int Direction = 1; 6289 if (HasSameBase(Src, Dest)) { 6290 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 6291 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 6292 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 6293 // Dest is inside the source region. 6294 if (!Move) { 6295 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 6296 return false; 6297 } 6298 // For memmove and friends, copy backwards. 6299 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 6300 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 6301 return false; 6302 Direction = -1; 6303 } else if (!Move && SrcOffset >= DestOffset && 6304 SrcOffset - DestOffset < NBytes) { 6305 // Src is inside the destination region for memcpy: invalid. 6306 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 6307 return false; 6308 } 6309 } 6310 6311 while (true) { 6312 APValue Val; 6313 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 6314 !handleAssignment(Info, E, Dest, T, Val)) 6315 return false; 6316 // Do not iterate past the last element; if we're copying backwards, that 6317 // might take us off the start of the array. 6318 if (--NElems == 0) 6319 return true; 6320 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 6321 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 6322 return false; 6323 } 6324 } 6325 6326 default: 6327 return visitNonBuiltinCallExpr(E); 6328 } 6329 } 6330 6331 //===----------------------------------------------------------------------===// 6332 // Member Pointer Evaluation 6333 //===----------------------------------------------------------------------===// 6334 6335 namespace { 6336 class MemberPointerExprEvaluator 6337 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 6338 MemberPtr &Result; 6339 6340 bool Success(const ValueDecl *D) { 6341 Result = MemberPtr(D); 6342 return true; 6343 } 6344 public: 6345 6346 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 6347 : ExprEvaluatorBaseTy(Info), Result(Result) {} 6348 6349 bool Success(const APValue &V, const Expr *E) { 6350 Result.setFrom(V); 6351 return true; 6352 } 6353 bool ZeroInitialization(const Expr *E) { 6354 return Success((const ValueDecl*)nullptr); 6355 } 6356 6357 bool VisitCastExpr(const CastExpr *E); 6358 bool VisitUnaryAddrOf(const UnaryOperator *E); 6359 }; 6360 } // end anonymous namespace 6361 6362 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 6363 EvalInfo &Info) { 6364 assert(E->isRValue() && E->getType()->isMemberPointerType()); 6365 return MemberPointerExprEvaluator(Info, Result).Visit(E); 6366 } 6367 6368 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 6369 switch (E->getCastKind()) { 6370 default: 6371 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6372 6373 case CK_NullToMemberPointer: 6374 VisitIgnoredValue(E->getSubExpr()); 6375 return ZeroInitialization(E); 6376 6377 case CK_BaseToDerivedMemberPointer: { 6378 if (!Visit(E->getSubExpr())) 6379 return false; 6380 if (E->path_empty()) 6381 return true; 6382 // Base-to-derived member pointer casts store the path in derived-to-base 6383 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 6384 // the wrong end of the derived->base arc, so stagger the path by one class. 6385 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 6386 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 6387 PathI != PathE; ++PathI) { 6388 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6389 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 6390 if (!Result.castToDerived(Derived)) 6391 return Error(E); 6392 } 6393 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 6394 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 6395 return Error(E); 6396 return true; 6397 } 6398 6399 case CK_DerivedToBaseMemberPointer: 6400 if (!Visit(E->getSubExpr())) 6401 return false; 6402 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6403 PathE = E->path_end(); PathI != PathE; ++PathI) { 6404 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6405 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6406 if (!Result.castToBase(Base)) 6407 return Error(E); 6408 } 6409 return true; 6410 } 6411 } 6412 6413 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 6414 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 6415 // member can be formed. 6416 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 6417 } 6418 6419 //===----------------------------------------------------------------------===// 6420 // Record Evaluation 6421 //===----------------------------------------------------------------------===// 6422 6423 namespace { 6424 class RecordExprEvaluator 6425 : public ExprEvaluatorBase<RecordExprEvaluator> { 6426 const LValue &This; 6427 APValue &Result; 6428 public: 6429 6430 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 6431 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 6432 6433 bool Success(const APValue &V, const Expr *E) { 6434 Result = V; 6435 return true; 6436 } 6437 bool ZeroInitialization(const Expr *E) { 6438 return ZeroInitialization(E, E->getType()); 6439 } 6440 bool ZeroInitialization(const Expr *E, QualType T); 6441 6442 bool VisitCallExpr(const CallExpr *E) { 6443 return handleCallExpr(E, Result, &This); 6444 } 6445 bool VisitCastExpr(const CastExpr *E); 6446 bool VisitInitListExpr(const InitListExpr *E); 6447 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6448 return VisitCXXConstructExpr(E, E->getType()); 6449 } 6450 bool VisitLambdaExpr(const LambdaExpr *E); 6451 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 6452 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 6453 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 6454 6455 bool VisitBinCmp(const BinaryOperator *E); 6456 }; 6457 } 6458 6459 /// Perform zero-initialization on an object of non-union class type. 6460 /// C++11 [dcl.init]p5: 6461 /// To zero-initialize an object or reference of type T means: 6462 /// [...] 6463 /// -- if T is a (possibly cv-qualified) non-union class type, 6464 /// each non-static data member and each base-class subobject is 6465 /// zero-initialized 6466 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 6467 const RecordDecl *RD, 6468 const LValue &This, APValue &Result) { 6469 assert(!RD->isUnion() && "Expected non-union class type"); 6470 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 6471 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 6472 std::distance(RD->field_begin(), RD->field_end())); 6473 6474 if (RD->isInvalidDecl()) return false; 6475 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6476 6477 if (CD) { 6478 unsigned Index = 0; 6479 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 6480 End = CD->bases_end(); I != End; ++I, ++Index) { 6481 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 6482 LValue Subobject = This; 6483 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 6484 return false; 6485 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 6486 Result.getStructBase(Index))) 6487 return false; 6488 } 6489 } 6490 6491 for (const auto *I : RD->fields()) { 6492 // -- if T is a reference type, no initialization is performed. 6493 if (I->getType()->isReferenceType()) 6494 continue; 6495 6496 LValue Subobject = This; 6497 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 6498 return false; 6499 6500 ImplicitValueInitExpr VIE(I->getType()); 6501 if (!EvaluateInPlace( 6502 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 6503 return false; 6504 } 6505 6506 return true; 6507 } 6508 6509 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 6510 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 6511 if (RD->isInvalidDecl()) return false; 6512 if (RD->isUnion()) { 6513 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 6514 // object's first non-static named data member is zero-initialized 6515 RecordDecl::field_iterator I = RD->field_begin(); 6516 if (I == RD->field_end()) { 6517 Result = APValue((const FieldDecl*)nullptr); 6518 return true; 6519 } 6520 6521 LValue Subobject = This; 6522 if (!HandleLValueMember(Info, E, Subobject, *I)) 6523 return false; 6524 Result = APValue(*I); 6525 ImplicitValueInitExpr VIE(I->getType()); 6526 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 6527 } 6528 6529 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 6530 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 6531 return false; 6532 } 6533 6534 return HandleClassZeroInitialization(Info, E, RD, This, Result); 6535 } 6536 6537 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 6538 switch (E->getCastKind()) { 6539 default: 6540 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6541 6542 case CK_ConstructorConversion: 6543 return Visit(E->getSubExpr()); 6544 6545 case CK_DerivedToBase: 6546 case CK_UncheckedDerivedToBase: { 6547 APValue DerivedObject; 6548 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 6549 return false; 6550 if (!DerivedObject.isStruct()) 6551 return Error(E->getSubExpr()); 6552 6553 // Derived-to-base rvalue conversion: just slice off the derived part. 6554 APValue *Value = &DerivedObject; 6555 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 6556 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6557 PathE = E->path_end(); PathI != PathE; ++PathI) { 6558 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 6559 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6560 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 6561 RD = Base; 6562 } 6563 Result = *Value; 6564 return true; 6565 } 6566 } 6567 } 6568 6569 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6570 if (E->isTransparent()) 6571 return Visit(E->getInit(0)); 6572 6573 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 6574 if (RD->isInvalidDecl()) return false; 6575 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6576 6577 if (RD->isUnion()) { 6578 const FieldDecl *Field = E->getInitializedFieldInUnion(); 6579 Result = APValue(Field); 6580 if (!Field) 6581 return true; 6582 6583 // If the initializer list for a union does not contain any elements, the 6584 // first element of the union is value-initialized. 6585 // FIXME: The element should be initialized from an initializer list. 6586 // Is this difference ever observable for initializer lists which 6587 // we don't build? 6588 ImplicitValueInitExpr VIE(Field->getType()); 6589 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 6590 6591 LValue Subobject = This; 6592 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 6593 return false; 6594 6595 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6596 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6597 isa<CXXDefaultInitExpr>(InitExpr)); 6598 6599 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 6600 } 6601 6602 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 6603 if (Result.isUninit()) 6604 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 6605 std::distance(RD->field_begin(), RD->field_end())); 6606 unsigned ElementNo = 0; 6607 bool Success = true; 6608 6609 // Initialize base classes. 6610 if (CXXRD) { 6611 for (const auto &Base : CXXRD->bases()) { 6612 assert(ElementNo < E->getNumInits() && "missing init for base class"); 6613 const Expr *Init = E->getInit(ElementNo); 6614 6615 LValue Subobject = This; 6616 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 6617 return false; 6618 6619 APValue &FieldVal = Result.getStructBase(ElementNo); 6620 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 6621 if (!Info.noteFailure()) 6622 return false; 6623 Success = false; 6624 } 6625 ++ElementNo; 6626 } 6627 } 6628 6629 // Initialize members. 6630 for (const auto *Field : RD->fields()) { 6631 // Anonymous bit-fields are not considered members of the class for 6632 // purposes of aggregate initialization. 6633 if (Field->isUnnamedBitfield()) 6634 continue; 6635 6636 LValue Subobject = This; 6637 6638 bool HaveInit = ElementNo < E->getNumInits(); 6639 6640 // FIXME: Diagnostics here should point to the end of the initializer 6641 // list, not the start. 6642 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 6643 Subobject, Field, &Layout)) 6644 return false; 6645 6646 // Perform an implicit value-initialization for members beyond the end of 6647 // the initializer list. 6648 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 6649 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 6650 6651 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6652 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6653 isa<CXXDefaultInitExpr>(Init)); 6654 6655 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6656 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 6657 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 6658 FieldVal, Field))) { 6659 if (!Info.noteFailure()) 6660 return false; 6661 Success = false; 6662 } 6663 } 6664 6665 return Success; 6666 } 6667 6668 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 6669 QualType T) { 6670 // Note that E's type is not necessarily the type of our class here; we might 6671 // be initializing an array element instead. 6672 const CXXConstructorDecl *FD = E->getConstructor(); 6673 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 6674 6675 bool ZeroInit = E->requiresZeroInitialization(); 6676 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 6677 // If we've already performed zero-initialization, we're already done. 6678 if (!Result.isUninit()) 6679 return true; 6680 6681 // We can get here in two different ways: 6682 // 1) We're performing value-initialization, and should zero-initialize 6683 // the object, or 6684 // 2) We're performing default-initialization of an object with a trivial 6685 // constexpr default constructor, in which case we should start the 6686 // lifetimes of all the base subobjects (there can be no data member 6687 // subobjects in this case) per [basic.life]p1. 6688 // Either way, ZeroInitialization is appropriate. 6689 return ZeroInitialization(E, T); 6690 } 6691 6692 const FunctionDecl *Definition = nullptr; 6693 auto Body = FD->getBody(Definition); 6694 6695 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6696 return false; 6697 6698 // Avoid materializing a temporary for an elidable copy/move constructor. 6699 if (E->isElidable() && !ZeroInit) 6700 if (const MaterializeTemporaryExpr *ME 6701 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 6702 return Visit(ME->GetTemporaryExpr()); 6703 6704 if (ZeroInit && !ZeroInitialization(E, T)) 6705 return false; 6706 6707 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 6708 return HandleConstructorCall(E, This, Args, 6709 cast<CXXConstructorDecl>(Definition), Info, 6710 Result); 6711 } 6712 6713 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 6714 const CXXInheritedCtorInitExpr *E) { 6715 if (!Info.CurrentCall) { 6716 assert(Info.checkingPotentialConstantExpression()); 6717 return false; 6718 } 6719 6720 const CXXConstructorDecl *FD = E->getConstructor(); 6721 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 6722 return false; 6723 6724 const FunctionDecl *Definition = nullptr; 6725 auto Body = FD->getBody(Definition); 6726 6727 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6728 return false; 6729 6730 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 6731 cast<CXXConstructorDecl>(Definition), Info, 6732 Result); 6733 } 6734 6735 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 6736 const CXXStdInitializerListExpr *E) { 6737 const ConstantArrayType *ArrayType = 6738 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 6739 6740 LValue Array; 6741 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 6742 return false; 6743 6744 // Get a pointer to the first element of the array. 6745 Array.addArray(Info, E, ArrayType); 6746 6747 // FIXME: Perform the checks on the field types in SemaInit. 6748 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 6749 RecordDecl::field_iterator Field = Record->field_begin(); 6750 if (Field == Record->field_end()) 6751 return Error(E); 6752 6753 // Start pointer. 6754 if (!Field->getType()->isPointerType() || 6755 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6756 ArrayType->getElementType())) 6757 return Error(E); 6758 6759 // FIXME: What if the initializer_list type has base classes, etc? 6760 Result = APValue(APValue::UninitStruct(), 0, 2); 6761 Array.moveInto(Result.getStructField(0)); 6762 6763 if (++Field == Record->field_end()) 6764 return Error(E); 6765 6766 if (Field->getType()->isPointerType() && 6767 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6768 ArrayType->getElementType())) { 6769 // End pointer. 6770 if (!HandleLValueArrayAdjustment(Info, E, Array, 6771 ArrayType->getElementType(), 6772 ArrayType->getSize().getZExtValue())) 6773 return false; 6774 Array.moveInto(Result.getStructField(1)); 6775 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 6776 // Length. 6777 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 6778 else 6779 return Error(E); 6780 6781 if (++Field != Record->field_end()) 6782 return Error(E); 6783 6784 return true; 6785 } 6786 6787 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 6788 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 6789 if (ClosureClass->isInvalidDecl()) return false; 6790 6791 if (Info.checkingPotentialConstantExpression()) return true; 6792 6793 const size_t NumFields = 6794 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 6795 6796 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 6797 E->capture_init_end()) && 6798 "The number of lambda capture initializers should equal the number of " 6799 "fields within the closure type"); 6800 6801 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 6802 // Iterate through all the lambda's closure object's fields and initialize 6803 // them. 6804 auto *CaptureInitIt = E->capture_init_begin(); 6805 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 6806 bool Success = true; 6807 for (const auto *Field : ClosureClass->fields()) { 6808 assert(CaptureInitIt != E->capture_init_end()); 6809 // Get the initializer for this field 6810 Expr *const CurFieldInit = *CaptureInitIt++; 6811 6812 // If there is no initializer, either this is a VLA or an error has 6813 // occurred. 6814 if (!CurFieldInit) 6815 return Error(E); 6816 6817 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6818 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 6819 if (!Info.keepEvaluatingAfterFailure()) 6820 return false; 6821 Success = false; 6822 } 6823 ++CaptureIt; 6824 } 6825 return Success; 6826 } 6827 6828 static bool EvaluateRecord(const Expr *E, const LValue &This, 6829 APValue &Result, EvalInfo &Info) { 6830 assert(E->isRValue() && E->getType()->isRecordType() && 6831 "can't evaluate expression as a record rvalue"); 6832 return RecordExprEvaluator(Info, This, Result).Visit(E); 6833 } 6834 6835 //===----------------------------------------------------------------------===// 6836 // Temporary Evaluation 6837 // 6838 // Temporaries are represented in the AST as rvalues, but generally behave like 6839 // lvalues. The full-object of which the temporary is a subobject is implicitly 6840 // materialized so that a reference can bind to it. 6841 //===----------------------------------------------------------------------===// 6842 namespace { 6843 class TemporaryExprEvaluator 6844 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 6845 public: 6846 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 6847 LValueExprEvaluatorBaseTy(Info, Result, false) {} 6848 6849 /// Visit an expression which constructs the value of this temporary. 6850 bool VisitConstructExpr(const Expr *E) { 6851 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall); 6852 return EvaluateInPlace(Value, Info, Result, E); 6853 } 6854 6855 bool VisitCastExpr(const CastExpr *E) { 6856 switch (E->getCastKind()) { 6857 default: 6858 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 6859 6860 case CK_ConstructorConversion: 6861 return VisitConstructExpr(E->getSubExpr()); 6862 } 6863 } 6864 bool VisitInitListExpr(const InitListExpr *E) { 6865 return VisitConstructExpr(E); 6866 } 6867 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6868 return VisitConstructExpr(E); 6869 } 6870 bool VisitCallExpr(const CallExpr *E) { 6871 return VisitConstructExpr(E); 6872 } 6873 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 6874 return VisitConstructExpr(E); 6875 } 6876 bool VisitLambdaExpr(const LambdaExpr *E) { 6877 return VisitConstructExpr(E); 6878 } 6879 }; 6880 } // end anonymous namespace 6881 6882 /// Evaluate an expression of record type as a temporary. 6883 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 6884 assert(E->isRValue() && E->getType()->isRecordType()); 6885 return TemporaryExprEvaluator(Info, Result).Visit(E); 6886 } 6887 6888 //===----------------------------------------------------------------------===// 6889 // Vector Evaluation 6890 //===----------------------------------------------------------------------===// 6891 6892 namespace { 6893 class VectorExprEvaluator 6894 : public ExprEvaluatorBase<VectorExprEvaluator> { 6895 APValue &Result; 6896 public: 6897 6898 VectorExprEvaluator(EvalInfo &info, APValue &Result) 6899 : ExprEvaluatorBaseTy(info), Result(Result) {} 6900 6901 bool Success(ArrayRef<APValue> V, const Expr *E) { 6902 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 6903 // FIXME: remove this APValue copy. 6904 Result = APValue(V.data(), V.size()); 6905 return true; 6906 } 6907 bool Success(const APValue &V, const Expr *E) { 6908 assert(V.isVector()); 6909 Result = V; 6910 return true; 6911 } 6912 bool ZeroInitialization(const Expr *E); 6913 6914 bool VisitUnaryReal(const UnaryOperator *E) 6915 { return Visit(E->getSubExpr()); } 6916 bool VisitCastExpr(const CastExpr* E); 6917 bool VisitInitListExpr(const InitListExpr *E); 6918 bool VisitUnaryImag(const UnaryOperator *E); 6919 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 6920 // binary comparisons, binary and/or/xor, 6921 // shufflevector, ExtVectorElementExpr 6922 }; 6923 } // end anonymous namespace 6924 6925 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 6926 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 6927 return VectorExprEvaluator(Info, Result).Visit(E); 6928 } 6929 6930 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 6931 const VectorType *VTy = E->getType()->castAs<VectorType>(); 6932 unsigned NElts = VTy->getNumElements(); 6933 6934 const Expr *SE = E->getSubExpr(); 6935 QualType SETy = SE->getType(); 6936 6937 switch (E->getCastKind()) { 6938 case CK_VectorSplat: { 6939 APValue Val = APValue(); 6940 if (SETy->isIntegerType()) { 6941 APSInt IntResult; 6942 if (!EvaluateInteger(SE, IntResult, Info)) 6943 return false; 6944 Val = APValue(std::move(IntResult)); 6945 } else if (SETy->isRealFloatingType()) { 6946 APFloat FloatResult(0.0); 6947 if (!EvaluateFloat(SE, FloatResult, Info)) 6948 return false; 6949 Val = APValue(std::move(FloatResult)); 6950 } else { 6951 return Error(E); 6952 } 6953 6954 // Splat and create vector APValue. 6955 SmallVector<APValue, 4> Elts(NElts, Val); 6956 return Success(Elts, E); 6957 } 6958 case CK_BitCast: { 6959 // Evaluate the operand into an APInt we can extract from. 6960 llvm::APInt SValInt; 6961 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 6962 return false; 6963 // Extract the elements 6964 QualType EltTy = VTy->getElementType(); 6965 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 6966 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 6967 SmallVector<APValue, 4> Elts; 6968 if (EltTy->isRealFloatingType()) { 6969 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 6970 unsigned FloatEltSize = EltSize; 6971 if (&Sem == &APFloat::x87DoubleExtended()) 6972 FloatEltSize = 80; 6973 for (unsigned i = 0; i < NElts; i++) { 6974 llvm::APInt Elt; 6975 if (BigEndian) 6976 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 6977 else 6978 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 6979 Elts.push_back(APValue(APFloat(Sem, Elt))); 6980 } 6981 } else if (EltTy->isIntegerType()) { 6982 for (unsigned i = 0; i < NElts; i++) { 6983 llvm::APInt Elt; 6984 if (BigEndian) 6985 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 6986 else 6987 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 6988 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 6989 } 6990 } else { 6991 return Error(E); 6992 } 6993 return Success(Elts, E); 6994 } 6995 default: 6996 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6997 } 6998 } 6999 7000 bool 7001 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7002 const VectorType *VT = E->getType()->castAs<VectorType>(); 7003 unsigned NumInits = E->getNumInits(); 7004 unsigned NumElements = VT->getNumElements(); 7005 7006 QualType EltTy = VT->getElementType(); 7007 SmallVector<APValue, 4> Elements; 7008 7009 // The number of initializers can be less than the number of 7010 // vector elements. For OpenCL, this can be due to nested vector 7011 // initialization. For GCC compatibility, missing trailing elements 7012 // should be initialized with zeroes. 7013 unsigned CountInits = 0, CountElts = 0; 7014 while (CountElts < NumElements) { 7015 // Handle nested vector initialization. 7016 if (CountInits < NumInits 7017 && E->getInit(CountInits)->getType()->isVectorType()) { 7018 APValue v; 7019 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 7020 return Error(E); 7021 unsigned vlen = v.getVectorLength(); 7022 for (unsigned j = 0; j < vlen; j++) 7023 Elements.push_back(v.getVectorElt(j)); 7024 CountElts += vlen; 7025 } else if (EltTy->isIntegerType()) { 7026 llvm::APSInt sInt(32); 7027 if (CountInits < NumInits) { 7028 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 7029 return false; 7030 } else // trailing integer zero. 7031 sInt = Info.Ctx.MakeIntValue(0, EltTy); 7032 Elements.push_back(APValue(sInt)); 7033 CountElts++; 7034 } else { 7035 llvm::APFloat f(0.0); 7036 if (CountInits < NumInits) { 7037 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 7038 return false; 7039 } else // trailing float zero. 7040 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 7041 Elements.push_back(APValue(f)); 7042 CountElts++; 7043 } 7044 CountInits++; 7045 } 7046 return Success(Elements, E); 7047 } 7048 7049 bool 7050 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 7051 const VectorType *VT = E->getType()->getAs<VectorType>(); 7052 QualType EltTy = VT->getElementType(); 7053 APValue ZeroElement; 7054 if (EltTy->isIntegerType()) 7055 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 7056 else 7057 ZeroElement = 7058 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 7059 7060 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 7061 return Success(Elements, E); 7062 } 7063 7064 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 7065 VisitIgnoredValue(E->getSubExpr()); 7066 return ZeroInitialization(E); 7067 } 7068 7069 //===----------------------------------------------------------------------===// 7070 // Array Evaluation 7071 //===----------------------------------------------------------------------===// 7072 7073 namespace { 7074 class ArrayExprEvaluator 7075 : public ExprEvaluatorBase<ArrayExprEvaluator> { 7076 const LValue &This; 7077 APValue &Result; 7078 public: 7079 7080 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 7081 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 7082 7083 bool Success(const APValue &V, const Expr *E) { 7084 assert((V.isArray() || V.isLValue()) && 7085 "expected array or string literal"); 7086 Result = V; 7087 return true; 7088 } 7089 7090 bool ZeroInitialization(const Expr *E) { 7091 const ConstantArrayType *CAT = 7092 Info.Ctx.getAsConstantArrayType(E->getType()); 7093 if (!CAT) 7094 return Error(E); 7095 7096 Result = APValue(APValue::UninitArray(), 0, 7097 CAT->getSize().getZExtValue()); 7098 if (!Result.hasArrayFiller()) return true; 7099 7100 // Zero-initialize all elements. 7101 LValue Subobject = This; 7102 Subobject.addArray(Info, E, CAT); 7103 ImplicitValueInitExpr VIE(CAT->getElementType()); 7104 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 7105 } 7106 7107 bool VisitCallExpr(const CallExpr *E) { 7108 return handleCallExpr(E, Result, &This); 7109 } 7110 bool VisitInitListExpr(const InitListExpr *E); 7111 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 7112 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 7113 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 7114 const LValue &Subobject, 7115 APValue *Value, QualType Type); 7116 }; 7117 } // end anonymous namespace 7118 7119 static bool EvaluateArray(const Expr *E, const LValue &This, 7120 APValue &Result, EvalInfo &Info) { 7121 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 7122 return ArrayExprEvaluator(Info, This, Result).Visit(E); 7123 } 7124 7125 // Return true iff the given array filler may depend on the element index. 7126 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 7127 // For now, just whitelist non-class value-initialization and initialization 7128 // lists comprised of them. 7129 if (isa<ImplicitValueInitExpr>(FillerExpr)) 7130 return false; 7131 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 7132 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 7133 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 7134 return true; 7135 } 7136 return false; 7137 } 7138 return true; 7139 } 7140 7141 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7142 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 7143 if (!CAT) 7144 return Error(E); 7145 7146 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 7147 // an appropriately-typed string literal enclosed in braces. 7148 if (E->isStringLiteralInit()) { 7149 LValue LV; 7150 if (!EvaluateLValue(E->getInit(0), LV, Info)) 7151 return false; 7152 APValue Val; 7153 LV.moveInto(Val); 7154 return Success(Val, E); 7155 } 7156 7157 bool Success = true; 7158 7159 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 7160 "zero-initialized array shouldn't have any initialized elts"); 7161 APValue Filler; 7162 if (Result.isArray() && Result.hasArrayFiller()) 7163 Filler = Result.getArrayFiller(); 7164 7165 unsigned NumEltsToInit = E->getNumInits(); 7166 unsigned NumElts = CAT->getSize().getZExtValue(); 7167 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 7168 7169 // If the initializer might depend on the array index, run it for each 7170 // array element. 7171 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 7172 NumEltsToInit = NumElts; 7173 7174 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 7175 << NumEltsToInit << ".\n"); 7176 7177 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 7178 7179 // If the array was previously zero-initialized, preserve the 7180 // zero-initialized values. 7181 if (!Filler.isUninit()) { 7182 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 7183 Result.getArrayInitializedElt(I) = Filler; 7184 if (Result.hasArrayFiller()) 7185 Result.getArrayFiller() = Filler; 7186 } 7187 7188 LValue Subobject = This; 7189 Subobject.addArray(Info, E, CAT); 7190 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 7191 const Expr *Init = 7192 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 7193 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 7194 Info, Subobject, Init) || 7195 !HandleLValueArrayAdjustment(Info, Init, Subobject, 7196 CAT->getElementType(), 1)) { 7197 if (!Info.noteFailure()) 7198 return false; 7199 Success = false; 7200 } 7201 } 7202 7203 if (!Result.hasArrayFiller()) 7204 return Success; 7205 7206 // If we get here, we have a trivial filler, which we can just evaluate 7207 // once and splat over the rest of the array elements. 7208 assert(FillerExpr && "no array filler for incomplete init list"); 7209 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 7210 FillerExpr) && Success; 7211 } 7212 7213 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 7214 if (E->getCommonExpr() && 7215 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false), 7216 Info, E->getCommonExpr()->getSourceExpr())) 7217 return false; 7218 7219 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 7220 7221 uint64_t Elements = CAT->getSize().getZExtValue(); 7222 Result = APValue(APValue::UninitArray(), Elements, Elements); 7223 7224 LValue Subobject = This; 7225 Subobject.addArray(Info, E, CAT); 7226 7227 bool Success = true; 7228 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 7229 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 7230 Info, Subobject, E->getSubExpr()) || 7231 !HandleLValueArrayAdjustment(Info, E, Subobject, 7232 CAT->getElementType(), 1)) { 7233 if (!Info.noteFailure()) 7234 return false; 7235 Success = false; 7236 } 7237 } 7238 7239 return Success; 7240 } 7241 7242 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 7243 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 7244 } 7245 7246 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 7247 const LValue &Subobject, 7248 APValue *Value, 7249 QualType Type) { 7250 bool HadZeroInit = !Value->isUninit(); 7251 7252 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 7253 unsigned N = CAT->getSize().getZExtValue(); 7254 7255 // Preserve the array filler if we had prior zero-initialization. 7256 APValue Filler = 7257 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 7258 : APValue(); 7259 7260 *Value = APValue(APValue::UninitArray(), N, N); 7261 7262 if (HadZeroInit) 7263 for (unsigned I = 0; I != N; ++I) 7264 Value->getArrayInitializedElt(I) = Filler; 7265 7266 // Initialize the elements. 7267 LValue ArrayElt = Subobject; 7268 ArrayElt.addArray(Info, E, CAT); 7269 for (unsigned I = 0; I != N; ++I) 7270 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 7271 CAT->getElementType()) || 7272 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 7273 CAT->getElementType(), 1)) 7274 return false; 7275 7276 return true; 7277 } 7278 7279 if (!Type->isRecordType()) 7280 return Error(E); 7281 7282 return RecordExprEvaluator(Info, Subobject, *Value) 7283 .VisitCXXConstructExpr(E, Type); 7284 } 7285 7286 //===----------------------------------------------------------------------===// 7287 // Integer Evaluation 7288 // 7289 // As a GNU extension, we support casting pointers to sufficiently-wide integer 7290 // types and back in constant folding. Integer values are thus represented 7291 // either as an integer-valued APValue, or as an lvalue-valued APValue. 7292 //===----------------------------------------------------------------------===// 7293 7294 namespace { 7295 class IntExprEvaluator 7296 : public ExprEvaluatorBase<IntExprEvaluator> { 7297 APValue &Result; 7298 public: 7299 IntExprEvaluator(EvalInfo &info, APValue &result) 7300 : ExprEvaluatorBaseTy(info), Result(result) {} 7301 7302 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 7303 assert(E->getType()->isIntegralOrEnumerationType() && 7304 "Invalid evaluation result."); 7305 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 7306 "Invalid evaluation result."); 7307 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7308 "Invalid evaluation result."); 7309 Result = APValue(SI); 7310 return true; 7311 } 7312 bool Success(const llvm::APSInt &SI, const Expr *E) { 7313 return Success(SI, E, Result); 7314 } 7315 7316 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 7317 assert(E->getType()->isIntegralOrEnumerationType() && 7318 "Invalid evaluation result."); 7319 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7320 "Invalid evaluation result."); 7321 Result = APValue(APSInt(I)); 7322 Result.getInt().setIsUnsigned( 7323 E->getType()->isUnsignedIntegerOrEnumerationType()); 7324 return true; 7325 } 7326 bool Success(const llvm::APInt &I, const Expr *E) { 7327 return Success(I, E, Result); 7328 } 7329 7330 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 7331 assert(E->getType()->isIntegralOrEnumerationType() && 7332 "Invalid evaluation result."); 7333 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 7334 return true; 7335 } 7336 bool Success(uint64_t Value, const Expr *E) { 7337 return Success(Value, E, Result); 7338 } 7339 7340 bool Success(CharUnits Size, const Expr *E) { 7341 return Success(Size.getQuantity(), E); 7342 } 7343 7344 bool Success(const APValue &V, const Expr *E) { 7345 if (V.isLValue() || V.isAddrLabelDiff()) { 7346 Result = V; 7347 return true; 7348 } 7349 return Success(V.getInt(), E); 7350 } 7351 7352 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 7353 7354 //===--------------------------------------------------------------------===// 7355 // Visitor Methods 7356 //===--------------------------------------------------------------------===// 7357 7358 bool VisitConstantExpr(const ConstantExpr *E); 7359 7360 bool VisitIntegerLiteral(const IntegerLiteral *E) { 7361 return Success(E->getValue(), E); 7362 } 7363 bool VisitCharacterLiteral(const CharacterLiteral *E) { 7364 return Success(E->getValue(), E); 7365 } 7366 7367 bool CheckReferencedDecl(const Expr *E, const Decl *D); 7368 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7369 if (CheckReferencedDecl(E, E->getDecl())) 7370 return true; 7371 7372 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 7373 } 7374 bool VisitMemberExpr(const MemberExpr *E) { 7375 if (CheckReferencedDecl(E, E->getMemberDecl())) { 7376 VisitIgnoredBaseExpression(E->getBase()); 7377 return true; 7378 } 7379 7380 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 7381 } 7382 7383 bool VisitCallExpr(const CallExpr *E); 7384 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 7385 bool VisitBinaryOperator(const BinaryOperator *E); 7386 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 7387 bool VisitUnaryOperator(const UnaryOperator *E); 7388 7389 bool VisitCastExpr(const CastExpr* E); 7390 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 7391 7392 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 7393 return Success(E->getValue(), E); 7394 } 7395 7396 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 7397 return Success(E->getValue(), E); 7398 } 7399 7400 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 7401 if (Info.ArrayInitIndex == uint64_t(-1)) { 7402 // We were asked to evaluate this subexpression independent of the 7403 // enclosing ArrayInitLoopExpr. We can't do that. 7404 Info.FFDiag(E); 7405 return false; 7406 } 7407 return Success(Info.ArrayInitIndex, E); 7408 } 7409 7410 // Note, GNU defines __null as an integer, not a pointer. 7411 bool VisitGNUNullExpr(const GNUNullExpr *E) { 7412 return ZeroInitialization(E); 7413 } 7414 7415 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 7416 return Success(E->getValue(), E); 7417 } 7418 7419 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 7420 return Success(E->getValue(), E); 7421 } 7422 7423 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 7424 return Success(E->getValue(), E); 7425 } 7426 7427 bool VisitUnaryReal(const UnaryOperator *E); 7428 bool VisitUnaryImag(const UnaryOperator *E); 7429 7430 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 7431 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 7432 7433 // FIXME: Missing: array subscript of vector, member of vector 7434 }; 7435 7436 class FixedPointExprEvaluator 7437 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 7438 APValue &Result; 7439 7440 public: 7441 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 7442 : ExprEvaluatorBaseTy(info), Result(result) {} 7443 7444 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 7445 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7446 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() && 7447 "Invalid evaluation result."); 7448 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7449 "Invalid evaluation result."); 7450 Result = APValue(SI); 7451 return true; 7452 } 7453 bool Success(const llvm::APSInt &SI, const Expr *E) { 7454 return Success(SI, E, Result); 7455 } 7456 7457 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 7458 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7459 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7460 "Invalid evaluation result."); 7461 Result = APValue(APSInt(I)); 7462 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType()); 7463 return true; 7464 } 7465 bool Success(const llvm::APInt &I, const Expr *E) { 7466 return Success(I, E, Result); 7467 } 7468 7469 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 7470 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7471 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 7472 return true; 7473 } 7474 bool Success(uint64_t Value, const Expr *E) { 7475 return Success(Value, E, Result); 7476 } 7477 7478 bool Success(CharUnits Size, const Expr *E) { 7479 return Success(Size.getQuantity(), E); 7480 } 7481 7482 bool Success(const APValue &V, const Expr *E) { 7483 if (V.isLValue() || V.isAddrLabelDiff()) { 7484 Result = V; 7485 return true; 7486 } 7487 return Success(V.getInt(), E); 7488 } 7489 7490 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 7491 7492 //===--------------------------------------------------------------------===// 7493 // Visitor Methods 7494 //===--------------------------------------------------------------------===// 7495 7496 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 7497 return Success(E->getValue(), E); 7498 } 7499 7500 bool VisitUnaryOperator(const UnaryOperator *E); 7501 }; 7502 } // end anonymous namespace 7503 7504 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 7505 /// produce either the integer value or a pointer. 7506 /// 7507 /// GCC has a heinous extension which folds casts between pointer types and 7508 /// pointer-sized integral types. We support this by allowing the evaluation of 7509 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 7510 /// Some simple arithmetic on such values is supported (they are treated much 7511 /// like char*). 7512 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 7513 EvalInfo &Info) { 7514 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 7515 return IntExprEvaluator(Info, Result).Visit(E); 7516 } 7517 7518 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 7519 APValue Val; 7520 if (!EvaluateIntegerOrLValue(E, Val, Info)) 7521 return false; 7522 if (!Val.isInt()) { 7523 // FIXME: It would be better to produce the diagnostic for casting 7524 // a pointer to an integer. 7525 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 7526 return false; 7527 } 7528 Result = Val.getInt(); 7529 return true; 7530 } 7531 7532 /// Check whether the given declaration can be directly converted to an integral 7533 /// rvalue. If not, no diagnostic is produced; there are other things we can 7534 /// try. 7535 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 7536 // Enums are integer constant exprs. 7537 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 7538 // Check for signedness/width mismatches between E type and ECD value. 7539 bool SameSign = (ECD->getInitVal().isSigned() 7540 == E->getType()->isSignedIntegerOrEnumerationType()); 7541 bool SameWidth = (ECD->getInitVal().getBitWidth() 7542 == Info.Ctx.getIntWidth(E->getType())); 7543 if (SameSign && SameWidth) 7544 return Success(ECD->getInitVal(), E); 7545 else { 7546 // Get rid of mismatch (otherwise Success assertions will fail) 7547 // by computing a new value matching the type of E. 7548 llvm::APSInt Val = ECD->getInitVal(); 7549 if (!SameSign) 7550 Val.setIsSigned(!ECD->getInitVal().isSigned()); 7551 if (!SameWidth) 7552 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 7553 return Success(Val, E); 7554 } 7555 } 7556 return false; 7557 } 7558 7559 /// Values returned by __builtin_classify_type, chosen to match the values 7560 /// produced by GCC's builtin. 7561 enum class GCCTypeClass { 7562 None = -1, 7563 Void = 0, 7564 Integer = 1, 7565 // GCC reserves 2 for character types, but instead classifies them as 7566 // integers. 7567 Enum = 3, 7568 Bool = 4, 7569 Pointer = 5, 7570 // GCC reserves 6 for references, but appears to never use it (because 7571 // expressions never have reference type, presumably). 7572 PointerToDataMember = 7, 7573 RealFloat = 8, 7574 Complex = 9, 7575 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 7576 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 7577 // GCC claims to reserve 11 for pointers to member functions, but *actually* 7578 // uses 12 for that purpose, same as for a class or struct. Maybe it 7579 // internally implements a pointer to member as a struct? Who knows. 7580 PointerToMemberFunction = 12, // Not a bug, see above. 7581 ClassOrStruct = 12, 7582 Union = 13, 7583 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 7584 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 7585 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 7586 // literals. 7587 }; 7588 7589 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 7590 /// as GCC. 7591 static GCCTypeClass 7592 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 7593 assert(!T->isDependentType() && "unexpected dependent type"); 7594 7595 QualType CanTy = T.getCanonicalType(); 7596 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 7597 7598 switch (CanTy->getTypeClass()) { 7599 #define TYPE(ID, BASE) 7600 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 7601 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 7602 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 7603 #include "clang/AST/TypeNodes.def" 7604 case Type::Auto: 7605 case Type::DeducedTemplateSpecialization: 7606 llvm_unreachable("unexpected non-canonical or dependent type"); 7607 7608 case Type::Builtin: 7609 switch (BT->getKind()) { 7610 #define BUILTIN_TYPE(ID, SINGLETON_ID) 7611 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 7612 case BuiltinType::ID: return GCCTypeClass::Integer; 7613 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 7614 case BuiltinType::ID: return GCCTypeClass::RealFloat; 7615 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 7616 case BuiltinType::ID: break; 7617 #include "clang/AST/BuiltinTypes.def" 7618 case BuiltinType::Void: 7619 return GCCTypeClass::Void; 7620 7621 case BuiltinType::Bool: 7622 return GCCTypeClass::Bool; 7623 7624 case BuiltinType::Char_U: 7625 case BuiltinType::UChar: 7626 case BuiltinType::WChar_U: 7627 case BuiltinType::Char8: 7628 case BuiltinType::Char16: 7629 case BuiltinType::Char32: 7630 case BuiltinType::UShort: 7631 case BuiltinType::UInt: 7632 case BuiltinType::ULong: 7633 case BuiltinType::ULongLong: 7634 case BuiltinType::UInt128: 7635 return GCCTypeClass::Integer; 7636 7637 case BuiltinType::UShortAccum: 7638 case BuiltinType::UAccum: 7639 case BuiltinType::ULongAccum: 7640 case BuiltinType::UShortFract: 7641 case BuiltinType::UFract: 7642 case BuiltinType::ULongFract: 7643 case BuiltinType::SatUShortAccum: 7644 case BuiltinType::SatUAccum: 7645 case BuiltinType::SatULongAccum: 7646 case BuiltinType::SatUShortFract: 7647 case BuiltinType::SatUFract: 7648 case BuiltinType::SatULongFract: 7649 return GCCTypeClass::None; 7650 7651 case BuiltinType::NullPtr: 7652 7653 case BuiltinType::ObjCId: 7654 case BuiltinType::ObjCClass: 7655 case BuiltinType::ObjCSel: 7656 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7657 case BuiltinType::Id: 7658 #include "clang/Basic/OpenCLImageTypes.def" 7659 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7660 case BuiltinType::Id: 7661 #include "clang/Basic/OpenCLExtensionTypes.def" 7662 case BuiltinType::OCLSampler: 7663 case BuiltinType::OCLEvent: 7664 case BuiltinType::OCLClkEvent: 7665 case BuiltinType::OCLQueue: 7666 case BuiltinType::OCLReserveID: 7667 return GCCTypeClass::None; 7668 7669 case BuiltinType::Dependent: 7670 llvm_unreachable("unexpected dependent type"); 7671 }; 7672 llvm_unreachable("unexpected placeholder type"); 7673 7674 case Type::Enum: 7675 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 7676 7677 case Type::Pointer: 7678 case Type::ConstantArray: 7679 case Type::VariableArray: 7680 case Type::IncompleteArray: 7681 case Type::FunctionNoProto: 7682 case Type::FunctionProto: 7683 return GCCTypeClass::Pointer; 7684 7685 case Type::MemberPointer: 7686 return CanTy->isMemberDataPointerType() 7687 ? GCCTypeClass::PointerToDataMember 7688 : GCCTypeClass::PointerToMemberFunction; 7689 7690 case Type::Complex: 7691 return GCCTypeClass::Complex; 7692 7693 case Type::Record: 7694 return CanTy->isUnionType() ? GCCTypeClass::Union 7695 : GCCTypeClass::ClassOrStruct; 7696 7697 case Type::Atomic: 7698 // GCC classifies _Atomic T the same as T. 7699 return EvaluateBuiltinClassifyType( 7700 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 7701 7702 case Type::BlockPointer: 7703 case Type::Vector: 7704 case Type::ExtVector: 7705 case Type::ObjCObject: 7706 case Type::ObjCInterface: 7707 case Type::ObjCObjectPointer: 7708 case Type::Pipe: 7709 // GCC classifies vectors as None. We follow its lead and classify all 7710 // other types that don't fit into the regular classification the same way. 7711 return GCCTypeClass::None; 7712 7713 case Type::LValueReference: 7714 case Type::RValueReference: 7715 llvm_unreachable("invalid type for expression"); 7716 } 7717 7718 llvm_unreachable("unexpected type class"); 7719 } 7720 7721 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 7722 /// as GCC. 7723 static GCCTypeClass 7724 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 7725 // If no argument was supplied, default to None. This isn't 7726 // ideal, however it is what gcc does. 7727 if (E->getNumArgs() == 0) 7728 return GCCTypeClass::None; 7729 7730 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 7731 // being an ICE, but still folds it to a constant using the type of the first 7732 // argument. 7733 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 7734 } 7735 7736 /// EvaluateBuiltinConstantPForLValue - Determine the result of 7737 /// __builtin_constant_p when applied to the given lvalue. 7738 /// 7739 /// An lvalue is only "constant" if it is a pointer or reference to the first 7740 /// character of a string literal. 7741 template<typename LValue> 7742 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) { 7743 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>(); 7744 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero(); 7745 } 7746 7747 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 7748 /// GCC as we can manage. 7749 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) { 7750 QualType ArgType = Arg->getType(); 7751 7752 // __builtin_constant_p always has one operand. The rules which gcc follows 7753 // are not precisely documented, but are as follows: 7754 // 7755 // - If the operand is of integral, floating, complex or enumeration type, 7756 // and can be folded to a known value of that type, it returns 1. 7757 // - If the operand and can be folded to a pointer to the first character 7758 // of a string literal (or such a pointer cast to an integral type), it 7759 // returns 1. 7760 // 7761 // Otherwise, it returns 0. 7762 // 7763 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 7764 // its support for this does not currently work. 7765 if (ArgType->isIntegralOrEnumerationType()) { 7766 Expr::EvalResult Result; 7767 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects) 7768 return false; 7769 7770 APValue &V = Result.Val; 7771 if (V.getKind() == APValue::Int) 7772 return true; 7773 if (V.getKind() == APValue::LValue) 7774 return EvaluateBuiltinConstantPForLValue(V); 7775 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) { 7776 return Arg->isEvaluatable(Ctx); 7777 } else if (ArgType->isPointerType() || Arg->isGLValue()) { 7778 LValue LV; 7779 Expr::EvalStatus Status; 7780 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 7781 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info) 7782 : EvaluatePointer(Arg, LV, Info)) && 7783 !Status.HasSideEffects) 7784 return EvaluateBuiltinConstantPForLValue(LV); 7785 } 7786 7787 // Anything else isn't considered to be sufficiently constant. 7788 return false; 7789 } 7790 7791 /// Retrieves the "underlying object type" of the given expression, 7792 /// as used by __builtin_object_size. 7793 static QualType getObjectType(APValue::LValueBase B) { 7794 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 7795 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 7796 return VD->getType(); 7797 } else if (const Expr *E = B.get<const Expr*>()) { 7798 if (isa<CompoundLiteralExpr>(E)) 7799 return E->getType(); 7800 } 7801 7802 return QualType(); 7803 } 7804 7805 /// A more selective version of E->IgnoreParenCasts for 7806 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 7807 /// to change the type of E. 7808 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 7809 /// 7810 /// Always returns an RValue with a pointer representation. 7811 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 7812 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 7813 7814 auto *NoParens = E->IgnoreParens(); 7815 auto *Cast = dyn_cast<CastExpr>(NoParens); 7816 if (Cast == nullptr) 7817 return NoParens; 7818 7819 // We only conservatively allow a few kinds of casts, because this code is 7820 // inherently a simple solution that seeks to support the common case. 7821 auto CastKind = Cast->getCastKind(); 7822 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 7823 CastKind != CK_AddressSpaceConversion) 7824 return NoParens; 7825 7826 auto *SubExpr = Cast->getSubExpr(); 7827 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 7828 return NoParens; 7829 return ignorePointerCastsAndParens(SubExpr); 7830 } 7831 7832 /// Checks to see if the given LValue's Designator is at the end of the LValue's 7833 /// record layout. e.g. 7834 /// struct { struct { int a, b; } fst, snd; } obj; 7835 /// obj.fst // no 7836 /// obj.snd // yes 7837 /// obj.fst.a // no 7838 /// obj.fst.b // no 7839 /// obj.snd.a // no 7840 /// obj.snd.b // yes 7841 /// 7842 /// Please note: this function is specialized for how __builtin_object_size 7843 /// views "objects". 7844 /// 7845 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 7846 /// correct result, it will always return true. 7847 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 7848 assert(!LVal.Designator.Invalid); 7849 7850 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 7851 const RecordDecl *Parent = FD->getParent(); 7852 Invalid = Parent->isInvalidDecl(); 7853 if (Invalid || Parent->isUnion()) 7854 return true; 7855 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 7856 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 7857 }; 7858 7859 auto &Base = LVal.getLValueBase(); 7860 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 7861 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 7862 bool Invalid; 7863 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7864 return Invalid; 7865 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 7866 for (auto *FD : IFD->chain()) { 7867 bool Invalid; 7868 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 7869 return Invalid; 7870 } 7871 } 7872 } 7873 7874 unsigned I = 0; 7875 QualType BaseType = getType(Base); 7876 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 7877 // If we don't know the array bound, conservatively assume we're looking at 7878 // the final array element. 7879 ++I; 7880 if (BaseType->isIncompleteArrayType()) 7881 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 7882 else 7883 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 7884 } 7885 7886 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 7887 const auto &Entry = LVal.Designator.Entries[I]; 7888 if (BaseType->isArrayType()) { 7889 // Because __builtin_object_size treats arrays as objects, we can ignore 7890 // the index iff this is the last array in the Designator. 7891 if (I + 1 == E) 7892 return true; 7893 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 7894 uint64_t Index = Entry.ArrayIndex; 7895 if (Index + 1 != CAT->getSize()) 7896 return false; 7897 BaseType = CAT->getElementType(); 7898 } else if (BaseType->isAnyComplexType()) { 7899 const auto *CT = BaseType->castAs<ComplexType>(); 7900 uint64_t Index = Entry.ArrayIndex; 7901 if (Index != 1) 7902 return false; 7903 BaseType = CT->getElementType(); 7904 } else if (auto *FD = getAsField(Entry)) { 7905 bool Invalid; 7906 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7907 return Invalid; 7908 BaseType = FD->getType(); 7909 } else { 7910 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 7911 return false; 7912 } 7913 } 7914 return true; 7915 } 7916 7917 /// Tests to see if the LValue has a user-specified designator (that isn't 7918 /// necessarily valid). Note that this always returns 'true' if the LValue has 7919 /// an unsized array as its first designator entry, because there's currently no 7920 /// way to tell if the user typed *foo or foo[0]. 7921 static bool refersToCompleteObject(const LValue &LVal) { 7922 if (LVal.Designator.Invalid) 7923 return false; 7924 7925 if (!LVal.Designator.Entries.empty()) 7926 return LVal.Designator.isMostDerivedAnUnsizedArray(); 7927 7928 if (!LVal.InvalidBase) 7929 return true; 7930 7931 // If `E` is a MemberExpr, then the first part of the designator is hiding in 7932 // the LValueBase. 7933 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 7934 return !E || !isa<MemberExpr>(E); 7935 } 7936 7937 /// Attempts to detect a user writing into a piece of memory that's impossible 7938 /// to figure out the size of by just using types. 7939 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 7940 const SubobjectDesignator &Designator = LVal.Designator; 7941 // Notes: 7942 // - Users can only write off of the end when we have an invalid base. Invalid 7943 // bases imply we don't know where the memory came from. 7944 // - We used to be a bit more aggressive here; we'd only be conservative if 7945 // the array at the end was flexible, or if it had 0 or 1 elements. This 7946 // broke some common standard library extensions (PR30346), but was 7947 // otherwise seemingly fine. It may be useful to reintroduce this behavior 7948 // with some sort of whitelist. OTOH, it seems that GCC is always 7949 // conservative with the last element in structs (if it's an array), so our 7950 // current behavior is more compatible than a whitelisting approach would 7951 // be. 7952 return LVal.InvalidBase && 7953 Designator.Entries.size() == Designator.MostDerivedPathLength && 7954 Designator.MostDerivedIsArrayElement && 7955 isDesignatorAtObjectEnd(Ctx, LVal); 7956 } 7957 7958 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 7959 /// Fails if the conversion would cause loss of precision. 7960 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 7961 CharUnits &Result) { 7962 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 7963 if (Int.ugt(CharUnitsMax)) 7964 return false; 7965 Result = CharUnits::fromQuantity(Int.getZExtValue()); 7966 return true; 7967 } 7968 7969 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 7970 /// determine how many bytes exist from the beginning of the object to either 7971 /// the end of the current subobject, or the end of the object itself, depending 7972 /// on what the LValue looks like + the value of Type. 7973 /// 7974 /// If this returns false, the value of Result is undefined. 7975 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 7976 unsigned Type, const LValue &LVal, 7977 CharUnits &EndOffset) { 7978 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 7979 7980 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 7981 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 7982 return false; 7983 return HandleSizeof(Info, ExprLoc, Ty, Result); 7984 }; 7985 7986 // We want to evaluate the size of the entire object. This is a valid fallback 7987 // for when Type=1 and the designator is invalid, because we're asked for an 7988 // upper-bound. 7989 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 7990 // Type=3 wants a lower bound, so we can't fall back to this. 7991 if (Type == 3 && !DetermineForCompleteObject) 7992 return false; 7993 7994 llvm::APInt APEndOffset; 7995 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7996 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 7997 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 7998 7999 if (LVal.InvalidBase) 8000 return false; 8001 8002 QualType BaseTy = getObjectType(LVal.getLValueBase()); 8003 return CheckedHandleSizeof(BaseTy, EndOffset); 8004 } 8005 8006 // We want to evaluate the size of a subobject. 8007 const SubobjectDesignator &Designator = LVal.Designator; 8008 8009 // The following is a moderately common idiom in C: 8010 // 8011 // struct Foo { int a; char c[1]; }; 8012 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 8013 // strcpy(&F->c[0], Bar); 8014 // 8015 // In order to not break too much legacy code, we need to support it. 8016 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 8017 // If we can resolve this to an alloc_size call, we can hand that back, 8018 // because we know for certain how many bytes there are to write to. 8019 llvm::APInt APEndOffset; 8020 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8021 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 8022 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 8023 8024 // If we cannot determine the size of the initial allocation, then we can't 8025 // given an accurate upper-bound. However, we are still able to give 8026 // conservative lower-bounds for Type=3. 8027 if (Type == 1) 8028 return false; 8029 } 8030 8031 CharUnits BytesPerElem; 8032 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 8033 return false; 8034 8035 // According to the GCC documentation, we want the size of the subobject 8036 // denoted by the pointer. But that's not quite right -- what we actually 8037 // want is the size of the immediately-enclosing array, if there is one. 8038 int64_t ElemsRemaining; 8039 if (Designator.MostDerivedIsArrayElement && 8040 Designator.Entries.size() == Designator.MostDerivedPathLength) { 8041 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 8042 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex; 8043 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 8044 } else { 8045 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 8046 } 8047 8048 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 8049 return true; 8050 } 8051 8052 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 8053 /// returns true and stores the result in @p Size. 8054 /// 8055 /// If @p WasError is non-null, this will report whether the failure to evaluate 8056 /// is to be treated as an Error in IntExprEvaluator. 8057 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 8058 EvalInfo &Info, uint64_t &Size) { 8059 // Determine the denoted object. 8060 LValue LVal; 8061 { 8062 // The operand of __builtin_object_size is never evaluated for side-effects. 8063 // If there are any, but we can determine the pointed-to object anyway, then 8064 // ignore the side-effects. 8065 SpeculativeEvaluationRAII SpeculativeEval(Info); 8066 IgnoreSideEffectsRAII Fold(Info); 8067 8068 if (E->isGLValue()) { 8069 // It's possible for us to be given GLValues if we're called via 8070 // Expr::tryEvaluateObjectSize. 8071 APValue RVal; 8072 if (!EvaluateAsRValue(Info, E, RVal)) 8073 return false; 8074 LVal.setFrom(Info.Ctx, RVal); 8075 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 8076 /*InvalidBaseOK=*/true)) 8077 return false; 8078 } 8079 8080 // If we point to before the start of the object, there are no accessible 8081 // bytes. 8082 if (LVal.getLValueOffset().isNegative()) { 8083 Size = 0; 8084 return true; 8085 } 8086 8087 CharUnits EndOffset; 8088 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 8089 return false; 8090 8091 // If we've fallen outside of the end offset, just pretend there's nothing to 8092 // write to/read from. 8093 if (EndOffset <= LVal.getLValueOffset()) 8094 Size = 0; 8095 else 8096 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 8097 return true; 8098 } 8099 8100 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) { 8101 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true); 8102 return ExprEvaluatorBaseTy::VisitConstantExpr(E); 8103 } 8104 8105 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 8106 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8107 return VisitBuiltinCallExpr(E, BuiltinOp); 8108 8109 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8110 } 8111 8112 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8113 unsigned BuiltinOp) { 8114 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 8115 default: 8116 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8117 8118 case Builtin::BI__builtin_object_size: { 8119 // The type was checked when we built the expression. 8120 unsigned Type = 8121 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 8122 assert(Type <= 3 && "unexpected type"); 8123 8124 uint64_t Size; 8125 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 8126 return Success(Size, E); 8127 8128 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 8129 return Success((Type & 2) ? 0 : -1, E); 8130 8131 // Expression had no side effects, but we couldn't statically determine the 8132 // size of the referenced object. 8133 switch (Info.EvalMode) { 8134 case EvalInfo::EM_ConstantExpression: 8135 case EvalInfo::EM_PotentialConstantExpression: 8136 case EvalInfo::EM_ConstantFold: 8137 case EvalInfo::EM_EvaluateForOverflow: 8138 case EvalInfo::EM_IgnoreSideEffects: 8139 // Leave it to IR generation. 8140 return Error(E); 8141 case EvalInfo::EM_ConstantExpressionUnevaluated: 8142 case EvalInfo::EM_PotentialConstantExpressionUnevaluated: 8143 // Reduce it to a constant now. 8144 return Success((Type & 2) ? 0 : -1, E); 8145 } 8146 8147 llvm_unreachable("unexpected EvalMode"); 8148 } 8149 8150 case Builtin::BI__builtin_os_log_format_buffer_size: { 8151 analyze_os_log::OSLogBufferLayout Layout; 8152 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 8153 return Success(Layout.size().getQuantity(), E); 8154 } 8155 8156 case Builtin::BI__builtin_bswap16: 8157 case Builtin::BI__builtin_bswap32: 8158 case Builtin::BI__builtin_bswap64: { 8159 APSInt Val; 8160 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8161 return false; 8162 8163 return Success(Val.byteSwap(), E); 8164 } 8165 8166 case Builtin::BI__builtin_classify_type: 8167 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 8168 8169 case Builtin::BI__builtin_clrsb: 8170 case Builtin::BI__builtin_clrsbl: 8171 case Builtin::BI__builtin_clrsbll: { 8172 APSInt Val; 8173 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8174 return false; 8175 8176 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 8177 } 8178 8179 case Builtin::BI__builtin_clz: 8180 case Builtin::BI__builtin_clzl: 8181 case Builtin::BI__builtin_clzll: 8182 case Builtin::BI__builtin_clzs: { 8183 APSInt Val; 8184 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8185 return false; 8186 if (!Val) 8187 return Error(E); 8188 8189 return Success(Val.countLeadingZeros(), E); 8190 } 8191 8192 case Builtin::BI__builtin_constant_p: { 8193 auto Arg = E->getArg(0); 8194 if (EvaluateBuiltinConstantP(Info.Ctx, Arg)) 8195 return Success(true, E); 8196 auto ArgTy = Arg->IgnoreImplicit()->getType(); 8197 if (!Info.InConstantContext && !Arg->HasSideEffects(Info.Ctx) && 8198 !ArgTy->isAggregateType() && !ArgTy->isPointerType()) { 8199 // We can delay calculation of __builtin_constant_p until after 8200 // inlining. Note: This diagnostic won't be shown to the user. 8201 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 8202 return false; 8203 } 8204 return Success(false, E); 8205 } 8206 8207 case Builtin::BI__builtin_ctz: 8208 case Builtin::BI__builtin_ctzl: 8209 case Builtin::BI__builtin_ctzll: 8210 case Builtin::BI__builtin_ctzs: { 8211 APSInt Val; 8212 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8213 return false; 8214 if (!Val) 8215 return Error(E); 8216 8217 return Success(Val.countTrailingZeros(), E); 8218 } 8219 8220 case Builtin::BI__builtin_eh_return_data_regno: { 8221 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 8222 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 8223 return Success(Operand, E); 8224 } 8225 8226 case Builtin::BI__builtin_expect: 8227 return Visit(E->getArg(0)); 8228 8229 case Builtin::BI__builtin_ffs: 8230 case Builtin::BI__builtin_ffsl: 8231 case Builtin::BI__builtin_ffsll: { 8232 APSInt Val; 8233 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8234 return false; 8235 8236 unsigned N = Val.countTrailingZeros(); 8237 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 8238 } 8239 8240 case Builtin::BI__builtin_fpclassify: { 8241 APFloat Val(0.0); 8242 if (!EvaluateFloat(E->getArg(5), Val, Info)) 8243 return false; 8244 unsigned Arg; 8245 switch (Val.getCategory()) { 8246 case APFloat::fcNaN: Arg = 0; break; 8247 case APFloat::fcInfinity: Arg = 1; break; 8248 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 8249 case APFloat::fcZero: Arg = 4; break; 8250 } 8251 return Visit(E->getArg(Arg)); 8252 } 8253 8254 case Builtin::BI__builtin_isinf_sign: { 8255 APFloat Val(0.0); 8256 return EvaluateFloat(E->getArg(0), Val, Info) && 8257 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 8258 } 8259 8260 case Builtin::BI__builtin_isinf: { 8261 APFloat Val(0.0); 8262 return EvaluateFloat(E->getArg(0), Val, Info) && 8263 Success(Val.isInfinity() ? 1 : 0, E); 8264 } 8265 8266 case Builtin::BI__builtin_isfinite: { 8267 APFloat Val(0.0); 8268 return EvaluateFloat(E->getArg(0), Val, Info) && 8269 Success(Val.isFinite() ? 1 : 0, E); 8270 } 8271 8272 case Builtin::BI__builtin_isnan: { 8273 APFloat Val(0.0); 8274 return EvaluateFloat(E->getArg(0), Val, Info) && 8275 Success(Val.isNaN() ? 1 : 0, E); 8276 } 8277 8278 case Builtin::BI__builtin_isnormal: { 8279 APFloat Val(0.0); 8280 return EvaluateFloat(E->getArg(0), Val, Info) && 8281 Success(Val.isNormal() ? 1 : 0, E); 8282 } 8283 8284 case Builtin::BI__builtin_parity: 8285 case Builtin::BI__builtin_parityl: 8286 case Builtin::BI__builtin_parityll: { 8287 APSInt Val; 8288 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8289 return false; 8290 8291 return Success(Val.countPopulation() % 2, E); 8292 } 8293 8294 case Builtin::BI__builtin_popcount: 8295 case Builtin::BI__builtin_popcountl: 8296 case Builtin::BI__builtin_popcountll: { 8297 APSInt Val; 8298 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8299 return false; 8300 8301 return Success(Val.countPopulation(), E); 8302 } 8303 8304 case Builtin::BIstrlen: 8305 case Builtin::BIwcslen: 8306 // A call to strlen is not a constant expression. 8307 if (Info.getLangOpts().CPlusPlus11) 8308 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8309 << /*isConstexpr*/0 << /*isConstructor*/0 8310 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8311 else 8312 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8313 LLVM_FALLTHROUGH; 8314 case Builtin::BI__builtin_strlen: 8315 case Builtin::BI__builtin_wcslen: { 8316 // As an extension, we support __builtin_strlen() as a constant expression, 8317 // and support folding strlen() to a constant. 8318 LValue String; 8319 if (!EvaluatePointer(E->getArg(0), String, Info)) 8320 return false; 8321 8322 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 8323 8324 // Fast path: if it's a string literal, search the string value. 8325 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 8326 String.getLValueBase().dyn_cast<const Expr *>())) { 8327 // The string literal may have embedded null characters. Find the first 8328 // one and truncate there. 8329 StringRef Str = S->getBytes(); 8330 int64_t Off = String.Offset.getQuantity(); 8331 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 8332 S->getCharByteWidth() == 1 && 8333 // FIXME: Add fast-path for wchar_t too. 8334 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 8335 Str = Str.substr(Off); 8336 8337 StringRef::size_type Pos = Str.find(0); 8338 if (Pos != StringRef::npos) 8339 Str = Str.substr(0, Pos); 8340 8341 return Success(Str.size(), E); 8342 } 8343 8344 // Fall through to slow path to issue appropriate diagnostic. 8345 } 8346 8347 // Slow path: scan the bytes of the string looking for the terminating 0. 8348 for (uint64_t Strlen = 0; /**/; ++Strlen) { 8349 APValue Char; 8350 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 8351 !Char.isInt()) 8352 return false; 8353 if (!Char.getInt()) 8354 return Success(Strlen, E); 8355 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 8356 return false; 8357 } 8358 } 8359 8360 case Builtin::BIstrcmp: 8361 case Builtin::BIwcscmp: 8362 case Builtin::BIstrncmp: 8363 case Builtin::BIwcsncmp: 8364 case Builtin::BImemcmp: 8365 case Builtin::BIwmemcmp: 8366 // A call to strlen is not a constant expression. 8367 if (Info.getLangOpts().CPlusPlus11) 8368 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8369 << /*isConstexpr*/0 << /*isConstructor*/0 8370 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8371 else 8372 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8373 LLVM_FALLTHROUGH; 8374 case Builtin::BI__builtin_strcmp: 8375 case Builtin::BI__builtin_wcscmp: 8376 case Builtin::BI__builtin_strncmp: 8377 case Builtin::BI__builtin_wcsncmp: 8378 case Builtin::BI__builtin_memcmp: 8379 case Builtin::BI__builtin_wmemcmp: { 8380 LValue String1, String2; 8381 if (!EvaluatePointer(E->getArg(0), String1, Info) || 8382 !EvaluatePointer(E->getArg(1), String2, Info)) 8383 return false; 8384 8385 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 8386 8387 uint64_t MaxLength = uint64_t(-1); 8388 if (BuiltinOp != Builtin::BIstrcmp && 8389 BuiltinOp != Builtin::BIwcscmp && 8390 BuiltinOp != Builtin::BI__builtin_strcmp && 8391 BuiltinOp != Builtin::BI__builtin_wcscmp) { 8392 APSInt N; 8393 if (!EvaluateInteger(E->getArg(2), N, Info)) 8394 return false; 8395 MaxLength = N.getExtValue(); 8396 } 8397 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp && 8398 BuiltinOp != Builtin::BIwmemcmp && 8399 BuiltinOp != Builtin::BI__builtin_memcmp && 8400 BuiltinOp != Builtin::BI__builtin_wmemcmp); 8401 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 8402 BuiltinOp == Builtin::BIwcsncmp || 8403 BuiltinOp == Builtin::BIwmemcmp || 8404 BuiltinOp == Builtin::BI__builtin_wcscmp || 8405 BuiltinOp == Builtin::BI__builtin_wcsncmp || 8406 BuiltinOp == Builtin::BI__builtin_wmemcmp; 8407 for (; MaxLength; --MaxLength) { 8408 APValue Char1, Char2; 8409 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) || 8410 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) || 8411 !Char1.isInt() || !Char2.isInt()) 8412 return false; 8413 if (Char1.getInt() != Char2.getInt()) { 8414 if (IsWide) // wmemcmp compares with wchar_t signedness. 8415 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 8416 // memcmp always compares unsigned chars. 8417 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 8418 } 8419 if (StopAtNull && !Char1.getInt()) 8420 return Success(0, E); 8421 assert(!(StopAtNull && !Char2.getInt())); 8422 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) || 8423 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1)) 8424 return false; 8425 } 8426 // We hit the strncmp / memcmp limit. 8427 return Success(0, E); 8428 } 8429 8430 case Builtin::BI__atomic_always_lock_free: 8431 case Builtin::BI__atomic_is_lock_free: 8432 case Builtin::BI__c11_atomic_is_lock_free: { 8433 APSInt SizeVal; 8434 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 8435 return false; 8436 8437 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 8438 // of two less than the maximum inline atomic width, we know it is 8439 // lock-free. If the size isn't a power of two, or greater than the 8440 // maximum alignment where we promote atomics, we know it is not lock-free 8441 // (at least not in the sense of atomic_is_lock_free). Otherwise, 8442 // the answer can only be determined at runtime; for example, 16-byte 8443 // atomics have lock-free implementations on some, but not all, 8444 // x86-64 processors. 8445 8446 // Check power-of-two. 8447 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 8448 if (Size.isPowerOfTwo()) { 8449 // Check against inlining width. 8450 unsigned InlineWidthBits = 8451 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 8452 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 8453 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 8454 Size == CharUnits::One() || 8455 E->getArg(1)->isNullPointerConstant(Info.Ctx, 8456 Expr::NPC_NeverValueDependent)) 8457 // OK, we will inline appropriately-aligned operations of this size, 8458 // and _Atomic(T) is appropriately-aligned. 8459 return Success(1, E); 8460 8461 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 8462 castAs<PointerType>()->getPointeeType(); 8463 if (!PointeeType->isIncompleteType() && 8464 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 8465 // OK, we will inline operations on this object. 8466 return Success(1, E); 8467 } 8468 } 8469 } 8470 8471 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 8472 Success(0, E) : Error(E); 8473 } 8474 case Builtin::BIomp_is_initial_device: 8475 // We can decide statically which value the runtime would return if called. 8476 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 8477 case Builtin::BI__builtin_add_overflow: 8478 case Builtin::BI__builtin_sub_overflow: 8479 case Builtin::BI__builtin_mul_overflow: 8480 case Builtin::BI__builtin_sadd_overflow: 8481 case Builtin::BI__builtin_uadd_overflow: 8482 case Builtin::BI__builtin_uaddl_overflow: 8483 case Builtin::BI__builtin_uaddll_overflow: 8484 case Builtin::BI__builtin_usub_overflow: 8485 case Builtin::BI__builtin_usubl_overflow: 8486 case Builtin::BI__builtin_usubll_overflow: 8487 case Builtin::BI__builtin_umul_overflow: 8488 case Builtin::BI__builtin_umull_overflow: 8489 case Builtin::BI__builtin_umulll_overflow: 8490 case Builtin::BI__builtin_saddl_overflow: 8491 case Builtin::BI__builtin_saddll_overflow: 8492 case Builtin::BI__builtin_ssub_overflow: 8493 case Builtin::BI__builtin_ssubl_overflow: 8494 case Builtin::BI__builtin_ssubll_overflow: 8495 case Builtin::BI__builtin_smul_overflow: 8496 case Builtin::BI__builtin_smull_overflow: 8497 case Builtin::BI__builtin_smulll_overflow: { 8498 LValue ResultLValue; 8499 APSInt LHS, RHS; 8500 8501 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 8502 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 8503 !EvaluateInteger(E->getArg(1), RHS, Info) || 8504 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 8505 return false; 8506 8507 APSInt Result; 8508 bool DidOverflow = false; 8509 8510 // If the types don't have to match, enlarge all 3 to the largest of them. 8511 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 8512 BuiltinOp == Builtin::BI__builtin_sub_overflow || 8513 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 8514 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 8515 ResultType->isSignedIntegerOrEnumerationType(); 8516 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 8517 ResultType->isSignedIntegerOrEnumerationType(); 8518 uint64_t LHSSize = LHS.getBitWidth(); 8519 uint64_t RHSSize = RHS.getBitWidth(); 8520 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 8521 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 8522 8523 // Add an additional bit if the signedness isn't uniformly agreed to. We 8524 // could do this ONLY if there is a signed and an unsigned that both have 8525 // MaxBits, but the code to check that is pretty nasty. The issue will be 8526 // caught in the shrink-to-result later anyway. 8527 if (IsSigned && !AllSigned) 8528 ++MaxBits; 8529 8530 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits), 8531 !IsSigned); 8532 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits), 8533 !IsSigned); 8534 Result = APSInt(MaxBits, !IsSigned); 8535 } 8536 8537 // Find largest int. 8538 switch (BuiltinOp) { 8539 default: 8540 llvm_unreachable("Invalid value for BuiltinOp"); 8541 case Builtin::BI__builtin_add_overflow: 8542 case Builtin::BI__builtin_sadd_overflow: 8543 case Builtin::BI__builtin_saddl_overflow: 8544 case Builtin::BI__builtin_saddll_overflow: 8545 case Builtin::BI__builtin_uadd_overflow: 8546 case Builtin::BI__builtin_uaddl_overflow: 8547 case Builtin::BI__builtin_uaddll_overflow: 8548 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 8549 : LHS.uadd_ov(RHS, DidOverflow); 8550 break; 8551 case Builtin::BI__builtin_sub_overflow: 8552 case Builtin::BI__builtin_ssub_overflow: 8553 case Builtin::BI__builtin_ssubl_overflow: 8554 case Builtin::BI__builtin_ssubll_overflow: 8555 case Builtin::BI__builtin_usub_overflow: 8556 case Builtin::BI__builtin_usubl_overflow: 8557 case Builtin::BI__builtin_usubll_overflow: 8558 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 8559 : LHS.usub_ov(RHS, DidOverflow); 8560 break; 8561 case Builtin::BI__builtin_mul_overflow: 8562 case Builtin::BI__builtin_smul_overflow: 8563 case Builtin::BI__builtin_smull_overflow: 8564 case Builtin::BI__builtin_smulll_overflow: 8565 case Builtin::BI__builtin_umul_overflow: 8566 case Builtin::BI__builtin_umull_overflow: 8567 case Builtin::BI__builtin_umulll_overflow: 8568 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 8569 : LHS.umul_ov(RHS, DidOverflow); 8570 break; 8571 } 8572 8573 // In the case where multiple sizes are allowed, truncate and see if 8574 // the values are the same. 8575 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 8576 BuiltinOp == Builtin::BI__builtin_sub_overflow || 8577 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 8578 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 8579 // since it will give us the behavior of a TruncOrSelf in the case where 8580 // its parameter <= its size. We previously set Result to be at least the 8581 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 8582 // will work exactly like TruncOrSelf. 8583 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 8584 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 8585 8586 if (!APSInt::isSameValue(Temp, Result)) 8587 DidOverflow = true; 8588 Result = Temp; 8589 } 8590 8591 APValue APV{Result}; 8592 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 8593 return false; 8594 return Success(DidOverflow, E); 8595 } 8596 } 8597 } 8598 8599 /// Determine whether this is a pointer past the end of the complete 8600 /// object referred to by the lvalue. 8601 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 8602 const LValue &LV) { 8603 // A null pointer can be viewed as being "past the end" but we don't 8604 // choose to look at it that way here. 8605 if (!LV.getLValueBase()) 8606 return false; 8607 8608 // If the designator is valid and refers to a subobject, we're not pointing 8609 // past the end. 8610 if (!LV.getLValueDesignator().Invalid && 8611 !LV.getLValueDesignator().isOnePastTheEnd()) 8612 return false; 8613 8614 // A pointer to an incomplete type might be past-the-end if the type's size is 8615 // zero. We cannot tell because the type is incomplete. 8616 QualType Ty = getType(LV.getLValueBase()); 8617 if (Ty->isIncompleteType()) 8618 return true; 8619 8620 // We're a past-the-end pointer if we point to the byte after the object, 8621 // no matter what our type or path is. 8622 auto Size = Ctx.getTypeSizeInChars(Ty); 8623 return LV.getLValueOffset() == Size; 8624 } 8625 8626 namespace { 8627 8628 /// Data recursive integer evaluator of certain binary operators. 8629 /// 8630 /// We use a data recursive algorithm for binary operators so that we are able 8631 /// to handle extreme cases of chained binary operators without causing stack 8632 /// overflow. 8633 class DataRecursiveIntBinOpEvaluator { 8634 struct EvalResult { 8635 APValue Val; 8636 bool Failed; 8637 8638 EvalResult() : Failed(false) { } 8639 8640 void swap(EvalResult &RHS) { 8641 Val.swap(RHS.Val); 8642 Failed = RHS.Failed; 8643 RHS.Failed = false; 8644 } 8645 }; 8646 8647 struct Job { 8648 const Expr *E; 8649 EvalResult LHSResult; // meaningful only for binary operator expression. 8650 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 8651 8652 Job() = default; 8653 Job(Job &&) = default; 8654 8655 void startSpeculativeEval(EvalInfo &Info) { 8656 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 8657 } 8658 8659 private: 8660 SpeculativeEvaluationRAII SpecEvalRAII; 8661 }; 8662 8663 SmallVector<Job, 16> Queue; 8664 8665 IntExprEvaluator &IntEval; 8666 EvalInfo &Info; 8667 APValue &FinalResult; 8668 8669 public: 8670 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 8671 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 8672 8673 /// True if \param E is a binary operator that we are going to handle 8674 /// data recursively. 8675 /// We handle binary operators that are comma, logical, or that have operands 8676 /// with integral or enumeration type. 8677 static bool shouldEnqueue(const BinaryOperator *E) { 8678 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 8679 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 8680 E->getLHS()->getType()->isIntegralOrEnumerationType() && 8681 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8682 } 8683 8684 bool Traverse(const BinaryOperator *E) { 8685 enqueue(E); 8686 EvalResult PrevResult; 8687 while (!Queue.empty()) 8688 process(PrevResult); 8689 8690 if (PrevResult.Failed) return false; 8691 8692 FinalResult.swap(PrevResult.Val); 8693 return true; 8694 } 8695 8696 private: 8697 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 8698 return IntEval.Success(Value, E, Result); 8699 } 8700 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 8701 return IntEval.Success(Value, E, Result); 8702 } 8703 bool Error(const Expr *E) { 8704 return IntEval.Error(E); 8705 } 8706 bool Error(const Expr *E, diag::kind D) { 8707 return IntEval.Error(E, D); 8708 } 8709 8710 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 8711 return Info.CCEDiag(E, D); 8712 } 8713 8714 // Returns true if visiting the RHS is necessary, false otherwise. 8715 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8716 bool &SuppressRHSDiags); 8717 8718 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8719 const BinaryOperator *E, APValue &Result); 8720 8721 void EvaluateExpr(const Expr *E, EvalResult &Result) { 8722 Result.Failed = !Evaluate(Result.Val, Info, E); 8723 if (Result.Failed) 8724 Result.Val = APValue(); 8725 } 8726 8727 void process(EvalResult &Result); 8728 8729 void enqueue(const Expr *E) { 8730 E = E->IgnoreParens(); 8731 Queue.resize(Queue.size()+1); 8732 Queue.back().E = E; 8733 Queue.back().Kind = Job::AnyExprKind; 8734 } 8735 }; 8736 8737 } 8738 8739 bool DataRecursiveIntBinOpEvaluator:: 8740 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8741 bool &SuppressRHSDiags) { 8742 if (E->getOpcode() == BO_Comma) { 8743 // Ignore LHS but note if we could not evaluate it. 8744 if (LHSResult.Failed) 8745 return Info.noteSideEffect(); 8746 return true; 8747 } 8748 8749 if (E->isLogicalOp()) { 8750 bool LHSAsBool; 8751 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 8752 // We were able to evaluate the LHS, see if we can get away with not 8753 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 8754 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 8755 Success(LHSAsBool, E, LHSResult.Val); 8756 return false; // Ignore RHS 8757 } 8758 } else { 8759 LHSResult.Failed = true; 8760 8761 // Since we weren't able to evaluate the left hand side, it 8762 // might have had side effects. 8763 if (!Info.noteSideEffect()) 8764 return false; 8765 8766 // We can't evaluate the LHS; however, sometimes the result 8767 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8768 // Don't ignore RHS and suppress diagnostics from this arm. 8769 SuppressRHSDiags = true; 8770 } 8771 8772 return true; 8773 } 8774 8775 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8776 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8777 8778 if (LHSResult.Failed && !Info.noteFailure()) 8779 return false; // Ignore RHS; 8780 8781 return true; 8782 } 8783 8784 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 8785 bool IsSub) { 8786 // Compute the new offset in the appropriate width, wrapping at 64 bits. 8787 // FIXME: When compiling for a 32-bit target, we should use 32-bit 8788 // offsets. 8789 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 8790 CharUnits &Offset = LVal.getLValueOffset(); 8791 uint64_t Offset64 = Offset.getQuantity(); 8792 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 8793 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 8794 : Offset64 + Index64); 8795 } 8796 8797 bool DataRecursiveIntBinOpEvaluator:: 8798 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8799 const BinaryOperator *E, APValue &Result) { 8800 if (E->getOpcode() == BO_Comma) { 8801 if (RHSResult.Failed) 8802 return false; 8803 Result = RHSResult.Val; 8804 return true; 8805 } 8806 8807 if (E->isLogicalOp()) { 8808 bool lhsResult, rhsResult; 8809 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 8810 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 8811 8812 if (LHSIsOK) { 8813 if (RHSIsOK) { 8814 if (E->getOpcode() == BO_LOr) 8815 return Success(lhsResult || rhsResult, E, Result); 8816 else 8817 return Success(lhsResult && rhsResult, E, Result); 8818 } 8819 } else { 8820 if (RHSIsOK) { 8821 // We can't evaluate the LHS; however, sometimes the result 8822 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8823 if (rhsResult == (E->getOpcode() == BO_LOr)) 8824 return Success(rhsResult, E, Result); 8825 } 8826 } 8827 8828 return false; 8829 } 8830 8831 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8832 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8833 8834 if (LHSResult.Failed || RHSResult.Failed) 8835 return false; 8836 8837 const APValue &LHSVal = LHSResult.Val; 8838 const APValue &RHSVal = RHSResult.Val; 8839 8840 // Handle cases like (unsigned long)&a + 4. 8841 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 8842 Result = LHSVal; 8843 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 8844 return true; 8845 } 8846 8847 // Handle cases like 4 + (unsigned long)&a 8848 if (E->getOpcode() == BO_Add && 8849 RHSVal.isLValue() && LHSVal.isInt()) { 8850 Result = RHSVal; 8851 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 8852 return true; 8853 } 8854 8855 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 8856 // Handle (intptr_t)&&A - (intptr_t)&&B. 8857 if (!LHSVal.getLValueOffset().isZero() || 8858 !RHSVal.getLValueOffset().isZero()) 8859 return false; 8860 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 8861 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 8862 if (!LHSExpr || !RHSExpr) 8863 return false; 8864 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 8865 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 8866 if (!LHSAddrExpr || !RHSAddrExpr) 8867 return false; 8868 // Make sure both labels come from the same function. 8869 if (LHSAddrExpr->getLabel()->getDeclContext() != 8870 RHSAddrExpr->getLabel()->getDeclContext()) 8871 return false; 8872 Result = APValue(LHSAddrExpr, RHSAddrExpr); 8873 return true; 8874 } 8875 8876 // All the remaining cases expect both operands to be an integer 8877 if (!LHSVal.isInt() || !RHSVal.isInt()) 8878 return Error(E); 8879 8880 // Set up the width and signedness manually, in case it can't be deduced 8881 // from the operation we're performing. 8882 // FIXME: Don't do this in the cases where we can deduce it. 8883 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 8884 E->getType()->isUnsignedIntegerOrEnumerationType()); 8885 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 8886 RHSVal.getInt(), Value)) 8887 return false; 8888 return Success(Value, E, Result); 8889 } 8890 8891 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 8892 Job &job = Queue.back(); 8893 8894 switch (job.Kind) { 8895 case Job::AnyExprKind: { 8896 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 8897 if (shouldEnqueue(Bop)) { 8898 job.Kind = Job::BinOpKind; 8899 enqueue(Bop->getLHS()); 8900 return; 8901 } 8902 } 8903 8904 EvaluateExpr(job.E, Result); 8905 Queue.pop_back(); 8906 return; 8907 } 8908 8909 case Job::BinOpKind: { 8910 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8911 bool SuppressRHSDiags = false; 8912 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 8913 Queue.pop_back(); 8914 return; 8915 } 8916 if (SuppressRHSDiags) 8917 job.startSpeculativeEval(Info); 8918 job.LHSResult.swap(Result); 8919 job.Kind = Job::BinOpVisitedLHSKind; 8920 enqueue(Bop->getRHS()); 8921 return; 8922 } 8923 8924 case Job::BinOpVisitedLHSKind: { 8925 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8926 EvalResult RHS; 8927 RHS.swap(Result); 8928 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 8929 Queue.pop_back(); 8930 return; 8931 } 8932 } 8933 8934 llvm_unreachable("Invalid Job::Kind!"); 8935 } 8936 8937 namespace { 8938 /// Used when we determine that we should fail, but can keep evaluating prior to 8939 /// noting that we had a failure. 8940 class DelayedNoteFailureRAII { 8941 EvalInfo &Info; 8942 bool NoteFailure; 8943 8944 public: 8945 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 8946 : Info(Info), NoteFailure(NoteFailure) {} 8947 ~DelayedNoteFailureRAII() { 8948 if (NoteFailure) { 8949 bool ContinueAfterFailure = Info.noteFailure(); 8950 (void)ContinueAfterFailure; 8951 assert(ContinueAfterFailure && 8952 "Shouldn't have kept evaluating on failure."); 8953 } 8954 } 8955 }; 8956 } 8957 8958 template <class SuccessCB, class AfterCB> 8959 static bool 8960 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 8961 SuccessCB &&Success, AfterCB &&DoAfter) { 8962 assert(E->isComparisonOp() && "expected comparison operator"); 8963 assert((E->getOpcode() == BO_Cmp || 8964 E->getType()->isIntegralOrEnumerationType()) && 8965 "unsupported binary expression evaluation"); 8966 auto Error = [&](const Expr *E) { 8967 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 8968 return false; 8969 }; 8970 8971 using CCR = ComparisonCategoryResult; 8972 bool IsRelational = E->isRelationalOp(); 8973 bool IsEquality = E->isEqualityOp(); 8974 if (E->getOpcode() == BO_Cmp) { 8975 const ComparisonCategoryInfo &CmpInfo = 8976 Info.Ctx.CompCategories.getInfoForType(E->getType()); 8977 IsRelational = CmpInfo.isOrdered(); 8978 IsEquality = CmpInfo.isEquality(); 8979 } 8980 8981 QualType LHSTy = E->getLHS()->getType(); 8982 QualType RHSTy = E->getRHS()->getType(); 8983 8984 if (LHSTy->isIntegralOrEnumerationType() && 8985 RHSTy->isIntegralOrEnumerationType()) { 8986 APSInt LHS, RHS; 8987 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 8988 if (!LHSOK && !Info.noteFailure()) 8989 return false; 8990 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 8991 return false; 8992 if (LHS < RHS) 8993 return Success(CCR::Less, E); 8994 if (LHS > RHS) 8995 return Success(CCR::Greater, E); 8996 return Success(CCR::Equal, E); 8997 } 8998 8999 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 9000 ComplexValue LHS, RHS; 9001 bool LHSOK; 9002 if (E->isAssignmentOp()) { 9003 LValue LV; 9004 EvaluateLValue(E->getLHS(), LV, Info); 9005 LHSOK = false; 9006 } else if (LHSTy->isRealFloatingType()) { 9007 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 9008 if (LHSOK) { 9009 LHS.makeComplexFloat(); 9010 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 9011 } 9012 } else { 9013 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 9014 } 9015 if (!LHSOK && !Info.noteFailure()) 9016 return false; 9017 9018 if (E->getRHS()->getType()->isRealFloatingType()) { 9019 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 9020 return false; 9021 RHS.makeComplexFloat(); 9022 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 9023 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 9024 return false; 9025 9026 if (LHS.isComplexFloat()) { 9027 APFloat::cmpResult CR_r = 9028 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 9029 APFloat::cmpResult CR_i = 9030 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 9031 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 9032 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 9033 } else { 9034 assert(IsEquality && "invalid complex comparison"); 9035 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 9036 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 9037 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 9038 } 9039 } 9040 9041 if (LHSTy->isRealFloatingType() && 9042 RHSTy->isRealFloatingType()) { 9043 APFloat RHS(0.0), LHS(0.0); 9044 9045 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 9046 if (!LHSOK && !Info.noteFailure()) 9047 return false; 9048 9049 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 9050 return false; 9051 9052 assert(E->isComparisonOp() && "Invalid binary operator!"); 9053 auto GetCmpRes = [&]() { 9054 switch (LHS.compare(RHS)) { 9055 case APFloat::cmpEqual: 9056 return CCR::Equal; 9057 case APFloat::cmpLessThan: 9058 return CCR::Less; 9059 case APFloat::cmpGreaterThan: 9060 return CCR::Greater; 9061 case APFloat::cmpUnordered: 9062 return CCR::Unordered; 9063 } 9064 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 9065 }; 9066 return Success(GetCmpRes(), E); 9067 } 9068 9069 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 9070 LValue LHSValue, RHSValue; 9071 9072 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 9073 if (!LHSOK && !Info.noteFailure()) 9074 return false; 9075 9076 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9077 return false; 9078 9079 // Reject differing bases from the normal codepath; we special-case 9080 // comparisons to null. 9081 if (!HasSameBase(LHSValue, RHSValue)) { 9082 // Inequalities and subtractions between unrelated pointers have 9083 // unspecified or undefined behavior. 9084 if (!IsEquality) 9085 return Error(E); 9086 // A constant address may compare equal to the address of a symbol. 9087 // The one exception is that address of an object cannot compare equal 9088 // to a null pointer constant. 9089 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 9090 (!RHSValue.Base && !RHSValue.Offset.isZero())) 9091 return Error(E); 9092 // It's implementation-defined whether distinct literals will have 9093 // distinct addresses. In clang, the result of such a comparison is 9094 // unspecified, so it is not a constant expression. However, we do know 9095 // that the address of a literal will be non-null. 9096 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 9097 LHSValue.Base && RHSValue.Base) 9098 return Error(E); 9099 // We can't tell whether weak symbols will end up pointing to the same 9100 // object. 9101 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 9102 return Error(E); 9103 // We can't compare the address of the start of one object with the 9104 // past-the-end address of another object, per C++ DR1652. 9105 if ((LHSValue.Base && LHSValue.Offset.isZero() && 9106 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 9107 (RHSValue.Base && RHSValue.Offset.isZero() && 9108 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 9109 return Error(E); 9110 // We can't tell whether an object is at the same address as another 9111 // zero sized object. 9112 if ((RHSValue.Base && isZeroSized(LHSValue)) || 9113 (LHSValue.Base && isZeroSized(RHSValue))) 9114 return Error(E); 9115 return Success(CCR::Nonequal, E); 9116 } 9117 9118 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 9119 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 9120 9121 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 9122 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 9123 9124 // C++11 [expr.rel]p3: 9125 // Pointers to void (after pointer conversions) can be compared, with a 9126 // result defined as follows: If both pointers represent the same 9127 // address or are both the null pointer value, the result is true if the 9128 // operator is <= or >= and false otherwise; otherwise the result is 9129 // unspecified. 9130 // We interpret this as applying to pointers to *cv* void. 9131 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 9132 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 9133 9134 // C++11 [expr.rel]p2: 9135 // - If two pointers point to non-static data members of the same object, 9136 // or to subobjects or array elements fo such members, recursively, the 9137 // pointer to the later declared member compares greater provided the 9138 // two members have the same access control and provided their class is 9139 // not a union. 9140 // [...] 9141 // - Otherwise pointer comparisons are unspecified. 9142 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 9143 bool WasArrayIndex; 9144 unsigned Mismatch = FindDesignatorMismatch( 9145 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 9146 // At the point where the designators diverge, the comparison has a 9147 // specified value if: 9148 // - we are comparing array indices 9149 // - we are comparing fields of a union, or fields with the same access 9150 // Otherwise, the result is unspecified and thus the comparison is not a 9151 // constant expression. 9152 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 9153 Mismatch < RHSDesignator.Entries.size()) { 9154 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 9155 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 9156 if (!LF && !RF) 9157 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 9158 else if (!LF) 9159 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 9160 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 9161 << RF->getParent() << RF; 9162 else if (!RF) 9163 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 9164 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 9165 << LF->getParent() << LF; 9166 else if (!LF->getParent()->isUnion() && 9167 LF->getAccess() != RF->getAccess()) 9168 Info.CCEDiag(E, 9169 diag::note_constexpr_pointer_comparison_differing_access) 9170 << LF << LF->getAccess() << RF << RF->getAccess() 9171 << LF->getParent(); 9172 } 9173 } 9174 9175 // The comparison here must be unsigned, and performed with the same 9176 // width as the pointer. 9177 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 9178 uint64_t CompareLHS = LHSOffset.getQuantity(); 9179 uint64_t CompareRHS = RHSOffset.getQuantity(); 9180 assert(PtrSize <= 64 && "Unexpected pointer width"); 9181 uint64_t Mask = ~0ULL >> (64 - PtrSize); 9182 CompareLHS &= Mask; 9183 CompareRHS &= Mask; 9184 9185 // If there is a base and this is a relational operator, we can only 9186 // compare pointers within the object in question; otherwise, the result 9187 // depends on where the object is located in memory. 9188 if (!LHSValue.Base.isNull() && IsRelational) { 9189 QualType BaseTy = getType(LHSValue.Base); 9190 if (BaseTy->isIncompleteType()) 9191 return Error(E); 9192 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 9193 uint64_t OffsetLimit = Size.getQuantity(); 9194 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 9195 return Error(E); 9196 } 9197 9198 if (CompareLHS < CompareRHS) 9199 return Success(CCR::Less, E); 9200 if (CompareLHS > CompareRHS) 9201 return Success(CCR::Greater, E); 9202 return Success(CCR::Equal, E); 9203 } 9204 9205 if (LHSTy->isMemberPointerType()) { 9206 assert(IsEquality && "unexpected member pointer operation"); 9207 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 9208 9209 MemberPtr LHSValue, RHSValue; 9210 9211 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 9212 if (!LHSOK && !Info.noteFailure()) 9213 return false; 9214 9215 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9216 return false; 9217 9218 // C++11 [expr.eq]p2: 9219 // If both operands are null, they compare equal. Otherwise if only one is 9220 // null, they compare unequal. 9221 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 9222 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 9223 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 9224 } 9225 9226 // Otherwise if either is a pointer to a virtual member function, the 9227 // result is unspecified. 9228 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 9229 if (MD->isVirtual()) 9230 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 9231 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 9232 if (MD->isVirtual()) 9233 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 9234 9235 // Otherwise they compare equal if and only if they would refer to the 9236 // same member of the same most derived object or the same subobject if 9237 // they were dereferenced with a hypothetical object of the associated 9238 // class type. 9239 bool Equal = LHSValue == RHSValue; 9240 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 9241 } 9242 9243 if (LHSTy->isNullPtrType()) { 9244 assert(E->isComparisonOp() && "unexpected nullptr operation"); 9245 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 9246 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 9247 // are compared, the result is true of the operator is <=, >= or ==, and 9248 // false otherwise. 9249 return Success(CCR::Equal, E); 9250 } 9251 9252 return DoAfter(); 9253 } 9254 9255 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 9256 if (!CheckLiteralType(Info, E)) 9257 return false; 9258 9259 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 9260 const BinaryOperator *E) { 9261 // Evaluation succeeded. Lookup the information for the comparison category 9262 // type and fetch the VarDecl for the result. 9263 const ComparisonCategoryInfo &CmpInfo = 9264 Info.Ctx.CompCategories.getInfoForType(E->getType()); 9265 const VarDecl *VD = 9266 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; 9267 // Check and evaluate the result as a constant expression. 9268 LValue LV; 9269 LV.set(VD); 9270 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 9271 return false; 9272 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 9273 }; 9274 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 9275 return ExprEvaluatorBaseTy::VisitBinCmp(E); 9276 }); 9277 } 9278 9279 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9280 // We don't call noteFailure immediately because the assignment happens after 9281 // we evaluate LHS and RHS. 9282 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 9283 return Error(E); 9284 9285 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 9286 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 9287 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 9288 9289 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 9290 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 9291 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 9292 9293 if (E->isComparisonOp()) { 9294 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way 9295 // comparisons and then translating the result. 9296 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 9297 const BinaryOperator *E) { 9298 using CCR = ComparisonCategoryResult; 9299 bool IsEqual = ResKind == CCR::Equal, 9300 IsLess = ResKind == CCR::Less, 9301 IsGreater = ResKind == CCR::Greater; 9302 auto Op = E->getOpcode(); 9303 switch (Op) { 9304 default: 9305 llvm_unreachable("unsupported binary operator"); 9306 case BO_EQ: 9307 case BO_NE: 9308 return Success(IsEqual == (Op == BO_EQ), E); 9309 case BO_LT: return Success(IsLess, E); 9310 case BO_GT: return Success(IsGreater, E); 9311 case BO_LE: return Success(IsEqual || IsLess, E); 9312 case BO_GE: return Success(IsEqual || IsGreater, E); 9313 } 9314 }; 9315 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 9316 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9317 }); 9318 } 9319 9320 QualType LHSTy = E->getLHS()->getType(); 9321 QualType RHSTy = E->getRHS()->getType(); 9322 9323 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 9324 E->getOpcode() == BO_Sub) { 9325 LValue LHSValue, RHSValue; 9326 9327 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 9328 if (!LHSOK && !Info.noteFailure()) 9329 return false; 9330 9331 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9332 return false; 9333 9334 // Reject differing bases from the normal codepath; we special-case 9335 // comparisons to null. 9336 if (!HasSameBase(LHSValue, RHSValue)) { 9337 // Handle &&A - &&B. 9338 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 9339 return Error(E); 9340 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 9341 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 9342 if (!LHSExpr || !RHSExpr) 9343 return Error(E); 9344 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 9345 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 9346 if (!LHSAddrExpr || !RHSAddrExpr) 9347 return Error(E); 9348 // Make sure both labels come from the same function. 9349 if (LHSAddrExpr->getLabel()->getDeclContext() != 9350 RHSAddrExpr->getLabel()->getDeclContext()) 9351 return Error(E); 9352 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 9353 } 9354 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 9355 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 9356 9357 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 9358 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 9359 9360 // C++11 [expr.add]p6: 9361 // Unless both pointers point to elements of the same array object, or 9362 // one past the last element of the array object, the behavior is 9363 // undefined. 9364 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 9365 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 9366 RHSDesignator)) 9367 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 9368 9369 QualType Type = E->getLHS()->getType(); 9370 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 9371 9372 CharUnits ElementSize; 9373 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 9374 return false; 9375 9376 // As an extension, a type may have zero size (empty struct or union in 9377 // C, array of zero length). Pointer subtraction in such cases has 9378 // undefined behavior, so is not constant. 9379 if (ElementSize.isZero()) { 9380 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 9381 << ElementType; 9382 return false; 9383 } 9384 9385 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 9386 // and produce incorrect results when it overflows. Such behavior 9387 // appears to be non-conforming, but is common, so perhaps we should 9388 // assume the standard intended for such cases to be undefined behavior 9389 // and check for them. 9390 9391 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 9392 // overflow in the final conversion to ptrdiff_t. 9393 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 9394 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 9395 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 9396 false); 9397 APSInt TrueResult = (LHS - RHS) / ElemSize; 9398 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 9399 9400 if (Result.extend(65) != TrueResult && 9401 !HandleOverflow(Info, E, TrueResult, E->getType())) 9402 return false; 9403 return Success(Result, E); 9404 } 9405 9406 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9407 } 9408 9409 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 9410 /// a result as the expression's type. 9411 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 9412 const UnaryExprOrTypeTraitExpr *E) { 9413 switch(E->getKind()) { 9414 case UETT_PreferredAlignOf: 9415 case UETT_AlignOf: { 9416 if (E->isArgumentType()) 9417 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 9418 E); 9419 else 9420 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 9421 E); 9422 } 9423 9424 case UETT_VecStep: { 9425 QualType Ty = E->getTypeOfArgument(); 9426 9427 if (Ty->isVectorType()) { 9428 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 9429 9430 // The vec_step built-in functions that take a 3-component 9431 // vector return 4. (OpenCL 1.1 spec 6.11.12) 9432 if (n == 3) 9433 n = 4; 9434 9435 return Success(n, E); 9436 } else 9437 return Success(1, E); 9438 } 9439 9440 case UETT_SizeOf: { 9441 QualType SrcTy = E->getTypeOfArgument(); 9442 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 9443 // the result is the size of the referenced type." 9444 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 9445 SrcTy = Ref->getPointeeType(); 9446 9447 CharUnits Sizeof; 9448 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 9449 return false; 9450 return Success(Sizeof, E); 9451 } 9452 case UETT_OpenMPRequiredSimdAlign: 9453 assert(E->isArgumentType()); 9454 return Success( 9455 Info.Ctx.toCharUnitsFromBits( 9456 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 9457 .getQuantity(), 9458 E); 9459 } 9460 9461 llvm_unreachable("unknown expr/type trait"); 9462 } 9463 9464 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 9465 CharUnits Result; 9466 unsigned n = OOE->getNumComponents(); 9467 if (n == 0) 9468 return Error(OOE); 9469 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 9470 for (unsigned i = 0; i != n; ++i) { 9471 OffsetOfNode ON = OOE->getComponent(i); 9472 switch (ON.getKind()) { 9473 case OffsetOfNode::Array: { 9474 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 9475 APSInt IdxResult; 9476 if (!EvaluateInteger(Idx, IdxResult, Info)) 9477 return false; 9478 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 9479 if (!AT) 9480 return Error(OOE); 9481 CurrentType = AT->getElementType(); 9482 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 9483 Result += IdxResult.getSExtValue() * ElementSize; 9484 break; 9485 } 9486 9487 case OffsetOfNode::Field: { 9488 FieldDecl *MemberDecl = ON.getField(); 9489 const RecordType *RT = CurrentType->getAs<RecordType>(); 9490 if (!RT) 9491 return Error(OOE); 9492 RecordDecl *RD = RT->getDecl(); 9493 if (RD->isInvalidDecl()) return false; 9494 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 9495 unsigned i = MemberDecl->getFieldIndex(); 9496 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 9497 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 9498 CurrentType = MemberDecl->getType().getNonReferenceType(); 9499 break; 9500 } 9501 9502 case OffsetOfNode::Identifier: 9503 llvm_unreachable("dependent __builtin_offsetof"); 9504 9505 case OffsetOfNode::Base: { 9506 CXXBaseSpecifier *BaseSpec = ON.getBase(); 9507 if (BaseSpec->isVirtual()) 9508 return Error(OOE); 9509 9510 // Find the layout of the class whose base we are looking into. 9511 const RecordType *RT = CurrentType->getAs<RecordType>(); 9512 if (!RT) 9513 return Error(OOE); 9514 RecordDecl *RD = RT->getDecl(); 9515 if (RD->isInvalidDecl()) return false; 9516 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 9517 9518 // Find the base class itself. 9519 CurrentType = BaseSpec->getType(); 9520 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 9521 if (!BaseRT) 9522 return Error(OOE); 9523 9524 // Add the offset to the base. 9525 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 9526 break; 9527 } 9528 } 9529 } 9530 return Success(Result, OOE); 9531 } 9532 9533 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9534 switch (E->getOpcode()) { 9535 default: 9536 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 9537 // See C99 6.6p3. 9538 return Error(E); 9539 case UO_Extension: 9540 // FIXME: Should extension allow i-c-e extension expressions in its scope? 9541 // If so, we could clear the diagnostic ID. 9542 return Visit(E->getSubExpr()); 9543 case UO_Plus: 9544 // The result is just the value. 9545 return Visit(E->getSubExpr()); 9546 case UO_Minus: { 9547 if (!Visit(E->getSubExpr())) 9548 return false; 9549 if (!Result.isInt()) return Error(E); 9550 const APSInt &Value = Result.getInt(); 9551 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 9552 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 9553 E->getType())) 9554 return false; 9555 return Success(-Value, E); 9556 } 9557 case UO_Not: { 9558 if (!Visit(E->getSubExpr())) 9559 return false; 9560 if (!Result.isInt()) return Error(E); 9561 return Success(~Result.getInt(), E); 9562 } 9563 case UO_LNot: { 9564 bool bres; 9565 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 9566 return false; 9567 return Success(!bres, E); 9568 } 9569 } 9570 } 9571 9572 /// HandleCast - This is used to evaluate implicit or explicit casts where the 9573 /// result type is integer. 9574 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 9575 const Expr *SubExpr = E->getSubExpr(); 9576 QualType DestType = E->getType(); 9577 QualType SrcType = SubExpr->getType(); 9578 9579 switch (E->getCastKind()) { 9580 case CK_BaseToDerived: 9581 case CK_DerivedToBase: 9582 case CK_UncheckedDerivedToBase: 9583 case CK_Dynamic: 9584 case CK_ToUnion: 9585 case CK_ArrayToPointerDecay: 9586 case CK_FunctionToPointerDecay: 9587 case CK_NullToPointer: 9588 case CK_NullToMemberPointer: 9589 case CK_BaseToDerivedMemberPointer: 9590 case CK_DerivedToBaseMemberPointer: 9591 case CK_ReinterpretMemberPointer: 9592 case CK_ConstructorConversion: 9593 case CK_IntegralToPointer: 9594 case CK_ToVoid: 9595 case CK_VectorSplat: 9596 case CK_IntegralToFloating: 9597 case CK_FloatingCast: 9598 case CK_CPointerToObjCPointerCast: 9599 case CK_BlockPointerToObjCPointerCast: 9600 case CK_AnyPointerToBlockPointerCast: 9601 case CK_ObjCObjectLValueCast: 9602 case CK_FloatingRealToComplex: 9603 case CK_FloatingComplexToReal: 9604 case CK_FloatingComplexCast: 9605 case CK_FloatingComplexToIntegralComplex: 9606 case CK_IntegralRealToComplex: 9607 case CK_IntegralComplexCast: 9608 case CK_IntegralComplexToFloatingComplex: 9609 case CK_BuiltinFnToFnPtr: 9610 case CK_ZeroToOCLOpaqueType: 9611 case CK_NonAtomicToAtomic: 9612 case CK_AddressSpaceConversion: 9613 case CK_IntToOCLSampler: 9614 case CK_FixedPointCast: 9615 llvm_unreachable("invalid cast kind for integral value"); 9616 9617 case CK_BitCast: 9618 case CK_Dependent: 9619 case CK_LValueBitCast: 9620 case CK_ARCProduceObject: 9621 case CK_ARCConsumeObject: 9622 case CK_ARCReclaimReturnedObject: 9623 case CK_ARCExtendBlockObject: 9624 case CK_CopyAndAutoreleaseBlockObject: 9625 return Error(E); 9626 9627 case CK_UserDefinedConversion: 9628 case CK_LValueToRValue: 9629 case CK_AtomicToNonAtomic: 9630 case CK_NoOp: 9631 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9632 9633 case CK_MemberPointerToBoolean: 9634 case CK_PointerToBoolean: 9635 case CK_IntegralToBoolean: 9636 case CK_FloatingToBoolean: 9637 case CK_BooleanToSignedIntegral: 9638 case CK_FloatingComplexToBoolean: 9639 case CK_IntegralComplexToBoolean: { 9640 bool BoolResult; 9641 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 9642 return false; 9643 uint64_t IntResult = BoolResult; 9644 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 9645 IntResult = (uint64_t)-1; 9646 return Success(IntResult, E); 9647 } 9648 9649 case CK_FixedPointToBoolean: { 9650 // Unsigned padding does not affect this. 9651 APValue Val; 9652 if (!Evaluate(Val, Info, SubExpr)) 9653 return false; 9654 return Success(Val.getInt().getBoolValue(), E); 9655 } 9656 9657 case CK_IntegralCast: { 9658 if (!Visit(SubExpr)) 9659 return false; 9660 9661 if (!Result.isInt()) { 9662 // Allow casts of address-of-label differences if they are no-ops 9663 // or narrowing. (The narrowing case isn't actually guaranteed to 9664 // be constant-evaluatable except in some narrow cases which are hard 9665 // to detect here. We let it through on the assumption the user knows 9666 // what they are doing.) 9667 if (Result.isAddrLabelDiff()) 9668 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 9669 // Only allow casts of lvalues if they are lossless. 9670 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 9671 } 9672 9673 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 9674 Result.getInt()), E); 9675 } 9676 9677 case CK_PointerToIntegral: { 9678 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 9679 9680 LValue LV; 9681 if (!EvaluatePointer(SubExpr, LV, Info)) 9682 return false; 9683 9684 if (LV.getLValueBase()) { 9685 // Only allow based lvalue casts if they are lossless. 9686 // FIXME: Allow a larger integer size than the pointer size, and allow 9687 // narrowing back down to pointer width in subsequent integral casts. 9688 // FIXME: Check integer type's active bits, not its type size. 9689 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 9690 return Error(E); 9691 9692 LV.Designator.setInvalid(); 9693 LV.moveInto(Result); 9694 return true; 9695 } 9696 9697 uint64_t V; 9698 if (LV.isNullPointer()) 9699 V = Info.Ctx.getTargetNullPointerValue(SrcType); 9700 else 9701 V = LV.getLValueOffset().getQuantity(); 9702 9703 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType); 9704 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 9705 } 9706 9707 case CK_IntegralComplexToReal: { 9708 ComplexValue C; 9709 if (!EvaluateComplex(SubExpr, C, Info)) 9710 return false; 9711 return Success(C.getComplexIntReal(), E); 9712 } 9713 9714 case CK_FloatingToIntegral: { 9715 APFloat F(0.0); 9716 if (!EvaluateFloat(SubExpr, F, Info)) 9717 return false; 9718 9719 APSInt Value; 9720 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 9721 return false; 9722 return Success(Value, E); 9723 } 9724 } 9725 9726 llvm_unreachable("unknown cast resulting in integral value"); 9727 } 9728 9729 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9730 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9731 ComplexValue LV; 9732 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9733 return false; 9734 if (!LV.isComplexInt()) 9735 return Error(E); 9736 return Success(LV.getComplexIntReal(), E); 9737 } 9738 9739 return Visit(E->getSubExpr()); 9740 } 9741 9742 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9743 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 9744 ComplexValue LV; 9745 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9746 return false; 9747 if (!LV.isComplexInt()) 9748 return Error(E); 9749 return Success(LV.getComplexIntImag(), E); 9750 } 9751 9752 VisitIgnoredValue(E->getSubExpr()); 9753 return Success(0, E); 9754 } 9755 9756 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 9757 return Success(E->getPackLength(), E); 9758 } 9759 9760 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 9761 return Success(E->getValue(), E); 9762 } 9763 9764 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9765 switch (E->getOpcode()) { 9766 default: 9767 // Invalid unary operators 9768 return Error(E); 9769 case UO_Plus: 9770 // The result is just the value. 9771 return Visit(E->getSubExpr()); 9772 case UO_Minus: { 9773 if (!Visit(E->getSubExpr())) return false; 9774 if (!Result.isInt()) return Error(E); 9775 const APSInt &Value = Result.getInt(); 9776 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) { 9777 SmallString<64> S; 9778 FixedPointValueToString(S, Value, 9779 Info.Ctx.getTypeInfo(E->getType()).Width); 9780 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType(); 9781 if (Info.noteUndefinedBehavior()) return false; 9782 } 9783 return Success(-Value, E); 9784 } 9785 case UO_LNot: { 9786 bool bres; 9787 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 9788 return false; 9789 return Success(!bres, E); 9790 } 9791 } 9792 } 9793 9794 //===----------------------------------------------------------------------===// 9795 // Float Evaluation 9796 //===----------------------------------------------------------------------===// 9797 9798 namespace { 9799 class FloatExprEvaluator 9800 : public ExprEvaluatorBase<FloatExprEvaluator> { 9801 APFloat &Result; 9802 public: 9803 FloatExprEvaluator(EvalInfo &info, APFloat &result) 9804 : ExprEvaluatorBaseTy(info), Result(result) {} 9805 9806 bool Success(const APValue &V, const Expr *e) { 9807 Result = V.getFloat(); 9808 return true; 9809 } 9810 9811 bool ZeroInitialization(const Expr *E) { 9812 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 9813 return true; 9814 } 9815 9816 bool VisitCallExpr(const CallExpr *E); 9817 9818 bool VisitUnaryOperator(const UnaryOperator *E); 9819 bool VisitBinaryOperator(const BinaryOperator *E); 9820 bool VisitFloatingLiteral(const FloatingLiteral *E); 9821 bool VisitCastExpr(const CastExpr *E); 9822 9823 bool VisitUnaryReal(const UnaryOperator *E); 9824 bool VisitUnaryImag(const UnaryOperator *E); 9825 9826 // FIXME: Missing: array subscript of vector, member of vector 9827 }; 9828 } // end anonymous namespace 9829 9830 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 9831 assert(E->isRValue() && E->getType()->isRealFloatingType()); 9832 return FloatExprEvaluator(Info, Result).Visit(E); 9833 } 9834 9835 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 9836 QualType ResultTy, 9837 const Expr *Arg, 9838 bool SNaN, 9839 llvm::APFloat &Result) { 9840 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 9841 if (!S) return false; 9842 9843 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 9844 9845 llvm::APInt fill; 9846 9847 // Treat empty strings as if they were zero. 9848 if (S->getString().empty()) 9849 fill = llvm::APInt(32, 0); 9850 else if (S->getString().getAsInteger(0, fill)) 9851 return false; 9852 9853 if (Context.getTargetInfo().isNan2008()) { 9854 if (SNaN) 9855 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9856 else 9857 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9858 } else { 9859 // Prior to IEEE 754-2008, architectures were allowed to choose whether 9860 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 9861 // a different encoding to what became a standard in 2008, and for pre- 9862 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 9863 // sNaN. This is now known as "legacy NaN" encoding. 9864 if (SNaN) 9865 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9866 else 9867 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9868 } 9869 9870 return true; 9871 } 9872 9873 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 9874 switch (E->getBuiltinCallee()) { 9875 default: 9876 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9877 9878 case Builtin::BI__builtin_huge_val: 9879 case Builtin::BI__builtin_huge_valf: 9880 case Builtin::BI__builtin_huge_vall: 9881 case Builtin::BI__builtin_huge_valf128: 9882 case Builtin::BI__builtin_inf: 9883 case Builtin::BI__builtin_inff: 9884 case Builtin::BI__builtin_infl: 9885 case Builtin::BI__builtin_inff128: { 9886 const llvm::fltSemantics &Sem = 9887 Info.Ctx.getFloatTypeSemantics(E->getType()); 9888 Result = llvm::APFloat::getInf(Sem); 9889 return true; 9890 } 9891 9892 case Builtin::BI__builtin_nans: 9893 case Builtin::BI__builtin_nansf: 9894 case Builtin::BI__builtin_nansl: 9895 case Builtin::BI__builtin_nansf128: 9896 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9897 true, Result)) 9898 return Error(E); 9899 return true; 9900 9901 case Builtin::BI__builtin_nan: 9902 case Builtin::BI__builtin_nanf: 9903 case Builtin::BI__builtin_nanl: 9904 case Builtin::BI__builtin_nanf128: 9905 // If this is __builtin_nan() turn this into a nan, otherwise we 9906 // can't constant fold it. 9907 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9908 false, Result)) 9909 return Error(E); 9910 return true; 9911 9912 case Builtin::BI__builtin_fabs: 9913 case Builtin::BI__builtin_fabsf: 9914 case Builtin::BI__builtin_fabsl: 9915 case Builtin::BI__builtin_fabsf128: 9916 if (!EvaluateFloat(E->getArg(0), Result, Info)) 9917 return false; 9918 9919 if (Result.isNegative()) 9920 Result.changeSign(); 9921 return true; 9922 9923 // FIXME: Builtin::BI__builtin_powi 9924 // FIXME: Builtin::BI__builtin_powif 9925 // FIXME: Builtin::BI__builtin_powil 9926 9927 case Builtin::BI__builtin_copysign: 9928 case Builtin::BI__builtin_copysignf: 9929 case Builtin::BI__builtin_copysignl: 9930 case Builtin::BI__builtin_copysignf128: { 9931 APFloat RHS(0.); 9932 if (!EvaluateFloat(E->getArg(0), Result, Info) || 9933 !EvaluateFloat(E->getArg(1), RHS, Info)) 9934 return false; 9935 Result.copySign(RHS); 9936 return true; 9937 } 9938 } 9939 } 9940 9941 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9942 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9943 ComplexValue CV; 9944 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9945 return false; 9946 Result = CV.FloatReal; 9947 return true; 9948 } 9949 9950 return Visit(E->getSubExpr()); 9951 } 9952 9953 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9954 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9955 ComplexValue CV; 9956 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9957 return false; 9958 Result = CV.FloatImag; 9959 return true; 9960 } 9961 9962 VisitIgnoredValue(E->getSubExpr()); 9963 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 9964 Result = llvm::APFloat::getZero(Sem); 9965 return true; 9966 } 9967 9968 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9969 switch (E->getOpcode()) { 9970 default: return Error(E); 9971 case UO_Plus: 9972 return EvaluateFloat(E->getSubExpr(), Result, Info); 9973 case UO_Minus: 9974 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 9975 return false; 9976 Result.changeSign(); 9977 return true; 9978 } 9979 } 9980 9981 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9982 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 9983 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9984 9985 APFloat RHS(0.0); 9986 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 9987 if (!LHSOK && !Info.noteFailure()) 9988 return false; 9989 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 9990 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 9991 } 9992 9993 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 9994 Result = E->getValue(); 9995 return true; 9996 } 9997 9998 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 9999 const Expr* SubExpr = E->getSubExpr(); 10000 10001 switch (E->getCastKind()) { 10002 default: 10003 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10004 10005 case CK_IntegralToFloating: { 10006 APSInt IntResult; 10007 return EvaluateInteger(SubExpr, IntResult, Info) && 10008 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 10009 E->getType(), Result); 10010 } 10011 10012 case CK_FloatingCast: { 10013 if (!Visit(SubExpr)) 10014 return false; 10015 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 10016 Result); 10017 } 10018 10019 case CK_FloatingComplexToReal: { 10020 ComplexValue V; 10021 if (!EvaluateComplex(SubExpr, V, Info)) 10022 return false; 10023 Result = V.getComplexFloatReal(); 10024 return true; 10025 } 10026 } 10027 } 10028 10029 //===----------------------------------------------------------------------===// 10030 // Complex Evaluation (for float and integer) 10031 //===----------------------------------------------------------------------===// 10032 10033 namespace { 10034 class ComplexExprEvaluator 10035 : public ExprEvaluatorBase<ComplexExprEvaluator> { 10036 ComplexValue &Result; 10037 10038 public: 10039 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 10040 : ExprEvaluatorBaseTy(info), Result(Result) {} 10041 10042 bool Success(const APValue &V, const Expr *e) { 10043 Result.setFrom(V); 10044 return true; 10045 } 10046 10047 bool ZeroInitialization(const Expr *E); 10048 10049 //===--------------------------------------------------------------------===// 10050 // Visitor Methods 10051 //===--------------------------------------------------------------------===// 10052 10053 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 10054 bool VisitCastExpr(const CastExpr *E); 10055 bool VisitBinaryOperator(const BinaryOperator *E); 10056 bool VisitUnaryOperator(const UnaryOperator *E); 10057 bool VisitInitListExpr(const InitListExpr *E); 10058 }; 10059 } // end anonymous namespace 10060 10061 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 10062 EvalInfo &Info) { 10063 assert(E->isRValue() && E->getType()->isAnyComplexType()); 10064 return ComplexExprEvaluator(Info, Result).Visit(E); 10065 } 10066 10067 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 10068 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 10069 if (ElemTy->isRealFloatingType()) { 10070 Result.makeComplexFloat(); 10071 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 10072 Result.FloatReal = Zero; 10073 Result.FloatImag = Zero; 10074 } else { 10075 Result.makeComplexInt(); 10076 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 10077 Result.IntReal = Zero; 10078 Result.IntImag = Zero; 10079 } 10080 return true; 10081 } 10082 10083 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 10084 const Expr* SubExpr = E->getSubExpr(); 10085 10086 if (SubExpr->getType()->isRealFloatingType()) { 10087 Result.makeComplexFloat(); 10088 APFloat &Imag = Result.FloatImag; 10089 if (!EvaluateFloat(SubExpr, Imag, Info)) 10090 return false; 10091 10092 Result.FloatReal = APFloat(Imag.getSemantics()); 10093 return true; 10094 } else { 10095 assert(SubExpr->getType()->isIntegerType() && 10096 "Unexpected imaginary literal."); 10097 10098 Result.makeComplexInt(); 10099 APSInt &Imag = Result.IntImag; 10100 if (!EvaluateInteger(SubExpr, Imag, Info)) 10101 return false; 10102 10103 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 10104 return true; 10105 } 10106 } 10107 10108 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 10109 10110 switch (E->getCastKind()) { 10111 case CK_BitCast: 10112 case CK_BaseToDerived: 10113 case CK_DerivedToBase: 10114 case CK_UncheckedDerivedToBase: 10115 case CK_Dynamic: 10116 case CK_ToUnion: 10117 case CK_ArrayToPointerDecay: 10118 case CK_FunctionToPointerDecay: 10119 case CK_NullToPointer: 10120 case CK_NullToMemberPointer: 10121 case CK_BaseToDerivedMemberPointer: 10122 case CK_DerivedToBaseMemberPointer: 10123 case CK_MemberPointerToBoolean: 10124 case CK_ReinterpretMemberPointer: 10125 case CK_ConstructorConversion: 10126 case CK_IntegralToPointer: 10127 case CK_PointerToIntegral: 10128 case CK_PointerToBoolean: 10129 case CK_ToVoid: 10130 case CK_VectorSplat: 10131 case CK_IntegralCast: 10132 case CK_BooleanToSignedIntegral: 10133 case CK_IntegralToBoolean: 10134 case CK_IntegralToFloating: 10135 case CK_FloatingToIntegral: 10136 case CK_FloatingToBoolean: 10137 case CK_FloatingCast: 10138 case CK_CPointerToObjCPointerCast: 10139 case CK_BlockPointerToObjCPointerCast: 10140 case CK_AnyPointerToBlockPointerCast: 10141 case CK_ObjCObjectLValueCast: 10142 case CK_FloatingComplexToReal: 10143 case CK_FloatingComplexToBoolean: 10144 case CK_IntegralComplexToReal: 10145 case CK_IntegralComplexToBoolean: 10146 case CK_ARCProduceObject: 10147 case CK_ARCConsumeObject: 10148 case CK_ARCReclaimReturnedObject: 10149 case CK_ARCExtendBlockObject: 10150 case CK_CopyAndAutoreleaseBlockObject: 10151 case CK_BuiltinFnToFnPtr: 10152 case CK_ZeroToOCLOpaqueType: 10153 case CK_NonAtomicToAtomic: 10154 case CK_AddressSpaceConversion: 10155 case CK_IntToOCLSampler: 10156 case CK_FixedPointCast: 10157 case CK_FixedPointToBoolean: 10158 llvm_unreachable("invalid cast kind for complex value"); 10159 10160 case CK_LValueToRValue: 10161 case CK_AtomicToNonAtomic: 10162 case CK_NoOp: 10163 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10164 10165 case CK_Dependent: 10166 case CK_LValueBitCast: 10167 case CK_UserDefinedConversion: 10168 return Error(E); 10169 10170 case CK_FloatingRealToComplex: { 10171 APFloat &Real = Result.FloatReal; 10172 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 10173 return false; 10174 10175 Result.makeComplexFloat(); 10176 Result.FloatImag = APFloat(Real.getSemantics()); 10177 return true; 10178 } 10179 10180 case CK_FloatingComplexCast: { 10181 if (!Visit(E->getSubExpr())) 10182 return false; 10183 10184 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10185 QualType From 10186 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10187 10188 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 10189 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 10190 } 10191 10192 case CK_FloatingComplexToIntegralComplex: { 10193 if (!Visit(E->getSubExpr())) 10194 return false; 10195 10196 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10197 QualType From 10198 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10199 Result.makeComplexInt(); 10200 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 10201 To, Result.IntReal) && 10202 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 10203 To, Result.IntImag); 10204 } 10205 10206 case CK_IntegralRealToComplex: { 10207 APSInt &Real = Result.IntReal; 10208 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 10209 return false; 10210 10211 Result.makeComplexInt(); 10212 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 10213 return true; 10214 } 10215 10216 case CK_IntegralComplexCast: { 10217 if (!Visit(E->getSubExpr())) 10218 return false; 10219 10220 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10221 QualType From 10222 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10223 10224 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 10225 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 10226 return true; 10227 } 10228 10229 case CK_IntegralComplexToFloatingComplex: { 10230 if (!Visit(E->getSubExpr())) 10231 return false; 10232 10233 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 10234 QualType From 10235 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 10236 Result.makeComplexFloat(); 10237 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 10238 To, Result.FloatReal) && 10239 HandleIntToFloatCast(Info, E, From, Result.IntImag, 10240 To, Result.FloatImag); 10241 } 10242 } 10243 10244 llvm_unreachable("unknown cast resulting in complex value"); 10245 } 10246 10247 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10248 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 10249 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10250 10251 // Track whether the LHS or RHS is real at the type system level. When this is 10252 // the case we can simplify our evaluation strategy. 10253 bool LHSReal = false, RHSReal = false; 10254 10255 bool LHSOK; 10256 if (E->getLHS()->getType()->isRealFloatingType()) { 10257 LHSReal = true; 10258 APFloat &Real = Result.FloatReal; 10259 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 10260 if (LHSOK) { 10261 Result.makeComplexFloat(); 10262 Result.FloatImag = APFloat(Real.getSemantics()); 10263 } 10264 } else { 10265 LHSOK = Visit(E->getLHS()); 10266 } 10267 if (!LHSOK && !Info.noteFailure()) 10268 return false; 10269 10270 ComplexValue RHS; 10271 if (E->getRHS()->getType()->isRealFloatingType()) { 10272 RHSReal = true; 10273 APFloat &Real = RHS.FloatReal; 10274 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 10275 return false; 10276 RHS.makeComplexFloat(); 10277 RHS.FloatImag = APFloat(Real.getSemantics()); 10278 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 10279 return false; 10280 10281 assert(!(LHSReal && RHSReal) && 10282 "Cannot have both operands of a complex operation be real."); 10283 switch (E->getOpcode()) { 10284 default: return Error(E); 10285 case BO_Add: 10286 if (Result.isComplexFloat()) { 10287 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 10288 APFloat::rmNearestTiesToEven); 10289 if (LHSReal) 10290 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 10291 else if (!RHSReal) 10292 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 10293 APFloat::rmNearestTiesToEven); 10294 } else { 10295 Result.getComplexIntReal() += RHS.getComplexIntReal(); 10296 Result.getComplexIntImag() += RHS.getComplexIntImag(); 10297 } 10298 break; 10299 case BO_Sub: 10300 if (Result.isComplexFloat()) { 10301 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 10302 APFloat::rmNearestTiesToEven); 10303 if (LHSReal) { 10304 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 10305 Result.getComplexFloatImag().changeSign(); 10306 } else if (!RHSReal) { 10307 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 10308 APFloat::rmNearestTiesToEven); 10309 } 10310 } else { 10311 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 10312 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 10313 } 10314 break; 10315 case BO_Mul: 10316 if (Result.isComplexFloat()) { 10317 // This is an implementation of complex multiplication according to the 10318 // constraints laid out in C11 Annex G. The implemention uses the 10319 // following naming scheme: 10320 // (a + ib) * (c + id) 10321 ComplexValue LHS = Result; 10322 APFloat &A = LHS.getComplexFloatReal(); 10323 APFloat &B = LHS.getComplexFloatImag(); 10324 APFloat &C = RHS.getComplexFloatReal(); 10325 APFloat &D = RHS.getComplexFloatImag(); 10326 APFloat &ResR = Result.getComplexFloatReal(); 10327 APFloat &ResI = Result.getComplexFloatImag(); 10328 if (LHSReal) { 10329 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 10330 ResR = A * C; 10331 ResI = A * D; 10332 } else if (RHSReal) { 10333 ResR = C * A; 10334 ResI = C * B; 10335 } else { 10336 // In the fully general case, we need to handle NaNs and infinities 10337 // robustly. 10338 APFloat AC = A * C; 10339 APFloat BD = B * D; 10340 APFloat AD = A * D; 10341 APFloat BC = B * C; 10342 ResR = AC - BD; 10343 ResI = AD + BC; 10344 if (ResR.isNaN() && ResI.isNaN()) { 10345 bool Recalc = false; 10346 if (A.isInfinity() || B.isInfinity()) { 10347 A = APFloat::copySign( 10348 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 10349 B = APFloat::copySign( 10350 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 10351 if (C.isNaN()) 10352 C = APFloat::copySign(APFloat(C.getSemantics()), C); 10353 if (D.isNaN()) 10354 D = APFloat::copySign(APFloat(D.getSemantics()), D); 10355 Recalc = true; 10356 } 10357 if (C.isInfinity() || D.isInfinity()) { 10358 C = APFloat::copySign( 10359 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 10360 D = APFloat::copySign( 10361 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 10362 if (A.isNaN()) 10363 A = APFloat::copySign(APFloat(A.getSemantics()), A); 10364 if (B.isNaN()) 10365 B = APFloat::copySign(APFloat(B.getSemantics()), B); 10366 Recalc = true; 10367 } 10368 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 10369 AD.isInfinity() || BC.isInfinity())) { 10370 if (A.isNaN()) 10371 A = APFloat::copySign(APFloat(A.getSemantics()), A); 10372 if (B.isNaN()) 10373 B = APFloat::copySign(APFloat(B.getSemantics()), B); 10374 if (C.isNaN()) 10375 C = APFloat::copySign(APFloat(C.getSemantics()), C); 10376 if (D.isNaN()) 10377 D = APFloat::copySign(APFloat(D.getSemantics()), D); 10378 Recalc = true; 10379 } 10380 if (Recalc) { 10381 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 10382 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 10383 } 10384 } 10385 } 10386 } else { 10387 ComplexValue LHS = Result; 10388 Result.getComplexIntReal() = 10389 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 10390 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 10391 Result.getComplexIntImag() = 10392 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 10393 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 10394 } 10395 break; 10396 case BO_Div: 10397 if (Result.isComplexFloat()) { 10398 // This is an implementation of complex division according to the 10399 // constraints laid out in C11 Annex G. The implemention uses the 10400 // following naming scheme: 10401 // (a + ib) / (c + id) 10402 ComplexValue LHS = Result; 10403 APFloat &A = LHS.getComplexFloatReal(); 10404 APFloat &B = LHS.getComplexFloatImag(); 10405 APFloat &C = RHS.getComplexFloatReal(); 10406 APFloat &D = RHS.getComplexFloatImag(); 10407 APFloat &ResR = Result.getComplexFloatReal(); 10408 APFloat &ResI = Result.getComplexFloatImag(); 10409 if (RHSReal) { 10410 ResR = A / C; 10411 ResI = B / C; 10412 } else { 10413 if (LHSReal) { 10414 // No real optimizations we can do here, stub out with zero. 10415 B = APFloat::getZero(A.getSemantics()); 10416 } 10417 int DenomLogB = 0; 10418 APFloat MaxCD = maxnum(abs(C), abs(D)); 10419 if (MaxCD.isFinite()) { 10420 DenomLogB = ilogb(MaxCD); 10421 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 10422 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 10423 } 10424 APFloat Denom = C * C + D * D; 10425 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 10426 APFloat::rmNearestTiesToEven); 10427 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 10428 APFloat::rmNearestTiesToEven); 10429 if (ResR.isNaN() && ResI.isNaN()) { 10430 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 10431 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 10432 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 10433 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 10434 D.isFinite()) { 10435 A = APFloat::copySign( 10436 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 10437 B = APFloat::copySign( 10438 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 10439 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 10440 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 10441 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 10442 C = APFloat::copySign( 10443 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 10444 D = APFloat::copySign( 10445 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 10446 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 10447 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 10448 } 10449 } 10450 } 10451 } else { 10452 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 10453 return Error(E, diag::note_expr_divide_by_zero); 10454 10455 ComplexValue LHS = Result; 10456 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 10457 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 10458 Result.getComplexIntReal() = 10459 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 10460 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 10461 Result.getComplexIntImag() = 10462 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 10463 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 10464 } 10465 break; 10466 } 10467 10468 return true; 10469 } 10470 10471 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10472 // Get the operand value into 'Result'. 10473 if (!Visit(E->getSubExpr())) 10474 return false; 10475 10476 switch (E->getOpcode()) { 10477 default: 10478 return Error(E); 10479 case UO_Extension: 10480 return true; 10481 case UO_Plus: 10482 // The result is always just the subexpr. 10483 return true; 10484 case UO_Minus: 10485 if (Result.isComplexFloat()) { 10486 Result.getComplexFloatReal().changeSign(); 10487 Result.getComplexFloatImag().changeSign(); 10488 } 10489 else { 10490 Result.getComplexIntReal() = -Result.getComplexIntReal(); 10491 Result.getComplexIntImag() = -Result.getComplexIntImag(); 10492 } 10493 return true; 10494 case UO_Not: 10495 if (Result.isComplexFloat()) 10496 Result.getComplexFloatImag().changeSign(); 10497 else 10498 Result.getComplexIntImag() = -Result.getComplexIntImag(); 10499 return true; 10500 } 10501 } 10502 10503 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10504 if (E->getNumInits() == 2) { 10505 if (E->getType()->isComplexType()) { 10506 Result.makeComplexFloat(); 10507 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 10508 return false; 10509 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 10510 return false; 10511 } else { 10512 Result.makeComplexInt(); 10513 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 10514 return false; 10515 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 10516 return false; 10517 } 10518 return true; 10519 } 10520 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 10521 } 10522 10523 //===----------------------------------------------------------------------===// 10524 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 10525 // implicit conversion. 10526 //===----------------------------------------------------------------------===// 10527 10528 namespace { 10529 class AtomicExprEvaluator : 10530 public ExprEvaluatorBase<AtomicExprEvaluator> { 10531 const LValue *This; 10532 APValue &Result; 10533 public: 10534 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 10535 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10536 10537 bool Success(const APValue &V, const Expr *E) { 10538 Result = V; 10539 return true; 10540 } 10541 10542 bool ZeroInitialization(const Expr *E) { 10543 ImplicitValueInitExpr VIE( 10544 E->getType()->castAs<AtomicType>()->getValueType()); 10545 // For atomic-qualified class (and array) types in C++, initialize the 10546 // _Atomic-wrapped subobject directly, in-place. 10547 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 10548 : Evaluate(Result, Info, &VIE); 10549 } 10550 10551 bool VisitCastExpr(const CastExpr *E) { 10552 switch (E->getCastKind()) { 10553 default: 10554 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10555 case CK_NonAtomicToAtomic: 10556 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 10557 : Evaluate(Result, Info, E->getSubExpr()); 10558 } 10559 } 10560 }; 10561 } // end anonymous namespace 10562 10563 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 10564 EvalInfo &Info) { 10565 assert(E->isRValue() && E->getType()->isAtomicType()); 10566 return AtomicExprEvaluator(Info, This, Result).Visit(E); 10567 } 10568 10569 //===----------------------------------------------------------------------===// 10570 // Void expression evaluation, primarily for a cast to void on the LHS of a 10571 // comma operator 10572 //===----------------------------------------------------------------------===// 10573 10574 namespace { 10575 class VoidExprEvaluator 10576 : public ExprEvaluatorBase<VoidExprEvaluator> { 10577 public: 10578 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 10579 10580 bool Success(const APValue &V, const Expr *e) { return true; } 10581 10582 bool ZeroInitialization(const Expr *E) { return true; } 10583 10584 bool VisitCastExpr(const CastExpr *E) { 10585 switch (E->getCastKind()) { 10586 default: 10587 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10588 case CK_ToVoid: 10589 VisitIgnoredValue(E->getSubExpr()); 10590 return true; 10591 } 10592 } 10593 10594 bool VisitCallExpr(const CallExpr *E) { 10595 switch (E->getBuiltinCallee()) { 10596 default: 10597 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10598 case Builtin::BI__assume: 10599 case Builtin::BI__builtin_assume: 10600 // The argument is not evaluated! 10601 return true; 10602 } 10603 } 10604 }; 10605 } // end anonymous namespace 10606 10607 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 10608 assert(E->isRValue() && E->getType()->isVoidType()); 10609 return VoidExprEvaluator(Info).Visit(E); 10610 } 10611 10612 //===----------------------------------------------------------------------===// 10613 // Top level Expr::EvaluateAsRValue method. 10614 //===----------------------------------------------------------------------===// 10615 10616 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 10617 // In C, function designators are not lvalues, but we evaluate them as if they 10618 // are. 10619 QualType T = E->getType(); 10620 if (E->isGLValue() || T->isFunctionType()) { 10621 LValue LV; 10622 if (!EvaluateLValue(E, LV, Info)) 10623 return false; 10624 LV.moveInto(Result); 10625 } else if (T->isVectorType()) { 10626 if (!EvaluateVector(E, Result, Info)) 10627 return false; 10628 } else if (T->isIntegralOrEnumerationType()) { 10629 if (!IntExprEvaluator(Info, Result).Visit(E)) 10630 return false; 10631 } else if (T->hasPointerRepresentation()) { 10632 LValue LV; 10633 if (!EvaluatePointer(E, LV, Info)) 10634 return false; 10635 LV.moveInto(Result); 10636 } else if (T->isRealFloatingType()) { 10637 llvm::APFloat F(0.0); 10638 if (!EvaluateFloat(E, F, Info)) 10639 return false; 10640 Result = APValue(F); 10641 } else if (T->isAnyComplexType()) { 10642 ComplexValue C; 10643 if (!EvaluateComplex(E, C, Info)) 10644 return false; 10645 C.moveInto(Result); 10646 } else if (T->isFixedPointType()) { 10647 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 10648 } else if (T->isMemberPointerType()) { 10649 MemberPtr P; 10650 if (!EvaluateMemberPointer(E, P, Info)) 10651 return false; 10652 P.moveInto(Result); 10653 return true; 10654 } else if (T->isArrayType()) { 10655 LValue LV; 10656 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10657 if (!EvaluateArray(E, LV, Value, Info)) 10658 return false; 10659 Result = Value; 10660 } else if (T->isRecordType()) { 10661 LValue LV; 10662 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10663 if (!EvaluateRecord(E, LV, Value, Info)) 10664 return false; 10665 Result = Value; 10666 } else if (T->isVoidType()) { 10667 if (!Info.getLangOpts().CPlusPlus11) 10668 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 10669 << E->getType(); 10670 if (!EvaluateVoid(E, Info)) 10671 return false; 10672 } else if (T->isAtomicType()) { 10673 QualType Unqual = T.getAtomicUnqualifiedType(); 10674 if (Unqual->isArrayType() || Unqual->isRecordType()) { 10675 LValue LV; 10676 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10677 if (!EvaluateAtomic(E, &LV, Value, Info)) 10678 return false; 10679 } else { 10680 if (!EvaluateAtomic(E, nullptr, Result, Info)) 10681 return false; 10682 } 10683 } else if (Info.getLangOpts().CPlusPlus11) { 10684 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 10685 return false; 10686 } else { 10687 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10688 return false; 10689 } 10690 10691 return true; 10692 } 10693 10694 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 10695 /// cases, the in-place evaluation is essential, since later initializers for 10696 /// an object can indirectly refer to subobjects which were initialized earlier. 10697 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 10698 const Expr *E, bool AllowNonLiteralTypes) { 10699 assert(!E->isValueDependent()); 10700 10701 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 10702 return false; 10703 10704 if (E->isRValue()) { 10705 // Evaluate arrays and record types in-place, so that later initializers can 10706 // refer to earlier-initialized members of the object. 10707 QualType T = E->getType(); 10708 if (T->isArrayType()) 10709 return EvaluateArray(E, This, Result, Info); 10710 else if (T->isRecordType()) 10711 return EvaluateRecord(E, This, Result, Info); 10712 else if (T->isAtomicType()) { 10713 QualType Unqual = T.getAtomicUnqualifiedType(); 10714 if (Unqual->isArrayType() || Unqual->isRecordType()) 10715 return EvaluateAtomic(E, &This, Result, Info); 10716 } 10717 } 10718 10719 // For any other type, in-place evaluation is unimportant. 10720 return Evaluate(Result, Info, E); 10721 } 10722 10723 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 10724 /// lvalue-to-rvalue cast if it is an lvalue. 10725 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 10726 if (E->getType().isNull()) 10727 return false; 10728 10729 if (!CheckLiteralType(Info, E)) 10730 return false; 10731 10732 if (!::Evaluate(Result, Info, E)) 10733 return false; 10734 10735 if (E->isGLValue()) { 10736 LValue LV; 10737 LV.setFrom(Info.Ctx, Result); 10738 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 10739 return false; 10740 } 10741 10742 // Check this core constant expression is a constant expression. 10743 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 10744 } 10745 10746 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 10747 const ASTContext &Ctx, bool &IsConst) { 10748 // Fast-path evaluations of integer literals, since we sometimes see files 10749 // containing vast quantities of these. 10750 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 10751 Result.Val = APValue(APSInt(L->getValue(), 10752 L->getType()->isUnsignedIntegerType())); 10753 IsConst = true; 10754 return true; 10755 } 10756 10757 // This case should be rare, but we need to check it before we check on 10758 // the type below. 10759 if (Exp->getType().isNull()) { 10760 IsConst = false; 10761 return true; 10762 } 10763 10764 // FIXME: Evaluating values of large array and record types can cause 10765 // performance problems. Only do so in C++11 for now. 10766 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 10767 Exp->getType()->isRecordType()) && 10768 !Ctx.getLangOpts().CPlusPlus11) { 10769 IsConst = false; 10770 return true; 10771 } 10772 return false; 10773 } 10774 10775 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 10776 Expr::SideEffectsKind SEK) { 10777 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 10778 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 10779 } 10780 10781 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 10782 const ASTContext &Ctx, EvalInfo &Info) { 10783 bool IsConst; 10784 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 10785 return IsConst; 10786 10787 return EvaluateAsRValue(Info, E, Result.Val); 10788 } 10789 10790 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 10791 const ASTContext &Ctx, 10792 Expr::SideEffectsKind AllowSideEffects, 10793 EvalInfo &Info) { 10794 if (!E->getType()->isIntegralOrEnumerationType()) 10795 return false; 10796 10797 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 10798 !ExprResult.Val.isInt() || 10799 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10800 return false; 10801 10802 return true; 10803 } 10804 10805 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 10806 /// any crazy technique (that has nothing to do with language standards) that 10807 /// we want to. If this function returns true, it returns the folded constant 10808 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 10809 /// will be applied to the result. 10810 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 10811 bool InConstantContext) const { 10812 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 10813 Info.InConstantContext = InConstantContext; 10814 return ::EvaluateAsRValue(this, Result, Ctx, Info); 10815 } 10816 10817 bool Expr::EvaluateAsBooleanCondition(bool &Result, 10818 const ASTContext &Ctx) const { 10819 EvalResult Scratch; 10820 return EvaluateAsRValue(Scratch, Ctx) && 10821 HandleConversionToBool(Scratch.Val, Result); 10822 } 10823 10824 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 10825 SideEffectsKind AllowSideEffects) const { 10826 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 10827 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 10828 } 10829 10830 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 10831 SideEffectsKind AllowSideEffects) const { 10832 if (!getType()->isRealFloatingType()) 10833 return false; 10834 10835 EvalResult ExprResult; 10836 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() || 10837 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10838 return false; 10839 10840 Result = ExprResult.Val.getFloat(); 10841 return true; 10842 } 10843 10844 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 10845 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 10846 10847 LValue LV; 10848 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 10849 !CheckLValueConstantExpression(Info, getExprLoc(), 10850 Ctx.getLValueReferenceType(getType()), LV, 10851 Expr::EvaluateForCodeGen)) 10852 return false; 10853 10854 LV.moveInto(Result.Val); 10855 return true; 10856 } 10857 10858 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 10859 const ASTContext &Ctx) const { 10860 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 10861 EvalInfo Info(Ctx, Result, EM); 10862 if (!::Evaluate(Result.Val, Info, this)) 10863 return false; 10864 10865 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val, 10866 Usage); 10867 } 10868 10869 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 10870 const VarDecl *VD, 10871 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 10872 // FIXME: Evaluating initializers for large array and record types can cause 10873 // performance problems. Only do so in C++11 for now. 10874 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 10875 !Ctx.getLangOpts().CPlusPlus11) 10876 return false; 10877 10878 Expr::EvalStatus EStatus; 10879 EStatus.Diag = &Notes; 10880 10881 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr() 10882 ? EvalInfo::EM_ConstantExpression 10883 : EvalInfo::EM_ConstantFold); 10884 InitInfo.setEvaluatingDecl(VD, Value); 10885 InitInfo.InConstantContext = true; 10886 10887 LValue LVal; 10888 LVal.set(VD); 10889 10890 // C++11 [basic.start.init]p2: 10891 // Variables with static storage duration or thread storage duration shall be 10892 // zero-initialized before any other initialization takes place. 10893 // This behavior is not present in C. 10894 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 10895 !VD->getType()->isReferenceType()) { 10896 ImplicitValueInitExpr VIE(VD->getType()); 10897 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, 10898 /*AllowNonLiteralTypes=*/true)) 10899 return false; 10900 } 10901 10902 if (!EvaluateInPlace(Value, InitInfo, LVal, this, 10903 /*AllowNonLiteralTypes=*/true) || 10904 EStatus.HasSideEffects) 10905 return false; 10906 10907 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 10908 Value); 10909 } 10910 10911 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 10912 /// constant folded, but discard the result. 10913 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 10914 EvalResult Result; 10915 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 10916 !hasUnacceptableSideEffect(Result, SEK); 10917 } 10918 10919 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 10920 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 10921 EvalResult EVResult; 10922 EVResult.Diag = Diag; 10923 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 10924 Info.InConstantContext = true; 10925 10926 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 10927 (void)Result; 10928 assert(Result && "Could not evaluate expression"); 10929 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 10930 10931 return EVResult.Val.getInt(); 10932 } 10933 10934 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 10935 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 10936 EvalResult EVResult; 10937 EVResult.Diag = Diag; 10938 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow); 10939 Info.InConstantContext = true; 10940 10941 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 10942 (void)Result; 10943 assert(Result && "Could not evaluate expression"); 10944 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 10945 10946 return EVResult.Val.getInt(); 10947 } 10948 10949 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 10950 bool IsConst; 10951 EvalResult EVResult; 10952 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 10953 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow); 10954 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 10955 } 10956 } 10957 10958 bool Expr::EvalResult::isGlobalLValue() const { 10959 assert(Val.isLValue()); 10960 return IsGlobalLValue(Val.getLValueBase()); 10961 } 10962 10963 10964 /// isIntegerConstantExpr - this recursive routine will test if an expression is 10965 /// an integer constant expression. 10966 10967 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 10968 /// comma, etc 10969 10970 // CheckICE - This function does the fundamental ICE checking: the returned 10971 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 10972 // and a (possibly null) SourceLocation indicating the location of the problem. 10973 // 10974 // Note that to reduce code duplication, this helper does no evaluation 10975 // itself; the caller checks whether the expression is evaluatable, and 10976 // in the rare cases where CheckICE actually cares about the evaluated 10977 // value, it calls into Evaluate. 10978 10979 namespace { 10980 10981 enum ICEKind { 10982 /// This expression is an ICE. 10983 IK_ICE, 10984 /// This expression is not an ICE, but if it isn't evaluated, it's 10985 /// a legal subexpression for an ICE. This return value is used to handle 10986 /// the comma operator in C99 mode, and non-constant subexpressions. 10987 IK_ICEIfUnevaluated, 10988 /// This expression is not an ICE, and is not a legal subexpression for one. 10989 IK_NotICE 10990 }; 10991 10992 struct ICEDiag { 10993 ICEKind Kind; 10994 SourceLocation Loc; 10995 10996 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 10997 }; 10998 10999 } 11000 11001 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 11002 11003 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 11004 11005 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 11006 Expr::EvalResult EVResult; 11007 Expr::EvalStatus Status; 11008 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 11009 11010 Info.InConstantContext = true; 11011 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 11012 !EVResult.Val.isInt()) 11013 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11014 11015 return NoDiag(); 11016 } 11017 11018 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 11019 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 11020 if (!E->getType()->isIntegralOrEnumerationType()) 11021 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11022 11023 switch (E->getStmtClass()) { 11024 #define ABSTRACT_STMT(Node) 11025 #define STMT(Node, Base) case Expr::Node##Class: 11026 #define EXPR(Node, Base) 11027 #include "clang/AST/StmtNodes.inc" 11028 case Expr::PredefinedExprClass: 11029 case Expr::FloatingLiteralClass: 11030 case Expr::ImaginaryLiteralClass: 11031 case Expr::StringLiteralClass: 11032 case Expr::ArraySubscriptExprClass: 11033 case Expr::OMPArraySectionExprClass: 11034 case Expr::MemberExprClass: 11035 case Expr::CompoundAssignOperatorClass: 11036 case Expr::CompoundLiteralExprClass: 11037 case Expr::ExtVectorElementExprClass: 11038 case Expr::DesignatedInitExprClass: 11039 case Expr::ArrayInitLoopExprClass: 11040 case Expr::ArrayInitIndexExprClass: 11041 case Expr::NoInitExprClass: 11042 case Expr::DesignatedInitUpdateExprClass: 11043 case Expr::ImplicitValueInitExprClass: 11044 case Expr::ParenListExprClass: 11045 case Expr::VAArgExprClass: 11046 case Expr::AddrLabelExprClass: 11047 case Expr::StmtExprClass: 11048 case Expr::CXXMemberCallExprClass: 11049 case Expr::CUDAKernelCallExprClass: 11050 case Expr::CXXDynamicCastExprClass: 11051 case Expr::CXXTypeidExprClass: 11052 case Expr::CXXUuidofExprClass: 11053 case Expr::MSPropertyRefExprClass: 11054 case Expr::MSPropertySubscriptExprClass: 11055 case Expr::CXXNullPtrLiteralExprClass: 11056 case Expr::UserDefinedLiteralClass: 11057 case Expr::CXXThisExprClass: 11058 case Expr::CXXThrowExprClass: 11059 case Expr::CXXNewExprClass: 11060 case Expr::CXXDeleteExprClass: 11061 case Expr::CXXPseudoDestructorExprClass: 11062 case Expr::UnresolvedLookupExprClass: 11063 case Expr::TypoExprClass: 11064 case Expr::DependentScopeDeclRefExprClass: 11065 case Expr::CXXConstructExprClass: 11066 case Expr::CXXInheritedCtorInitExprClass: 11067 case Expr::CXXStdInitializerListExprClass: 11068 case Expr::CXXBindTemporaryExprClass: 11069 case Expr::ExprWithCleanupsClass: 11070 case Expr::CXXTemporaryObjectExprClass: 11071 case Expr::CXXUnresolvedConstructExprClass: 11072 case Expr::CXXDependentScopeMemberExprClass: 11073 case Expr::UnresolvedMemberExprClass: 11074 case Expr::ObjCStringLiteralClass: 11075 case Expr::ObjCBoxedExprClass: 11076 case Expr::ObjCArrayLiteralClass: 11077 case Expr::ObjCDictionaryLiteralClass: 11078 case Expr::ObjCEncodeExprClass: 11079 case Expr::ObjCMessageExprClass: 11080 case Expr::ObjCSelectorExprClass: 11081 case Expr::ObjCProtocolExprClass: 11082 case Expr::ObjCIvarRefExprClass: 11083 case Expr::ObjCPropertyRefExprClass: 11084 case Expr::ObjCSubscriptRefExprClass: 11085 case Expr::ObjCIsaExprClass: 11086 case Expr::ObjCAvailabilityCheckExprClass: 11087 case Expr::ShuffleVectorExprClass: 11088 case Expr::ConvertVectorExprClass: 11089 case Expr::BlockExprClass: 11090 case Expr::NoStmtClass: 11091 case Expr::OpaqueValueExprClass: 11092 case Expr::PackExpansionExprClass: 11093 case Expr::SubstNonTypeTemplateParmPackExprClass: 11094 case Expr::FunctionParmPackExprClass: 11095 case Expr::AsTypeExprClass: 11096 case Expr::ObjCIndirectCopyRestoreExprClass: 11097 case Expr::MaterializeTemporaryExprClass: 11098 case Expr::PseudoObjectExprClass: 11099 case Expr::AtomicExprClass: 11100 case Expr::LambdaExprClass: 11101 case Expr::CXXFoldExprClass: 11102 case Expr::CoawaitExprClass: 11103 case Expr::DependentCoawaitExprClass: 11104 case Expr::CoyieldExprClass: 11105 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11106 11107 case Expr::InitListExprClass: { 11108 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 11109 // form "T x = { a };" is equivalent to "T x = a;". 11110 // Unless we're initializing a reference, T is a scalar as it is known to be 11111 // of integral or enumeration type. 11112 if (E->isRValue()) 11113 if (cast<InitListExpr>(E)->getNumInits() == 1) 11114 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 11115 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11116 } 11117 11118 case Expr::SizeOfPackExprClass: 11119 case Expr::GNUNullExprClass: 11120 // GCC considers the GNU __null value to be an integral constant expression. 11121 return NoDiag(); 11122 11123 case Expr::SubstNonTypeTemplateParmExprClass: 11124 return 11125 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 11126 11127 case Expr::ConstantExprClass: 11128 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 11129 11130 case Expr::ParenExprClass: 11131 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 11132 case Expr::GenericSelectionExprClass: 11133 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 11134 case Expr::IntegerLiteralClass: 11135 case Expr::FixedPointLiteralClass: 11136 case Expr::CharacterLiteralClass: 11137 case Expr::ObjCBoolLiteralExprClass: 11138 case Expr::CXXBoolLiteralExprClass: 11139 case Expr::CXXScalarValueInitExprClass: 11140 case Expr::TypeTraitExprClass: 11141 case Expr::ArrayTypeTraitExprClass: 11142 case Expr::ExpressionTraitExprClass: 11143 case Expr::CXXNoexceptExprClass: 11144 return NoDiag(); 11145 case Expr::CallExprClass: 11146 case Expr::CXXOperatorCallExprClass: { 11147 // C99 6.6/3 allows function calls within unevaluated subexpressions of 11148 // constant expressions, but they can never be ICEs because an ICE cannot 11149 // contain an operand of (pointer to) function type. 11150 const CallExpr *CE = cast<CallExpr>(E); 11151 if (CE->getBuiltinCallee()) 11152 return CheckEvalInICE(E, Ctx); 11153 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11154 } 11155 case Expr::DeclRefExprClass: { 11156 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 11157 return NoDiag(); 11158 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 11159 if (Ctx.getLangOpts().CPlusPlus && 11160 D && IsConstNonVolatile(D->getType())) { 11161 // Parameter variables are never constants. Without this check, 11162 // getAnyInitializer() can find a default argument, which leads 11163 // to chaos. 11164 if (isa<ParmVarDecl>(D)) 11165 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11166 11167 // C++ 7.1.5.1p2 11168 // A variable of non-volatile const-qualified integral or enumeration 11169 // type initialized by an ICE can be used in ICEs. 11170 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 11171 if (!Dcl->getType()->isIntegralOrEnumerationType()) 11172 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11173 11174 const VarDecl *VD; 11175 // Look for a declaration of this variable that has an initializer, and 11176 // check whether it is an ICE. 11177 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 11178 return NoDiag(); 11179 else 11180 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11181 } 11182 } 11183 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11184 } 11185 case Expr::UnaryOperatorClass: { 11186 const UnaryOperator *Exp = cast<UnaryOperator>(E); 11187 switch (Exp->getOpcode()) { 11188 case UO_PostInc: 11189 case UO_PostDec: 11190 case UO_PreInc: 11191 case UO_PreDec: 11192 case UO_AddrOf: 11193 case UO_Deref: 11194 case UO_Coawait: 11195 // C99 6.6/3 allows increment and decrement within unevaluated 11196 // subexpressions of constant expressions, but they can never be ICEs 11197 // because an ICE cannot contain an lvalue operand. 11198 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11199 case UO_Extension: 11200 case UO_LNot: 11201 case UO_Plus: 11202 case UO_Minus: 11203 case UO_Not: 11204 case UO_Real: 11205 case UO_Imag: 11206 return CheckICE(Exp->getSubExpr(), Ctx); 11207 } 11208 llvm_unreachable("invalid unary operator class"); 11209 } 11210 case Expr::OffsetOfExprClass: { 11211 // Note that per C99, offsetof must be an ICE. And AFAIK, using 11212 // EvaluateAsRValue matches the proposed gcc behavior for cases like 11213 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 11214 // compliance: we should warn earlier for offsetof expressions with 11215 // array subscripts that aren't ICEs, and if the array subscripts 11216 // are ICEs, the value of the offsetof must be an integer constant. 11217 return CheckEvalInICE(E, Ctx); 11218 } 11219 case Expr::UnaryExprOrTypeTraitExprClass: { 11220 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 11221 if ((Exp->getKind() == UETT_SizeOf) && 11222 Exp->getTypeOfArgument()->isVariableArrayType()) 11223 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11224 return NoDiag(); 11225 } 11226 case Expr::BinaryOperatorClass: { 11227 const BinaryOperator *Exp = cast<BinaryOperator>(E); 11228 switch (Exp->getOpcode()) { 11229 case BO_PtrMemD: 11230 case BO_PtrMemI: 11231 case BO_Assign: 11232 case BO_MulAssign: 11233 case BO_DivAssign: 11234 case BO_RemAssign: 11235 case BO_AddAssign: 11236 case BO_SubAssign: 11237 case BO_ShlAssign: 11238 case BO_ShrAssign: 11239 case BO_AndAssign: 11240 case BO_XorAssign: 11241 case BO_OrAssign: 11242 // C99 6.6/3 allows assignments within unevaluated subexpressions of 11243 // constant expressions, but they can never be ICEs because an ICE cannot 11244 // contain an lvalue operand. 11245 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11246 11247 case BO_Mul: 11248 case BO_Div: 11249 case BO_Rem: 11250 case BO_Add: 11251 case BO_Sub: 11252 case BO_Shl: 11253 case BO_Shr: 11254 case BO_LT: 11255 case BO_GT: 11256 case BO_LE: 11257 case BO_GE: 11258 case BO_EQ: 11259 case BO_NE: 11260 case BO_And: 11261 case BO_Xor: 11262 case BO_Or: 11263 case BO_Comma: 11264 case BO_Cmp: { 11265 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 11266 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 11267 if (Exp->getOpcode() == BO_Div || 11268 Exp->getOpcode() == BO_Rem) { 11269 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 11270 // we don't evaluate one. 11271 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 11272 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 11273 if (REval == 0) 11274 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11275 if (REval.isSigned() && REval.isAllOnesValue()) { 11276 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 11277 if (LEval.isMinSignedValue()) 11278 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11279 } 11280 } 11281 } 11282 if (Exp->getOpcode() == BO_Comma) { 11283 if (Ctx.getLangOpts().C99) { 11284 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 11285 // if it isn't evaluated. 11286 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 11287 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11288 } else { 11289 // In both C89 and C++, commas in ICEs are illegal. 11290 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11291 } 11292 } 11293 return Worst(LHSResult, RHSResult); 11294 } 11295 case BO_LAnd: 11296 case BO_LOr: { 11297 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 11298 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 11299 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 11300 // Rare case where the RHS has a comma "side-effect"; we need 11301 // to actually check the condition to see whether the side 11302 // with the comma is evaluated. 11303 if ((Exp->getOpcode() == BO_LAnd) != 11304 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 11305 return RHSResult; 11306 return NoDiag(); 11307 } 11308 11309 return Worst(LHSResult, RHSResult); 11310 } 11311 } 11312 llvm_unreachable("invalid binary operator kind"); 11313 } 11314 case Expr::ImplicitCastExprClass: 11315 case Expr::CStyleCastExprClass: 11316 case Expr::CXXFunctionalCastExprClass: 11317 case Expr::CXXStaticCastExprClass: 11318 case Expr::CXXReinterpretCastExprClass: 11319 case Expr::CXXConstCastExprClass: 11320 case Expr::ObjCBridgedCastExprClass: { 11321 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 11322 if (isa<ExplicitCastExpr>(E)) { 11323 if (const FloatingLiteral *FL 11324 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 11325 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 11326 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 11327 APSInt IgnoredVal(DestWidth, !DestSigned); 11328 bool Ignored; 11329 // If the value does not fit in the destination type, the behavior is 11330 // undefined, so we are not required to treat it as a constant 11331 // expression. 11332 if (FL->getValue().convertToInteger(IgnoredVal, 11333 llvm::APFloat::rmTowardZero, 11334 &Ignored) & APFloat::opInvalidOp) 11335 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11336 return NoDiag(); 11337 } 11338 } 11339 switch (cast<CastExpr>(E)->getCastKind()) { 11340 case CK_LValueToRValue: 11341 case CK_AtomicToNonAtomic: 11342 case CK_NonAtomicToAtomic: 11343 case CK_NoOp: 11344 case CK_IntegralToBoolean: 11345 case CK_IntegralCast: 11346 return CheckICE(SubExpr, Ctx); 11347 default: 11348 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11349 } 11350 } 11351 case Expr::BinaryConditionalOperatorClass: { 11352 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 11353 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 11354 if (CommonResult.Kind == IK_NotICE) return CommonResult; 11355 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 11356 if (FalseResult.Kind == IK_NotICE) return FalseResult; 11357 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 11358 if (FalseResult.Kind == IK_ICEIfUnevaluated && 11359 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 11360 return FalseResult; 11361 } 11362 case Expr::ConditionalOperatorClass: { 11363 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 11364 // If the condition (ignoring parens) is a __builtin_constant_p call, 11365 // then only the true side is actually considered in an integer constant 11366 // expression, and it is fully evaluated. This is an important GNU 11367 // extension. See GCC PR38377 for discussion. 11368 if (const CallExpr *CallCE 11369 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 11370 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 11371 return CheckEvalInICE(E, Ctx); 11372 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 11373 if (CondResult.Kind == IK_NotICE) 11374 return CondResult; 11375 11376 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 11377 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 11378 11379 if (TrueResult.Kind == IK_NotICE) 11380 return TrueResult; 11381 if (FalseResult.Kind == IK_NotICE) 11382 return FalseResult; 11383 if (CondResult.Kind == IK_ICEIfUnevaluated) 11384 return CondResult; 11385 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 11386 return NoDiag(); 11387 // Rare case where the diagnostics depend on which side is evaluated 11388 // Note that if we get here, CondResult is 0, and at least one of 11389 // TrueResult and FalseResult is non-zero. 11390 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 11391 return FalseResult; 11392 return TrueResult; 11393 } 11394 case Expr::CXXDefaultArgExprClass: 11395 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 11396 case Expr::CXXDefaultInitExprClass: 11397 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 11398 case Expr::ChooseExprClass: { 11399 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 11400 } 11401 } 11402 11403 llvm_unreachable("Invalid StmtClass!"); 11404 } 11405 11406 /// Evaluate an expression as a C++11 integral constant expression. 11407 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 11408 const Expr *E, 11409 llvm::APSInt *Value, 11410 SourceLocation *Loc) { 11411 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 11412 if (Loc) *Loc = E->getExprLoc(); 11413 return false; 11414 } 11415 11416 APValue Result; 11417 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 11418 return false; 11419 11420 if (!Result.isInt()) { 11421 if (Loc) *Loc = E->getExprLoc(); 11422 return false; 11423 } 11424 11425 if (Value) *Value = Result.getInt(); 11426 return true; 11427 } 11428 11429 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 11430 SourceLocation *Loc) const { 11431 if (Ctx.getLangOpts().CPlusPlus11) 11432 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 11433 11434 ICEDiag D = CheckICE(this, Ctx); 11435 if (D.Kind != IK_ICE) { 11436 if (Loc) *Loc = D.Loc; 11437 return false; 11438 } 11439 return true; 11440 } 11441 11442 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 11443 SourceLocation *Loc, bool isEvaluated) const { 11444 if (Ctx.getLangOpts().CPlusPlus11) 11445 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 11446 11447 if (!isIntegerConstantExpr(Ctx, Loc)) 11448 return false; 11449 11450 // The only possible side-effects here are due to UB discovered in the 11451 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 11452 // required to treat the expression as an ICE, so we produce the folded 11453 // value. 11454 EvalResult ExprResult; 11455 Expr::EvalStatus Status; 11456 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 11457 Info.InConstantContext = true; 11458 11459 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 11460 llvm_unreachable("ICE cannot be evaluated!"); 11461 11462 Value = ExprResult.Val.getInt(); 11463 return true; 11464 } 11465 11466 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 11467 return CheckICE(this, Ctx).Kind == IK_ICE; 11468 } 11469 11470 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 11471 SourceLocation *Loc) const { 11472 // We support this checking in C++98 mode in order to diagnose compatibility 11473 // issues. 11474 assert(Ctx.getLangOpts().CPlusPlus); 11475 11476 // Build evaluation settings. 11477 Expr::EvalStatus Status; 11478 SmallVector<PartialDiagnosticAt, 8> Diags; 11479 Status.Diag = &Diags; 11480 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 11481 11482 APValue Scratch; 11483 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 11484 11485 if (!Diags.empty()) { 11486 IsConstExpr = false; 11487 if (Loc) *Loc = Diags[0].first; 11488 } else if (!IsConstExpr) { 11489 // FIXME: This shouldn't happen. 11490 if (Loc) *Loc = getExprLoc(); 11491 } 11492 11493 return IsConstExpr; 11494 } 11495 11496 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 11497 const FunctionDecl *Callee, 11498 ArrayRef<const Expr*> Args, 11499 const Expr *This) const { 11500 Expr::EvalStatus Status; 11501 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 11502 11503 LValue ThisVal; 11504 const LValue *ThisPtr = nullptr; 11505 if (This) { 11506 #ifndef NDEBUG 11507 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 11508 assert(MD && "Don't provide `this` for non-methods."); 11509 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 11510 #endif 11511 if (EvaluateObjectArgument(Info, This, ThisVal)) 11512 ThisPtr = &ThisVal; 11513 if (Info.EvalStatus.HasSideEffects) 11514 return false; 11515 } 11516 11517 ArgVector ArgValues(Args.size()); 11518 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 11519 I != E; ++I) { 11520 if ((*I)->isValueDependent() || 11521 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 11522 // If evaluation fails, throw away the argument entirely. 11523 ArgValues[I - Args.begin()] = APValue(); 11524 if (Info.EvalStatus.HasSideEffects) 11525 return false; 11526 } 11527 11528 // Build fake call to Callee. 11529 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 11530 ArgValues.data()); 11531 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 11532 } 11533 11534 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 11535 SmallVectorImpl< 11536 PartialDiagnosticAt> &Diags) { 11537 // FIXME: It would be useful to check constexpr function templates, but at the 11538 // moment the constant expression evaluator cannot cope with the non-rigorous 11539 // ASTs which we build for dependent expressions. 11540 if (FD->isDependentContext()) 11541 return true; 11542 11543 Expr::EvalStatus Status; 11544 Status.Diag = &Diags; 11545 11546 EvalInfo Info(FD->getASTContext(), Status, 11547 EvalInfo::EM_PotentialConstantExpression); 11548 Info.InConstantContext = true; 11549 11550 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 11551 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 11552 11553 // Fabricate an arbitrary expression on the stack and pretend that it 11554 // is a temporary being used as the 'this' pointer. 11555 LValue This; 11556 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 11557 This.set({&VIE, Info.CurrentCall->Index}); 11558 11559 ArrayRef<const Expr*> Args; 11560 11561 APValue Scratch; 11562 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 11563 // Evaluate the call as a constant initializer, to allow the construction 11564 // of objects of non-literal types. 11565 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 11566 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 11567 } else { 11568 SourceLocation Loc = FD->getLocation(); 11569 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 11570 Args, FD->getBody(), Info, Scratch, nullptr); 11571 } 11572 11573 return Diags.empty(); 11574 } 11575 11576 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 11577 const FunctionDecl *FD, 11578 SmallVectorImpl< 11579 PartialDiagnosticAt> &Diags) { 11580 Expr::EvalStatus Status; 11581 Status.Diag = &Diags; 11582 11583 EvalInfo Info(FD->getASTContext(), Status, 11584 EvalInfo::EM_PotentialConstantExpressionUnevaluated); 11585 11586 // Fabricate a call stack frame to give the arguments a plausible cover story. 11587 ArrayRef<const Expr*> Args; 11588 ArgVector ArgValues(0); 11589 bool Success = EvaluateArgs(Args, ArgValues, Info); 11590 (void)Success; 11591 assert(Success && 11592 "Failed to set up arguments for potential constant evaluation"); 11593 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 11594 11595 APValue ResultScratch; 11596 Evaluate(ResultScratch, Info, E); 11597 return Diags.empty(); 11598 } 11599 11600 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 11601 unsigned Type) const { 11602 if (!getType()->isPointerType()) 11603 return false; 11604 11605 Expr::EvalStatus Status; 11606 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 11607 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 11608 } 11609