1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Expr constant evaluator. 11 // 12 // Constant expression evaluation produces four main results: 13 // 14 // * A success/failure flag indicating whether constant folding was successful. 15 // This is the 'bool' return value used by most of the code in this file. A 16 // 'false' return value indicates that constant folding has failed, and any 17 // appropriate diagnostic has already been produced. 18 // 19 // * An evaluated result, valid only if constant folding has not failed. 20 // 21 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 23 // where it is possible to determine the evaluated result regardless. 24 // 25 // * A set of notes indicating why the evaluation was not a constant expression 26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 27 // too, why the expression could not be folded. 28 // 29 // If we are checking for a potential constant expression, failure to constant 30 // fold a potential constant sub-expression will be indicated by a 'false' 31 // return value (the expression could not be folded) and no diagnostic (the 32 // expression is not necessarily non-constant). 33 // 34 //===----------------------------------------------------------------------===// 35 36 #include "clang/AST/APValue.h" 37 #include "clang/AST/ASTContext.h" 38 #include "clang/AST/ASTDiagnostic.h" 39 #include "clang/AST/ASTLambda.h" 40 #include "clang/AST/CharUnits.h" 41 #include "clang/AST/Expr.h" 42 #include "clang/AST/RecordLayout.h" 43 #include "clang/AST/StmtVisitor.h" 44 #include "clang/AST/TypeLoc.h" 45 #include "clang/Basic/Builtins.h" 46 #include "clang/Basic/TargetInfo.h" 47 #include "llvm/Support/raw_ostream.h" 48 #include <cstring> 49 #include <functional> 50 51 #define DEBUG_TYPE "exprconstant" 52 53 using namespace clang; 54 using llvm::APSInt; 55 using llvm::APFloat; 56 57 static bool IsGlobalLValue(APValue::LValueBase B); 58 59 namespace { 60 struct LValue; 61 struct CallStackFrame; 62 struct EvalInfo; 63 64 static QualType getType(APValue::LValueBase B) { 65 if (!B) return QualType(); 66 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 67 // FIXME: It's unclear where we're supposed to take the type from, and 68 // this actually matters for arrays of unknown bound. Eg: 69 // 70 // extern int arr[]; void f() { extern int arr[3]; }; 71 // constexpr int *p = &arr[1]; // valid? 72 // 73 // For now, we take the array bound from the most recent declaration. 74 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 75 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 76 QualType T = Redecl->getType(); 77 if (!T->isIncompleteArrayType()) 78 return T; 79 } 80 return D->getType(); 81 } 82 83 const Expr *Base = B.get<const Expr*>(); 84 85 // For a materialized temporary, the type of the temporary we materialized 86 // may not be the type of the expression. 87 if (const MaterializeTemporaryExpr *MTE = 88 dyn_cast<MaterializeTemporaryExpr>(Base)) { 89 SmallVector<const Expr *, 2> CommaLHSs; 90 SmallVector<SubobjectAdjustment, 2> Adjustments; 91 const Expr *Temp = MTE->GetTemporaryExpr(); 92 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 93 Adjustments); 94 // Keep any cv-qualifiers from the reference if we generated a temporary 95 // for it directly. Otherwise use the type after adjustment. 96 if (!Adjustments.empty()) 97 return Inner->getType(); 98 } 99 100 return Base->getType(); 101 } 102 103 /// Get an LValue path entry, which is known to not be an array index, as a 104 /// field or base class. 105 static 106 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) { 107 APValue::BaseOrMemberType Value; 108 Value.setFromOpaqueValue(E.BaseOrMember); 109 return Value; 110 } 111 112 /// Get an LValue path entry, which is known to not be an array index, as a 113 /// field declaration. 114 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 115 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer()); 116 } 117 /// Get an LValue path entry, which is known to not be an array index, as a 118 /// base class declaration. 119 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 120 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer()); 121 } 122 /// Determine whether this LValue path entry for a base class names a virtual 123 /// base class. 124 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 125 return getAsBaseOrMember(E).getInt(); 126 } 127 128 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 129 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 130 const FunctionDecl *Callee = CE->getDirectCallee(); 131 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 132 } 133 134 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 135 /// This will look through a single cast. 136 /// 137 /// Returns null if we couldn't unwrap a function with alloc_size. 138 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 139 if (!E->getType()->isPointerType()) 140 return nullptr; 141 142 E = E->IgnoreParens(); 143 // If we're doing a variable assignment from e.g. malloc(N), there will 144 // probably be a cast of some kind. In exotic cases, we might also see a 145 // top-level ExprWithCleanups. Ignore them either way. 146 if (const auto *EC = dyn_cast<ExprWithCleanups>(E)) 147 E = EC->getSubExpr()->IgnoreParens(); 148 149 if (const auto *Cast = dyn_cast<CastExpr>(E)) 150 E = Cast->getSubExpr()->IgnoreParens(); 151 152 if (const auto *CE = dyn_cast<CallExpr>(E)) 153 return getAllocSizeAttr(CE) ? CE : nullptr; 154 return nullptr; 155 } 156 157 /// Determines whether or not the given Base contains a call to a function 158 /// with the alloc_size attribute. 159 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 160 const auto *E = Base.dyn_cast<const Expr *>(); 161 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 162 } 163 164 /// The bound to claim that an array of unknown bound has. 165 /// The value in MostDerivedArraySize is undefined in this case. So, set it 166 /// to an arbitrary value that's likely to loudly break things if it's used. 167 static const uint64_t AssumedSizeForUnsizedArray = 168 std::numeric_limits<uint64_t>::max() / 2; 169 170 /// Determines if an LValue with the given LValueBase will have an unsized 171 /// array in its designator. 172 /// Find the path length and type of the most-derived subobject in the given 173 /// path, and find the size of the containing array, if any. 174 static unsigned 175 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 176 ArrayRef<APValue::LValuePathEntry> Path, 177 uint64_t &ArraySize, QualType &Type, bool &IsArray, 178 bool &FirstEntryIsUnsizedArray) { 179 // This only accepts LValueBases from APValues, and APValues don't support 180 // arrays that lack size info. 181 assert(!isBaseAnAllocSizeCall(Base) && 182 "Unsized arrays shouldn't appear here"); 183 unsigned MostDerivedLength = 0; 184 Type = getType(Base); 185 186 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 187 if (Type->isArrayType()) { 188 const ArrayType *AT = Ctx.getAsArrayType(Type); 189 Type = AT->getElementType(); 190 MostDerivedLength = I + 1; 191 IsArray = true; 192 193 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 194 ArraySize = CAT->getSize().getZExtValue(); 195 } else { 196 assert(I == 0 && "unexpected unsized array designator"); 197 FirstEntryIsUnsizedArray = true; 198 ArraySize = AssumedSizeForUnsizedArray; 199 } 200 } else if (Type->isAnyComplexType()) { 201 const ComplexType *CT = Type->castAs<ComplexType>(); 202 Type = CT->getElementType(); 203 ArraySize = 2; 204 MostDerivedLength = I + 1; 205 IsArray = true; 206 } else if (const FieldDecl *FD = getAsField(Path[I])) { 207 Type = FD->getType(); 208 ArraySize = 0; 209 MostDerivedLength = I + 1; 210 IsArray = false; 211 } else { 212 // Path[I] describes a base class. 213 ArraySize = 0; 214 IsArray = false; 215 } 216 } 217 return MostDerivedLength; 218 } 219 220 // The order of this enum is important for diagnostics. 221 enum CheckSubobjectKind { 222 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 223 CSK_This, CSK_Real, CSK_Imag 224 }; 225 226 /// A path from a glvalue to a subobject of that glvalue. 227 struct SubobjectDesignator { 228 /// True if the subobject was named in a manner not supported by C++11. Such 229 /// lvalues can still be folded, but they are not core constant expressions 230 /// and we cannot perform lvalue-to-rvalue conversions on them. 231 unsigned Invalid : 1; 232 233 /// Is this a pointer one past the end of an object? 234 unsigned IsOnePastTheEnd : 1; 235 236 /// Indicator of whether the first entry is an unsized array. 237 unsigned FirstEntryIsAnUnsizedArray : 1; 238 239 /// Indicator of whether the most-derived object is an array element. 240 unsigned MostDerivedIsArrayElement : 1; 241 242 /// The length of the path to the most-derived object of which this is a 243 /// subobject. 244 unsigned MostDerivedPathLength : 28; 245 246 /// The size of the array of which the most-derived object is an element. 247 /// This will always be 0 if the most-derived object is not an array 248 /// element. 0 is not an indicator of whether or not the most-derived object 249 /// is an array, however, because 0-length arrays are allowed. 250 /// 251 /// If the current array is an unsized array, the value of this is 252 /// undefined. 253 uint64_t MostDerivedArraySize; 254 255 /// The type of the most derived object referred to by this address. 256 QualType MostDerivedType; 257 258 typedef APValue::LValuePathEntry PathEntry; 259 260 /// The entries on the path from the glvalue to the designated subobject. 261 SmallVector<PathEntry, 8> Entries; 262 263 SubobjectDesignator() : Invalid(true) {} 264 265 explicit SubobjectDesignator(QualType T) 266 : Invalid(false), IsOnePastTheEnd(false), 267 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 268 MostDerivedPathLength(0), MostDerivedArraySize(0), 269 MostDerivedType(T) {} 270 271 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 272 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 274 MostDerivedPathLength(0), MostDerivedArraySize(0) { 275 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 276 if (!Invalid) { 277 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 278 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 279 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 280 if (V.getLValueBase()) { 281 bool IsArray = false; 282 bool FirstIsUnsizedArray = false; 283 MostDerivedPathLength = findMostDerivedSubobject( 284 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 285 MostDerivedType, IsArray, FirstIsUnsizedArray); 286 MostDerivedIsArrayElement = IsArray; 287 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 288 } 289 } 290 } 291 292 void setInvalid() { 293 Invalid = true; 294 Entries.clear(); 295 } 296 297 /// Determine whether the most derived subobject is an array without a 298 /// known bound. 299 bool isMostDerivedAnUnsizedArray() const { 300 assert(!Invalid && "Calling this makes no sense on invalid designators"); 301 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 302 } 303 304 /// Determine what the most derived array's size is. Results in an assertion 305 /// failure if the most derived array lacks a size. 306 uint64_t getMostDerivedArraySize() const { 307 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 308 return MostDerivedArraySize; 309 } 310 311 /// Determine whether this is a one-past-the-end pointer. 312 bool isOnePastTheEnd() const { 313 assert(!Invalid); 314 if (IsOnePastTheEnd) 315 return true; 316 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 317 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize) 318 return true; 319 return false; 320 } 321 322 /// Get the range of valid index adjustments in the form 323 /// {maximum value that can be subtracted from this pointer, 324 /// maximum value that can be added to this pointer} 325 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 326 if (Invalid || isMostDerivedAnUnsizedArray()) 327 return {0, 0}; 328 329 // [expr.add]p4: For the purposes of these operators, a pointer to a 330 // nonarray object behaves the same as a pointer to the first element of 331 // an array of length one with the type of the object as its element type. 332 bool IsArray = MostDerivedPathLength == Entries.size() && 333 MostDerivedIsArrayElement; 334 uint64_t ArrayIndex = 335 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; 336 uint64_t ArraySize = 337 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 338 return {ArrayIndex, ArraySize - ArrayIndex}; 339 } 340 341 /// Check that this refers to a valid subobject. 342 bool isValidSubobject() const { 343 if (Invalid) 344 return false; 345 return !isOnePastTheEnd(); 346 } 347 /// Check that this refers to a valid subobject, and if not, produce a 348 /// relevant diagnostic and set the designator as invalid. 349 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 350 351 /// Get the type of the designated object. 352 QualType getType(ASTContext &Ctx) const { 353 assert(!Invalid && "invalid designator has no subobject type"); 354 return MostDerivedPathLength == Entries.size() 355 ? MostDerivedType 356 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 357 } 358 359 /// Update this designator to refer to the first element within this array. 360 void addArrayUnchecked(const ConstantArrayType *CAT) { 361 PathEntry Entry; 362 Entry.ArrayIndex = 0; 363 Entries.push_back(Entry); 364 365 // This is a most-derived object. 366 MostDerivedType = CAT->getElementType(); 367 MostDerivedIsArrayElement = true; 368 MostDerivedArraySize = CAT->getSize().getZExtValue(); 369 MostDerivedPathLength = Entries.size(); 370 } 371 /// Update this designator to refer to the first element within the array of 372 /// elements of type T. This is an array of unknown size. 373 void addUnsizedArrayUnchecked(QualType ElemTy) { 374 PathEntry Entry; 375 Entry.ArrayIndex = 0; 376 Entries.push_back(Entry); 377 378 MostDerivedType = ElemTy; 379 MostDerivedIsArrayElement = true; 380 // The value in MostDerivedArraySize is undefined in this case. So, set it 381 // to an arbitrary value that's likely to loudly break things if it's 382 // used. 383 MostDerivedArraySize = AssumedSizeForUnsizedArray; 384 MostDerivedPathLength = Entries.size(); 385 } 386 /// Update this designator to refer to the given base or member of this 387 /// object. 388 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 389 PathEntry Entry; 390 APValue::BaseOrMemberType Value(D, Virtual); 391 Entry.BaseOrMember = Value.getOpaqueValue(); 392 Entries.push_back(Entry); 393 394 // If this isn't a base class, it's a new most-derived object. 395 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 396 MostDerivedType = FD->getType(); 397 MostDerivedIsArrayElement = false; 398 MostDerivedArraySize = 0; 399 MostDerivedPathLength = Entries.size(); 400 } 401 } 402 /// Update this designator to refer to the given complex component. 403 void addComplexUnchecked(QualType EltTy, bool Imag) { 404 PathEntry Entry; 405 Entry.ArrayIndex = Imag; 406 Entries.push_back(Entry); 407 408 // This is technically a most-derived object, though in practice this 409 // is unlikely to matter. 410 MostDerivedType = EltTy; 411 MostDerivedIsArrayElement = true; 412 MostDerivedArraySize = 2; 413 MostDerivedPathLength = Entries.size(); 414 } 415 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 416 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 417 const APSInt &N); 418 /// Add N to the address of this subobject. 419 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 420 if (Invalid || !N) return; 421 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 422 if (isMostDerivedAnUnsizedArray()) { 423 diagnoseUnsizedArrayPointerArithmetic(Info, E); 424 // Can't verify -- trust that the user is doing the right thing (or if 425 // not, trust that the caller will catch the bad behavior). 426 // FIXME: Should we reject if this overflows, at least? 427 Entries.back().ArrayIndex += TruncatedN; 428 return; 429 } 430 431 // [expr.add]p4: For the purposes of these operators, a pointer to a 432 // nonarray object behaves the same as a pointer to the first element of 433 // an array of length one with the type of the object as its element type. 434 bool IsArray = MostDerivedPathLength == Entries.size() && 435 MostDerivedIsArrayElement; 436 uint64_t ArrayIndex = 437 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; 438 uint64_t ArraySize = 439 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 440 441 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 442 // Calculate the actual index in a wide enough type, so we can include 443 // it in the note. 444 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 445 (llvm::APInt&)N += ArrayIndex; 446 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 447 diagnosePointerArithmetic(Info, E, N); 448 setInvalid(); 449 return; 450 } 451 452 ArrayIndex += TruncatedN; 453 assert(ArrayIndex <= ArraySize && 454 "bounds check succeeded for out-of-bounds index"); 455 456 if (IsArray) 457 Entries.back().ArrayIndex = ArrayIndex; 458 else 459 IsOnePastTheEnd = (ArrayIndex != 0); 460 } 461 }; 462 463 /// A stack frame in the constexpr call stack. 464 struct CallStackFrame { 465 EvalInfo &Info; 466 467 /// Parent - The caller of this stack frame. 468 CallStackFrame *Caller; 469 470 /// Callee - The function which was called. 471 const FunctionDecl *Callee; 472 473 /// This - The binding for the this pointer in this call, if any. 474 const LValue *This; 475 476 /// Arguments - Parameter bindings for this function call, indexed by 477 /// parameters' function scope indices. 478 APValue *Arguments; 479 480 // Note that we intentionally use std::map here so that references to 481 // values are stable. 482 typedef std::pair<const void *, unsigned> MapKeyTy; 483 typedef std::map<MapKeyTy, APValue> MapTy; 484 /// Temporaries - Temporary lvalues materialized within this stack frame. 485 MapTy Temporaries; 486 487 /// CallLoc - The location of the call expression for this call. 488 SourceLocation CallLoc; 489 490 /// Index - The call index of this call. 491 unsigned Index; 492 493 /// The stack of integers for tracking version numbers for temporaries. 494 SmallVector<unsigned, 2> TempVersionStack = {1}; 495 unsigned CurTempVersion = TempVersionStack.back(); 496 497 unsigned getTempVersion() const { return TempVersionStack.back(); } 498 499 void pushTempVersion() { 500 TempVersionStack.push_back(++CurTempVersion); 501 } 502 503 void popTempVersion() { 504 TempVersionStack.pop_back(); 505 } 506 507 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 508 // on the overall stack usage of deeply-recursing constexpr evaluataions. 509 // (We should cache this map rather than recomputing it repeatedly.) 510 // But let's try this and see how it goes; we can look into caching the map 511 // as a later change. 512 513 /// LambdaCaptureFields - Mapping from captured variables/this to 514 /// corresponding data members in the closure class. 515 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 516 FieldDecl *LambdaThisCaptureField; 517 518 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 519 const FunctionDecl *Callee, const LValue *This, 520 APValue *Arguments); 521 ~CallStackFrame(); 522 523 // Return the temporary for Key whose version number is Version. 524 APValue *getTemporary(const void *Key, unsigned Version) { 525 MapKeyTy KV(Key, Version); 526 auto LB = Temporaries.lower_bound(KV); 527 if (LB != Temporaries.end() && LB->first == KV) 528 return &LB->second; 529 // Pair (Key,Version) wasn't found in the map. Check that no elements 530 // in the map have 'Key' as their key. 531 assert((LB == Temporaries.end() || LB->first.first != Key) && 532 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 533 "Element with key 'Key' found in map"); 534 return nullptr; 535 } 536 537 // Return the current temporary for Key in the map. 538 APValue *getCurrentTemporary(const void *Key) { 539 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 540 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 541 return &std::prev(UB)->second; 542 return nullptr; 543 } 544 545 // Return the version number of the current temporary for Key. 546 unsigned getCurrentTemporaryVersion(const void *Key) const { 547 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 548 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 549 return std::prev(UB)->first.second; 550 return 0; 551 } 552 553 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 554 }; 555 556 /// Temporarily override 'this'. 557 class ThisOverrideRAII { 558 public: 559 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 560 : Frame(Frame), OldThis(Frame.This) { 561 if (Enable) 562 Frame.This = NewThis; 563 } 564 ~ThisOverrideRAII() { 565 Frame.This = OldThis; 566 } 567 private: 568 CallStackFrame &Frame; 569 const LValue *OldThis; 570 }; 571 572 /// A partial diagnostic which we might know in advance that we are not going 573 /// to emit. 574 class OptionalDiagnostic { 575 PartialDiagnostic *Diag; 576 577 public: 578 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr) 579 : Diag(Diag) {} 580 581 template<typename T> 582 OptionalDiagnostic &operator<<(const T &v) { 583 if (Diag) 584 *Diag << v; 585 return *this; 586 } 587 588 OptionalDiagnostic &operator<<(const APSInt &I) { 589 if (Diag) { 590 SmallVector<char, 32> Buffer; 591 I.toString(Buffer); 592 *Diag << StringRef(Buffer.data(), Buffer.size()); 593 } 594 return *this; 595 } 596 597 OptionalDiagnostic &operator<<(const APFloat &F) { 598 if (Diag) { 599 // FIXME: Force the precision of the source value down so we don't 600 // print digits which are usually useless (we don't really care here if 601 // we truncate a digit by accident in edge cases). Ideally, 602 // APFloat::toString would automatically print the shortest 603 // representation which rounds to the correct value, but it's a bit 604 // tricky to implement. 605 unsigned precision = 606 llvm::APFloat::semanticsPrecision(F.getSemantics()); 607 precision = (precision * 59 + 195) / 196; 608 SmallVector<char, 32> Buffer; 609 F.toString(Buffer, precision); 610 *Diag << StringRef(Buffer.data(), Buffer.size()); 611 } 612 return *this; 613 } 614 }; 615 616 /// A cleanup, and a flag indicating whether it is lifetime-extended. 617 class Cleanup { 618 llvm::PointerIntPair<APValue*, 1, bool> Value; 619 620 public: 621 Cleanup(APValue *Val, bool IsLifetimeExtended) 622 : Value(Val, IsLifetimeExtended) {} 623 624 bool isLifetimeExtended() const { return Value.getInt(); } 625 void endLifetime() { 626 *Value.getPointer() = APValue(); 627 } 628 }; 629 630 /// EvalInfo - This is a private struct used by the evaluator to capture 631 /// information about a subexpression as it is folded. It retains information 632 /// about the AST context, but also maintains information about the folded 633 /// expression. 634 /// 635 /// If an expression could be evaluated, it is still possible it is not a C 636 /// "integer constant expression" or constant expression. If not, this struct 637 /// captures information about how and why not. 638 /// 639 /// One bit of information passed *into* the request for constant folding 640 /// indicates whether the subexpression is "evaluated" or not according to C 641 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 642 /// evaluate the expression regardless of what the RHS is, but C only allows 643 /// certain things in certain situations. 644 struct EvalInfo { 645 ASTContext &Ctx; 646 647 /// EvalStatus - Contains information about the evaluation. 648 Expr::EvalStatus &EvalStatus; 649 650 /// CurrentCall - The top of the constexpr call stack. 651 CallStackFrame *CurrentCall; 652 653 /// CallStackDepth - The number of calls in the call stack right now. 654 unsigned CallStackDepth; 655 656 /// NextCallIndex - The next call index to assign. 657 unsigned NextCallIndex; 658 659 /// StepsLeft - The remaining number of evaluation steps we're permitted 660 /// to perform. This is essentially a limit for the number of statements 661 /// we will evaluate. 662 unsigned StepsLeft; 663 664 /// BottomFrame - The frame in which evaluation started. This must be 665 /// initialized after CurrentCall and CallStackDepth. 666 CallStackFrame BottomFrame; 667 668 /// A stack of values whose lifetimes end at the end of some surrounding 669 /// evaluation frame. 670 llvm::SmallVector<Cleanup, 16> CleanupStack; 671 672 /// EvaluatingDecl - This is the declaration whose initializer is being 673 /// evaluated, if any. 674 APValue::LValueBase EvaluatingDecl; 675 676 /// EvaluatingDeclValue - This is the value being constructed for the 677 /// declaration whose initializer is being evaluated, if any. 678 APValue *EvaluatingDeclValue; 679 680 /// EvaluatingObject - Pair of the AST node that an lvalue represents and 681 /// the call index that that lvalue was allocated in. 682 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>> 683 EvaluatingObject; 684 685 /// EvaluatingConstructors - Set of objects that are currently being 686 /// constructed. 687 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors; 688 689 struct EvaluatingConstructorRAII { 690 EvalInfo &EI; 691 EvaluatingObject Object; 692 bool DidInsert; 693 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object) 694 : EI(EI), Object(Object) { 695 DidInsert = EI.EvaluatingConstructors.insert(Object).second; 696 } 697 ~EvaluatingConstructorRAII() { 698 if (DidInsert) EI.EvaluatingConstructors.erase(Object); 699 } 700 }; 701 702 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex, 703 unsigned Version) { 704 return EvaluatingConstructors.count( 705 EvaluatingObject(Decl, {CallIndex, Version})); 706 } 707 708 /// The current array initialization index, if we're performing array 709 /// initialization. 710 uint64_t ArrayInitIndex = -1; 711 712 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 713 /// notes attached to it will also be stored, otherwise they will not be. 714 bool HasActiveDiagnostic; 715 716 /// Have we emitted a diagnostic explaining why we couldn't constant 717 /// fold (not just why it's not strictly a constant expression)? 718 bool HasFoldFailureDiagnostic; 719 720 /// Whether or not we're currently speculatively evaluating. 721 bool IsSpeculativelyEvaluating; 722 723 enum EvaluationMode { 724 /// Evaluate as a constant expression. Stop if we find that the expression 725 /// is not a constant expression. 726 EM_ConstantExpression, 727 728 /// Evaluate as a potential constant expression. Keep going if we hit a 729 /// construct that we can't evaluate yet (because we don't yet know the 730 /// value of something) but stop if we hit something that could never be 731 /// a constant expression. 732 EM_PotentialConstantExpression, 733 734 /// Fold the expression to a constant. Stop if we hit a side-effect that 735 /// we can't model. 736 EM_ConstantFold, 737 738 /// Evaluate the expression looking for integer overflow and similar 739 /// issues. Don't worry about side-effects, and try to visit all 740 /// subexpressions. 741 EM_EvaluateForOverflow, 742 743 /// Evaluate in any way we know how. Don't worry about side-effects that 744 /// can't be modeled. 745 EM_IgnoreSideEffects, 746 747 /// Evaluate as a constant expression. Stop if we find that the expression 748 /// is not a constant expression. Some expressions can be retried in the 749 /// optimizer if we don't constant fold them here, but in an unevaluated 750 /// context we try to fold them immediately since the optimizer never 751 /// gets a chance to look at it. 752 EM_ConstantExpressionUnevaluated, 753 754 /// Evaluate as a potential constant expression. Keep going if we hit a 755 /// construct that we can't evaluate yet (because we don't yet know the 756 /// value of something) but stop if we hit something that could never be 757 /// a constant expression. Some expressions can be retried in the 758 /// optimizer if we don't constant fold them here, but in an unevaluated 759 /// context we try to fold them immediately since the optimizer never 760 /// gets a chance to look at it. 761 EM_PotentialConstantExpressionUnevaluated, 762 763 /// Evaluate as a constant expression. In certain scenarios, if: 764 /// - we find a MemberExpr with a base that can't be evaluated, or 765 /// - we find a variable initialized with a call to a function that has 766 /// the alloc_size attribute on it 767 /// then we may consider evaluation to have succeeded. 768 /// 769 /// In either case, the LValue returned shall have an invalid base; in the 770 /// former, the base will be the invalid MemberExpr, in the latter, the 771 /// base will be either the alloc_size CallExpr or a CastExpr wrapping 772 /// said CallExpr. 773 EM_OffsetFold, 774 } EvalMode; 775 776 /// Are we checking whether the expression is a potential constant 777 /// expression? 778 bool checkingPotentialConstantExpression() const { 779 return EvalMode == EM_PotentialConstantExpression || 780 EvalMode == EM_PotentialConstantExpressionUnevaluated; 781 } 782 783 /// Are we checking an expression for overflow? 784 // FIXME: We should check for any kind of undefined or suspicious behavior 785 // in such constructs, not just overflow. 786 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; } 787 788 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 789 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 790 CallStackDepth(0), NextCallIndex(1), 791 StepsLeft(getLangOpts().ConstexprStepLimit), 792 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 793 EvaluatingDecl((const ValueDecl *)nullptr), 794 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 795 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false), 796 EvalMode(Mode) {} 797 798 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 799 EvaluatingDecl = Base; 800 EvaluatingDeclValue = &Value; 801 EvaluatingConstructors.insert({Base, {0, 0}}); 802 } 803 804 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 805 806 bool CheckCallLimit(SourceLocation Loc) { 807 // Don't perform any constexpr calls (other than the call we're checking) 808 // when checking a potential constant expression. 809 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 810 return false; 811 if (NextCallIndex == 0) { 812 // NextCallIndex has wrapped around. 813 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 814 return false; 815 } 816 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 817 return true; 818 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 819 << getLangOpts().ConstexprCallDepth; 820 return false; 821 } 822 823 CallStackFrame *getCallFrame(unsigned CallIndex) { 824 assert(CallIndex && "no call index in getCallFrame"); 825 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 826 // be null in this loop. 827 CallStackFrame *Frame = CurrentCall; 828 while (Frame->Index > CallIndex) 829 Frame = Frame->Caller; 830 return (Frame->Index == CallIndex) ? Frame : nullptr; 831 } 832 833 bool nextStep(const Stmt *S) { 834 if (!StepsLeft) { 835 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 836 return false; 837 } 838 --StepsLeft; 839 return true; 840 } 841 842 private: 843 /// Add a diagnostic to the diagnostics list. 844 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 845 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 846 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 847 return EvalStatus.Diag->back().second; 848 } 849 850 /// Add notes containing a call stack to the current point of evaluation. 851 void addCallStack(unsigned Limit); 852 853 private: 854 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, 855 unsigned ExtraNotes, bool IsCCEDiag) { 856 857 if (EvalStatus.Diag) { 858 // If we have a prior diagnostic, it will be noting that the expression 859 // isn't a constant expression. This diagnostic is more important, 860 // unless we require this evaluation to produce a constant expression. 861 // 862 // FIXME: We might want to show both diagnostics to the user in 863 // EM_ConstantFold mode. 864 if (!EvalStatus.Diag->empty()) { 865 switch (EvalMode) { 866 case EM_ConstantFold: 867 case EM_IgnoreSideEffects: 868 case EM_EvaluateForOverflow: 869 if (!HasFoldFailureDiagnostic) 870 break; 871 // We've already failed to fold something. Keep that diagnostic. 872 LLVM_FALLTHROUGH; 873 case EM_ConstantExpression: 874 case EM_PotentialConstantExpression: 875 case EM_ConstantExpressionUnevaluated: 876 case EM_PotentialConstantExpressionUnevaluated: 877 case EM_OffsetFold: 878 HasActiveDiagnostic = false; 879 return OptionalDiagnostic(); 880 } 881 } 882 883 unsigned CallStackNotes = CallStackDepth - 1; 884 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 885 if (Limit) 886 CallStackNotes = std::min(CallStackNotes, Limit + 1); 887 if (checkingPotentialConstantExpression()) 888 CallStackNotes = 0; 889 890 HasActiveDiagnostic = true; 891 HasFoldFailureDiagnostic = !IsCCEDiag; 892 EvalStatus.Diag->clear(); 893 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 894 addDiag(Loc, DiagId); 895 if (!checkingPotentialConstantExpression()) 896 addCallStack(Limit); 897 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 898 } 899 HasActiveDiagnostic = false; 900 return OptionalDiagnostic(); 901 } 902 public: 903 // Diagnose that the evaluation could not be folded (FF => FoldFailure) 904 OptionalDiagnostic 905 FFDiag(SourceLocation Loc, 906 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, 907 unsigned ExtraNotes = 0) { 908 return Diag(Loc, DiagId, ExtraNotes, false); 909 } 910 911 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId 912 = diag::note_invalid_subexpr_in_const_expr, 913 unsigned ExtraNotes = 0) { 914 if (EvalStatus.Diag) 915 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false); 916 HasActiveDiagnostic = false; 917 return OptionalDiagnostic(); 918 } 919 920 /// Diagnose that the evaluation does not produce a C++11 core constant 921 /// expression. 922 /// 923 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or 924 /// EM_PotentialConstantExpression mode and we produce one of these. 925 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 926 = diag::note_invalid_subexpr_in_const_expr, 927 unsigned ExtraNotes = 0) { 928 // Don't override a previous diagnostic. Don't bother collecting 929 // diagnostics if we're evaluating for overflow. 930 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 931 HasActiveDiagnostic = false; 932 return OptionalDiagnostic(); 933 } 934 return Diag(Loc, DiagId, ExtraNotes, true); 935 } 936 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId 937 = diag::note_invalid_subexpr_in_const_expr, 938 unsigned ExtraNotes = 0) { 939 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes); 940 } 941 /// Add a note to a prior diagnostic. 942 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 943 if (!HasActiveDiagnostic) 944 return OptionalDiagnostic(); 945 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 946 } 947 948 /// Add a stack of notes to a prior diagnostic. 949 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 950 if (HasActiveDiagnostic) { 951 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 952 Diags.begin(), Diags.end()); 953 } 954 } 955 956 /// Should we continue evaluation after encountering a side-effect that we 957 /// couldn't model? 958 bool keepEvaluatingAfterSideEffect() { 959 switch (EvalMode) { 960 case EM_PotentialConstantExpression: 961 case EM_PotentialConstantExpressionUnevaluated: 962 case EM_EvaluateForOverflow: 963 case EM_IgnoreSideEffects: 964 return true; 965 966 case EM_ConstantExpression: 967 case EM_ConstantExpressionUnevaluated: 968 case EM_ConstantFold: 969 case EM_OffsetFold: 970 return false; 971 } 972 llvm_unreachable("Missed EvalMode case"); 973 } 974 975 /// Note that we have had a side-effect, and determine whether we should 976 /// keep evaluating. 977 bool noteSideEffect() { 978 EvalStatus.HasSideEffects = true; 979 return keepEvaluatingAfterSideEffect(); 980 } 981 982 /// Should we continue evaluation after encountering undefined behavior? 983 bool keepEvaluatingAfterUndefinedBehavior() { 984 switch (EvalMode) { 985 case EM_EvaluateForOverflow: 986 case EM_IgnoreSideEffects: 987 case EM_ConstantFold: 988 case EM_OffsetFold: 989 return true; 990 991 case EM_PotentialConstantExpression: 992 case EM_PotentialConstantExpressionUnevaluated: 993 case EM_ConstantExpression: 994 case EM_ConstantExpressionUnevaluated: 995 return false; 996 } 997 llvm_unreachable("Missed EvalMode case"); 998 } 999 1000 /// Note that we hit something that was technically undefined behavior, but 1001 /// that we can evaluate past it (such as signed overflow or floating-point 1002 /// division by zero.) 1003 bool noteUndefinedBehavior() { 1004 EvalStatus.HasUndefinedBehavior = true; 1005 return keepEvaluatingAfterUndefinedBehavior(); 1006 } 1007 1008 /// Should we continue evaluation as much as possible after encountering a 1009 /// construct which can't be reduced to a value? 1010 bool keepEvaluatingAfterFailure() { 1011 if (!StepsLeft) 1012 return false; 1013 1014 switch (EvalMode) { 1015 case EM_PotentialConstantExpression: 1016 case EM_PotentialConstantExpressionUnevaluated: 1017 case EM_EvaluateForOverflow: 1018 return true; 1019 1020 case EM_ConstantExpression: 1021 case EM_ConstantExpressionUnevaluated: 1022 case EM_ConstantFold: 1023 case EM_IgnoreSideEffects: 1024 case EM_OffsetFold: 1025 return false; 1026 } 1027 llvm_unreachable("Missed EvalMode case"); 1028 } 1029 1030 /// Notes that we failed to evaluate an expression that other expressions 1031 /// directly depend on, and determine if we should keep evaluating. This 1032 /// should only be called if we actually intend to keep evaluating. 1033 /// 1034 /// Call noteSideEffect() instead if we may be able to ignore the value that 1035 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1036 /// 1037 /// (Foo(), 1) // use noteSideEffect 1038 /// (Foo() || true) // use noteSideEffect 1039 /// Foo() + 1 // use noteFailure 1040 LLVM_NODISCARD bool noteFailure() { 1041 // Failure when evaluating some expression often means there is some 1042 // subexpression whose evaluation was skipped. Therefore, (because we 1043 // don't track whether we skipped an expression when unwinding after an 1044 // evaluation failure) every evaluation failure that bubbles up from a 1045 // subexpression implies that a side-effect has potentially happened. We 1046 // skip setting the HasSideEffects flag to true until we decide to 1047 // continue evaluating after that point, which happens here. 1048 bool KeepGoing = keepEvaluatingAfterFailure(); 1049 EvalStatus.HasSideEffects |= KeepGoing; 1050 return KeepGoing; 1051 } 1052 1053 class ArrayInitLoopIndex { 1054 EvalInfo &Info; 1055 uint64_t OuterIndex; 1056 1057 public: 1058 ArrayInitLoopIndex(EvalInfo &Info) 1059 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1060 Info.ArrayInitIndex = 0; 1061 } 1062 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1063 1064 operator uint64_t&() { return Info.ArrayInitIndex; } 1065 }; 1066 }; 1067 1068 /// Object used to treat all foldable expressions as constant expressions. 1069 struct FoldConstant { 1070 EvalInfo &Info; 1071 bool Enabled; 1072 bool HadNoPriorDiags; 1073 EvalInfo::EvaluationMode OldMode; 1074 1075 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1076 : Info(Info), 1077 Enabled(Enabled), 1078 HadNoPriorDiags(Info.EvalStatus.Diag && 1079 Info.EvalStatus.Diag->empty() && 1080 !Info.EvalStatus.HasSideEffects), 1081 OldMode(Info.EvalMode) { 1082 if (Enabled && 1083 (Info.EvalMode == EvalInfo::EM_ConstantExpression || 1084 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated)) 1085 Info.EvalMode = EvalInfo::EM_ConstantFold; 1086 } 1087 void keepDiagnostics() { Enabled = false; } 1088 ~FoldConstant() { 1089 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1090 !Info.EvalStatus.HasSideEffects) 1091 Info.EvalStatus.Diag->clear(); 1092 Info.EvalMode = OldMode; 1093 } 1094 }; 1095 1096 /// RAII object used to treat the current evaluation as the correct pointer 1097 /// offset fold for the current EvalMode 1098 struct FoldOffsetRAII { 1099 EvalInfo &Info; 1100 EvalInfo::EvaluationMode OldMode; 1101 explicit FoldOffsetRAII(EvalInfo &Info) 1102 : Info(Info), OldMode(Info.EvalMode) { 1103 if (!Info.checkingPotentialConstantExpression()) 1104 Info.EvalMode = EvalInfo::EM_OffsetFold; 1105 } 1106 1107 ~FoldOffsetRAII() { Info.EvalMode = OldMode; } 1108 }; 1109 1110 /// RAII object used to optionally suppress diagnostics and side-effects from 1111 /// a speculative evaluation. 1112 class SpeculativeEvaluationRAII { 1113 EvalInfo *Info = nullptr; 1114 Expr::EvalStatus OldStatus; 1115 bool OldIsSpeculativelyEvaluating; 1116 1117 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1118 Info = Other.Info; 1119 OldStatus = Other.OldStatus; 1120 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating; 1121 Other.Info = nullptr; 1122 } 1123 1124 void maybeRestoreState() { 1125 if (!Info) 1126 return; 1127 1128 Info->EvalStatus = OldStatus; 1129 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating; 1130 } 1131 1132 public: 1133 SpeculativeEvaluationRAII() = default; 1134 1135 SpeculativeEvaluationRAII( 1136 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1137 : Info(&Info), OldStatus(Info.EvalStatus), 1138 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) { 1139 Info.EvalStatus.Diag = NewDiag; 1140 Info.IsSpeculativelyEvaluating = true; 1141 } 1142 1143 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1144 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1145 moveFromAndCancel(std::move(Other)); 1146 } 1147 1148 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1149 maybeRestoreState(); 1150 moveFromAndCancel(std::move(Other)); 1151 return *this; 1152 } 1153 1154 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1155 }; 1156 1157 /// RAII object wrapping a full-expression or block scope, and handling 1158 /// the ending of the lifetime of temporaries created within it. 1159 template<bool IsFullExpression> 1160 class ScopeRAII { 1161 EvalInfo &Info; 1162 unsigned OldStackSize; 1163 public: 1164 ScopeRAII(EvalInfo &Info) 1165 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1166 // Push a new temporary version. This is needed to distinguish between 1167 // temporaries created in different iterations of a loop. 1168 Info.CurrentCall->pushTempVersion(); 1169 } 1170 ~ScopeRAII() { 1171 // Body moved to a static method to encourage the compiler to inline away 1172 // instances of this class. 1173 cleanup(Info, OldStackSize); 1174 Info.CurrentCall->popTempVersion(); 1175 } 1176 private: 1177 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 1178 unsigned NewEnd = OldStackSize; 1179 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 1180 I != N; ++I) { 1181 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 1182 // Full-expression cleanup of a lifetime-extended temporary: nothing 1183 // to do, just move this cleanup to the right place in the stack. 1184 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 1185 ++NewEnd; 1186 } else { 1187 // End the lifetime of the object. 1188 Info.CleanupStack[I].endLifetime(); 1189 } 1190 } 1191 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 1192 Info.CleanupStack.end()); 1193 } 1194 }; 1195 typedef ScopeRAII<false> BlockScopeRAII; 1196 typedef ScopeRAII<true> FullExpressionRAII; 1197 } 1198 1199 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1200 CheckSubobjectKind CSK) { 1201 if (Invalid) 1202 return false; 1203 if (isOnePastTheEnd()) { 1204 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1205 << CSK; 1206 setInvalid(); 1207 return false; 1208 } 1209 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1210 // must actually be at least one array element; even a VLA cannot have a 1211 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1212 return true; 1213 } 1214 1215 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1216 const Expr *E) { 1217 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1218 // Do not set the designator as invalid: we can represent this situation, 1219 // and correct handling of __builtin_object_size requires us to do so. 1220 } 1221 1222 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1223 const Expr *E, 1224 const APSInt &N) { 1225 // If we're complaining, we must be able to statically determine the size of 1226 // the most derived array. 1227 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1228 Info.CCEDiag(E, diag::note_constexpr_array_index) 1229 << N << /*array*/ 0 1230 << static_cast<unsigned>(getMostDerivedArraySize()); 1231 else 1232 Info.CCEDiag(E, diag::note_constexpr_array_index) 1233 << N << /*non-array*/ 1; 1234 setInvalid(); 1235 } 1236 1237 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1238 const FunctionDecl *Callee, const LValue *This, 1239 APValue *Arguments) 1240 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1241 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1242 Info.CurrentCall = this; 1243 ++Info.CallStackDepth; 1244 } 1245 1246 CallStackFrame::~CallStackFrame() { 1247 assert(Info.CurrentCall == this && "calls retired out of order"); 1248 --Info.CallStackDepth; 1249 Info.CurrentCall = Caller; 1250 } 1251 1252 APValue &CallStackFrame::createTemporary(const void *Key, 1253 bool IsLifetimeExtended) { 1254 unsigned Version = Info.CurrentCall->getTempVersion(); 1255 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1256 assert(Result.isUninit() && "temporary created multiple times"); 1257 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 1258 return Result; 1259 } 1260 1261 static void describeCall(CallStackFrame *Frame, raw_ostream &Out); 1262 1263 void EvalInfo::addCallStack(unsigned Limit) { 1264 // Determine which calls to skip, if any. 1265 unsigned ActiveCalls = CallStackDepth - 1; 1266 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 1267 if (Limit && Limit < ActiveCalls) { 1268 SkipStart = Limit / 2 + Limit % 2; 1269 SkipEnd = ActiveCalls - Limit / 2; 1270 } 1271 1272 // Walk the call stack and add the diagnostics. 1273 unsigned CallIdx = 0; 1274 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 1275 Frame = Frame->Caller, ++CallIdx) { 1276 // Skip this call? 1277 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 1278 if (CallIdx == SkipStart) { 1279 // Note that we're skipping calls. 1280 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 1281 << unsigned(ActiveCalls - Limit); 1282 } 1283 continue; 1284 } 1285 1286 // Use a different note for an inheriting constructor, because from the 1287 // user's perspective it's not really a function at all. 1288 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) { 1289 if (CD->isInheritingConstructor()) { 1290 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here) 1291 << CD->getParent(); 1292 continue; 1293 } 1294 } 1295 1296 SmallVector<char, 128> Buffer; 1297 llvm::raw_svector_ostream Out(Buffer); 1298 describeCall(Frame, Out); 1299 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 1300 } 1301 } 1302 1303 namespace { 1304 struct ComplexValue { 1305 private: 1306 bool IsInt; 1307 1308 public: 1309 APSInt IntReal, IntImag; 1310 APFloat FloatReal, FloatImag; 1311 1312 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1313 1314 void makeComplexFloat() { IsInt = false; } 1315 bool isComplexFloat() const { return !IsInt; } 1316 APFloat &getComplexFloatReal() { return FloatReal; } 1317 APFloat &getComplexFloatImag() { return FloatImag; } 1318 1319 void makeComplexInt() { IsInt = true; } 1320 bool isComplexInt() const { return IsInt; } 1321 APSInt &getComplexIntReal() { return IntReal; } 1322 APSInt &getComplexIntImag() { return IntImag; } 1323 1324 void moveInto(APValue &v) const { 1325 if (isComplexFloat()) 1326 v = APValue(FloatReal, FloatImag); 1327 else 1328 v = APValue(IntReal, IntImag); 1329 } 1330 void setFrom(const APValue &v) { 1331 assert(v.isComplexFloat() || v.isComplexInt()); 1332 if (v.isComplexFloat()) { 1333 makeComplexFloat(); 1334 FloatReal = v.getComplexFloatReal(); 1335 FloatImag = v.getComplexFloatImag(); 1336 } else { 1337 makeComplexInt(); 1338 IntReal = v.getComplexIntReal(); 1339 IntImag = v.getComplexIntImag(); 1340 } 1341 } 1342 }; 1343 1344 struct LValue { 1345 APValue::LValueBase Base; 1346 CharUnits Offset; 1347 SubobjectDesignator Designator; 1348 bool IsNullPtr : 1; 1349 bool InvalidBase : 1; 1350 1351 const APValue::LValueBase getLValueBase() const { return Base; } 1352 CharUnits &getLValueOffset() { return Offset; } 1353 const CharUnits &getLValueOffset() const { return Offset; } 1354 SubobjectDesignator &getLValueDesignator() { return Designator; } 1355 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1356 bool isNullPointer() const { return IsNullPtr;} 1357 1358 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1359 unsigned getLValueVersion() const { return Base.getVersion(); } 1360 1361 void moveInto(APValue &V) const { 1362 if (Designator.Invalid) 1363 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1364 else { 1365 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1366 V = APValue(Base, Offset, Designator.Entries, 1367 Designator.IsOnePastTheEnd, IsNullPtr); 1368 } 1369 } 1370 void setFrom(ASTContext &Ctx, const APValue &V) { 1371 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1372 Base = V.getLValueBase(); 1373 Offset = V.getLValueOffset(); 1374 InvalidBase = false; 1375 Designator = SubobjectDesignator(Ctx, V); 1376 IsNullPtr = V.isNullPointer(); 1377 } 1378 1379 void set(APValue::LValueBase B, bool BInvalid = false) { 1380 #ifndef NDEBUG 1381 // We only allow a few types of invalid bases. Enforce that here. 1382 if (BInvalid) { 1383 const auto *E = B.get<const Expr *>(); 1384 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1385 "Unexpected type of invalid base"); 1386 } 1387 #endif 1388 1389 Base = B; 1390 Offset = CharUnits::fromQuantity(0); 1391 InvalidBase = BInvalid; 1392 Designator = SubobjectDesignator(getType(B)); 1393 IsNullPtr = false; 1394 } 1395 1396 void setNull(QualType PointerTy, uint64_t TargetVal) { 1397 Base = (Expr *)nullptr; 1398 Offset = CharUnits::fromQuantity(TargetVal); 1399 InvalidBase = false; 1400 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1401 IsNullPtr = true; 1402 } 1403 1404 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1405 set(B, true); 1406 } 1407 1408 // Check that this LValue is not based on a null pointer. If it is, produce 1409 // a diagnostic and mark the designator as invalid. 1410 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1411 CheckSubobjectKind CSK) { 1412 if (Designator.Invalid) 1413 return false; 1414 if (IsNullPtr) { 1415 Info.CCEDiag(E, diag::note_constexpr_null_subobject) 1416 << CSK; 1417 Designator.setInvalid(); 1418 return false; 1419 } 1420 return true; 1421 } 1422 1423 // Check this LValue refers to an object. If not, set the designator to be 1424 // invalid and emit a diagnostic. 1425 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1426 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1427 Designator.checkSubobject(Info, E, CSK); 1428 } 1429 1430 void addDecl(EvalInfo &Info, const Expr *E, 1431 const Decl *D, bool Virtual = false) { 1432 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1433 Designator.addDeclUnchecked(D, Virtual); 1434 } 1435 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1436 if (!Designator.Entries.empty()) { 1437 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1438 Designator.setInvalid(); 1439 return; 1440 } 1441 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1442 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1443 Designator.FirstEntryIsAnUnsizedArray = true; 1444 Designator.addUnsizedArrayUnchecked(ElemTy); 1445 } 1446 } 1447 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1448 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1449 Designator.addArrayUnchecked(CAT); 1450 } 1451 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1452 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1453 Designator.addComplexUnchecked(EltTy, Imag); 1454 } 1455 void clearIsNullPointer() { 1456 IsNullPtr = false; 1457 } 1458 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1459 const APSInt &Index, CharUnits ElementSize) { 1460 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1461 // but we're not required to diagnose it and it's valid in C++.) 1462 if (!Index) 1463 return; 1464 1465 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1466 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1467 // offsets. 1468 uint64_t Offset64 = Offset.getQuantity(); 1469 uint64_t ElemSize64 = ElementSize.getQuantity(); 1470 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1471 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1472 1473 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1474 Designator.adjustIndex(Info, E, Index); 1475 clearIsNullPointer(); 1476 } 1477 void adjustOffset(CharUnits N) { 1478 Offset += N; 1479 if (N.getQuantity()) 1480 clearIsNullPointer(); 1481 } 1482 }; 1483 1484 struct MemberPtr { 1485 MemberPtr() {} 1486 explicit MemberPtr(const ValueDecl *Decl) : 1487 DeclAndIsDerivedMember(Decl, false), Path() {} 1488 1489 /// The member or (direct or indirect) field referred to by this member 1490 /// pointer, or 0 if this is a null member pointer. 1491 const ValueDecl *getDecl() const { 1492 return DeclAndIsDerivedMember.getPointer(); 1493 } 1494 /// Is this actually a member of some type derived from the relevant class? 1495 bool isDerivedMember() const { 1496 return DeclAndIsDerivedMember.getInt(); 1497 } 1498 /// Get the class which the declaration actually lives in. 1499 const CXXRecordDecl *getContainingRecord() const { 1500 return cast<CXXRecordDecl>( 1501 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1502 } 1503 1504 void moveInto(APValue &V) const { 1505 V = APValue(getDecl(), isDerivedMember(), Path); 1506 } 1507 void setFrom(const APValue &V) { 1508 assert(V.isMemberPointer()); 1509 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1510 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1511 Path.clear(); 1512 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1513 Path.insert(Path.end(), P.begin(), P.end()); 1514 } 1515 1516 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1517 /// whether the member is a member of some class derived from the class type 1518 /// of the member pointer. 1519 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1520 /// Path - The path of base/derived classes from the member declaration's 1521 /// class (exclusive) to the class type of the member pointer (inclusive). 1522 SmallVector<const CXXRecordDecl*, 4> Path; 1523 1524 /// Perform a cast towards the class of the Decl (either up or down the 1525 /// hierarchy). 1526 bool castBack(const CXXRecordDecl *Class) { 1527 assert(!Path.empty()); 1528 const CXXRecordDecl *Expected; 1529 if (Path.size() >= 2) 1530 Expected = Path[Path.size() - 2]; 1531 else 1532 Expected = getContainingRecord(); 1533 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1534 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1535 // if B does not contain the original member and is not a base or 1536 // derived class of the class containing the original member, the result 1537 // of the cast is undefined. 1538 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1539 // (D::*). We consider that to be a language defect. 1540 return false; 1541 } 1542 Path.pop_back(); 1543 return true; 1544 } 1545 /// Perform a base-to-derived member pointer cast. 1546 bool castToDerived(const CXXRecordDecl *Derived) { 1547 if (!getDecl()) 1548 return true; 1549 if (!isDerivedMember()) { 1550 Path.push_back(Derived); 1551 return true; 1552 } 1553 if (!castBack(Derived)) 1554 return false; 1555 if (Path.empty()) 1556 DeclAndIsDerivedMember.setInt(false); 1557 return true; 1558 } 1559 /// Perform a derived-to-base member pointer cast. 1560 bool castToBase(const CXXRecordDecl *Base) { 1561 if (!getDecl()) 1562 return true; 1563 if (Path.empty()) 1564 DeclAndIsDerivedMember.setInt(true); 1565 if (isDerivedMember()) { 1566 Path.push_back(Base); 1567 return true; 1568 } 1569 return castBack(Base); 1570 } 1571 }; 1572 1573 /// Compare two member pointers, which are assumed to be of the same type. 1574 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1575 if (!LHS.getDecl() || !RHS.getDecl()) 1576 return !LHS.getDecl() && !RHS.getDecl(); 1577 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1578 return false; 1579 return LHS.Path == RHS.Path; 1580 } 1581 } 1582 1583 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1584 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1585 const LValue &This, const Expr *E, 1586 bool AllowNonLiteralTypes = false); 1587 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1588 bool InvalidBaseOK = false); 1589 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1590 bool InvalidBaseOK = false); 1591 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1592 EvalInfo &Info); 1593 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1594 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1595 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1596 EvalInfo &Info); 1597 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1598 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1599 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1600 EvalInfo &Info); 1601 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1602 1603 //===----------------------------------------------------------------------===// 1604 // Misc utilities 1605 //===----------------------------------------------------------------------===// 1606 1607 /// A helper function to create a temporary and set an LValue. 1608 template <class KeyTy> 1609 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended, 1610 LValue &LV, CallStackFrame &Frame) { 1611 LV.set({Key, Frame.Info.CurrentCall->Index, 1612 Frame.Info.CurrentCall->getTempVersion()}); 1613 return Frame.createTemporary(Key, IsLifetimeExtended); 1614 } 1615 1616 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1617 /// preserving its value (by extending by up to one bit as needed). 1618 static void negateAsSigned(APSInt &Int) { 1619 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1620 Int = Int.extend(Int.getBitWidth() + 1); 1621 Int.setIsSigned(true); 1622 } 1623 Int = -Int; 1624 } 1625 1626 /// Produce a string describing the given constexpr call. 1627 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) { 1628 unsigned ArgIndex = 0; 1629 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 1630 !isa<CXXConstructorDecl>(Frame->Callee) && 1631 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 1632 1633 if (!IsMemberCall) 1634 Out << *Frame->Callee << '('; 1635 1636 if (Frame->This && IsMemberCall) { 1637 APValue Val; 1638 Frame->This->moveInto(Val); 1639 Val.printPretty(Out, Frame->Info.Ctx, 1640 Frame->This->Designator.MostDerivedType); 1641 // FIXME: Add parens around Val if needed. 1642 Out << "->" << *Frame->Callee << '('; 1643 IsMemberCall = false; 1644 } 1645 1646 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 1647 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 1648 if (ArgIndex > (unsigned)IsMemberCall) 1649 Out << ", "; 1650 1651 const ParmVarDecl *Param = *I; 1652 const APValue &Arg = Frame->Arguments[ArgIndex]; 1653 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 1654 1655 if (ArgIndex == 0 && IsMemberCall) 1656 Out << "->" << *Frame->Callee << '('; 1657 } 1658 1659 Out << ')'; 1660 } 1661 1662 /// Evaluate an expression to see if it had side-effects, and discard its 1663 /// result. 1664 /// \return \c true if the caller should keep evaluating. 1665 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1666 APValue Scratch; 1667 if (!Evaluate(Scratch, Info, E)) 1668 // We don't need the value, but we might have skipped a side effect here. 1669 return Info.noteSideEffect(); 1670 return true; 1671 } 1672 1673 /// Should this call expression be treated as a string literal? 1674 static bool IsStringLiteralCall(const CallExpr *E) { 1675 unsigned Builtin = E->getBuiltinCallee(); 1676 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1677 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1678 } 1679 1680 static bool IsGlobalLValue(APValue::LValueBase B) { 1681 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1682 // constant expression of pointer type that evaluates to... 1683 1684 // ... a null pointer value, or a prvalue core constant expression of type 1685 // std::nullptr_t. 1686 if (!B) return true; 1687 1688 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1689 // ... the address of an object with static storage duration, 1690 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1691 return VD->hasGlobalStorage(); 1692 // ... the address of a function, 1693 return isa<FunctionDecl>(D); 1694 } 1695 1696 const Expr *E = B.get<const Expr*>(); 1697 switch (E->getStmtClass()) { 1698 default: 1699 return false; 1700 case Expr::CompoundLiteralExprClass: { 1701 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1702 return CLE->isFileScope() && CLE->isLValue(); 1703 } 1704 case Expr::MaterializeTemporaryExprClass: 1705 // A materialized temporary might have been lifetime-extended to static 1706 // storage duration. 1707 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1708 // A string literal has static storage duration. 1709 case Expr::StringLiteralClass: 1710 case Expr::PredefinedExprClass: 1711 case Expr::ObjCStringLiteralClass: 1712 case Expr::ObjCEncodeExprClass: 1713 case Expr::CXXTypeidExprClass: 1714 case Expr::CXXUuidofExprClass: 1715 return true; 1716 case Expr::CallExprClass: 1717 return IsStringLiteralCall(cast<CallExpr>(E)); 1718 // For GCC compatibility, &&label has static storage duration. 1719 case Expr::AddrLabelExprClass: 1720 return true; 1721 // A Block literal expression may be used as the initialization value for 1722 // Block variables at global or local static scope. 1723 case Expr::BlockExprClass: 1724 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1725 case Expr::ImplicitValueInitExprClass: 1726 // FIXME: 1727 // We can never form an lvalue with an implicit value initialization as its 1728 // base through expression evaluation, so these only appear in one case: the 1729 // implicit variable declaration we invent when checking whether a constexpr 1730 // constructor can produce a constant expression. We must assume that such 1731 // an expression might be a global lvalue. 1732 return true; 1733 } 1734 } 1735 1736 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1737 return LVal.Base.dyn_cast<const ValueDecl*>(); 1738 } 1739 1740 static bool IsLiteralLValue(const LValue &Value) { 1741 if (Value.getLValueCallIndex()) 1742 return false; 1743 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1744 return E && !isa<MaterializeTemporaryExpr>(E); 1745 } 1746 1747 static bool IsWeakLValue(const LValue &Value) { 1748 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1749 return Decl && Decl->isWeak(); 1750 } 1751 1752 static bool isZeroSized(const LValue &Value) { 1753 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1754 if (Decl && isa<VarDecl>(Decl)) { 1755 QualType Ty = Decl->getType(); 1756 if (Ty->isArrayType()) 1757 return Ty->isIncompleteType() || 1758 Decl->getASTContext().getTypeSize(Ty) == 0; 1759 } 1760 return false; 1761 } 1762 1763 static bool HasSameBase(const LValue &A, const LValue &B) { 1764 if (!A.getLValueBase()) 1765 return !B.getLValueBase(); 1766 if (!B.getLValueBase()) 1767 return false; 1768 1769 if (A.getLValueBase().getOpaqueValue() != 1770 B.getLValueBase().getOpaqueValue()) { 1771 const Decl *ADecl = GetLValueBaseDecl(A); 1772 if (!ADecl) 1773 return false; 1774 const Decl *BDecl = GetLValueBaseDecl(B); 1775 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1776 return false; 1777 } 1778 1779 return IsGlobalLValue(A.getLValueBase()) || 1780 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1781 A.getLValueVersion() == B.getLValueVersion()); 1782 } 1783 1784 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1785 assert(Base && "no location for a null lvalue"); 1786 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1787 if (VD) 1788 Info.Note(VD->getLocation(), diag::note_declared_at); 1789 else 1790 Info.Note(Base.get<const Expr*>()->getExprLoc(), 1791 diag::note_constexpr_temporary_here); 1792 } 1793 1794 /// Check that this reference or pointer core constant expression is a valid 1795 /// value for an address or reference constant expression. Return true if we 1796 /// can fold this expression, whether or not it's a constant expression. 1797 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1798 QualType Type, const LValue &LVal, 1799 Expr::ConstExprUsage Usage) { 1800 bool IsReferenceType = Type->isReferenceType(); 1801 1802 APValue::LValueBase Base = LVal.getLValueBase(); 1803 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1804 1805 // Check that the object is a global. Note that the fake 'this' object we 1806 // manufacture when checking potential constant expressions is conservatively 1807 // assumed to be global here. 1808 if (!IsGlobalLValue(Base)) { 1809 if (Info.getLangOpts().CPlusPlus11) { 1810 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1811 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1812 << IsReferenceType << !Designator.Entries.empty() 1813 << !!VD << VD; 1814 NoteLValueLocation(Info, Base); 1815 } else { 1816 Info.FFDiag(Loc); 1817 } 1818 // Don't allow references to temporaries to escape. 1819 return false; 1820 } 1821 assert((Info.checkingPotentialConstantExpression() || 1822 LVal.getLValueCallIndex() == 0) && 1823 "have call index for global lvalue"); 1824 1825 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1826 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1827 // Check if this is a thread-local variable. 1828 if (Var->getTLSKind()) 1829 return false; 1830 1831 // A dllimport variable never acts like a constant. 1832 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 1833 return false; 1834 } 1835 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1836 // __declspec(dllimport) must be handled very carefully: 1837 // We must never initialize an expression with the thunk in C++. 1838 // Doing otherwise would allow the same id-expression to yield 1839 // different addresses for the same function in different translation 1840 // units. However, this means that we must dynamically initialize the 1841 // expression with the contents of the import address table at runtime. 1842 // 1843 // The C language has no notion of ODR; furthermore, it has no notion of 1844 // dynamic initialization. This means that we are permitted to 1845 // perform initialization with the address of the thunk. 1846 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 1847 FD->hasAttr<DLLImportAttr>()) 1848 return false; 1849 } 1850 } 1851 1852 // Allow address constant expressions to be past-the-end pointers. This is 1853 // an extension: the standard requires them to point to an object. 1854 if (!IsReferenceType) 1855 return true; 1856 1857 // A reference constant expression must refer to an object. 1858 if (!Base) { 1859 // FIXME: diagnostic 1860 Info.CCEDiag(Loc); 1861 return true; 1862 } 1863 1864 // Does this refer one past the end of some object? 1865 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1866 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1867 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1868 << !Designator.Entries.empty() << !!VD << VD; 1869 NoteLValueLocation(Info, Base); 1870 } 1871 1872 return true; 1873 } 1874 1875 /// Member pointers are constant expressions unless they point to a 1876 /// non-virtual dllimport member function. 1877 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 1878 SourceLocation Loc, 1879 QualType Type, 1880 const APValue &Value, 1881 Expr::ConstExprUsage Usage) { 1882 const ValueDecl *Member = Value.getMemberPointerDecl(); 1883 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 1884 if (!FD) 1885 return true; 1886 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 1887 !FD->hasAttr<DLLImportAttr>(); 1888 } 1889 1890 /// Check that this core constant expression is of literal type, and if not, 1891 /// produce an appropriate diagnostic. 1892 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 1893 const LValue *This = nullptr) { 1894 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 1895 return true; 1896 1897 // C++1y: A constant initializer for an object o [...] may also invoke 1898 // constexpr constructors for o and its subobjects even if those objects 1899 // are of non-literal class types. 1900 // 1901 // C++11 missed this detail for aggregates, so classes like this: 1902 // struct foo_t { union { int i; volatile int j; } u; }; 1903 // are not (obviously) initializable like so: 1904 // __attribute__((__require_constant_initialization__)) 1905 // static const foo_t x = {{0}}; 1906 // because "i" is a subobject with non-literal initialization (due to the 1907 // volatile member of the union). See: 1908 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 1909 // Therefore, we use the C++1y behavior. 1910 if (This && Info.EvaluatingDecl == This->getLValueBase()) 1911 return true; 1912 1913 // Prvalue constant expressions must be of literal types. 1914 if (Info.getLangOpts().CPlusPlus11) 1915 Info.FFDiag(E, diag::note_constexpr_nonliteral) 1916 << E->getType(); 1917 else 1918 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1919 return false; 1920 } 1921 1922 /// Check that this core constant expression value is a valid value for a 1923 /// constant expression. If not, report an appropriate diagnostic. Does not 1924 /// check that the expression is of literal type. 1925 static bool 1926 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 1927 const APValue &Value, 1928 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 1929 if (Value.isUninit()) { 1930 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 1931 << true << Type; 1932 return false; 1933 } 1934 1935 // We allow _Atomic(T) to be initialized from anything that T can be 1936 // initialized from. 1937 if (const AtomicType *AT = Type->getAs<AtomicType>()) 1938 Type = AT->getValueType(); 1939 1940 // Core issue 1454: For a literal constant expression of array or class type, 1941 // each subobject of its value shall have been initialized by a constant 1942 // expression. 1943 if (Value.isArray()) { 1944 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 1945 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 1946 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 1947 Value.getArrayInitializedElt(I), Usage)) 1948 return false; 1949 } 1950 if (!Value.hasArrayFiller()) 1951 return true; 1952 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(), 1953 Usage); 1954 } 1955 if (Value.isUnion() && Value.getUnionField()) { 1956 return CheckConstantExpression(Info, DiagLoc, 1957 Value.getUnionField()->getType(), 1958 Value.getUnionValue(), Usage); 1959 } 1960 if (Value.isStruct()) { 1961 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 1962 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 1963 unsigned BaseIndex = 0; 1964 for (const CXXBaseSpecifier &BS : CD->bases()) { 1965 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(), 1966 Value.getStructBase(BaseIndex), Usage)) 1967 return false; 1968 ++BaseIndex; 1969 } 1970 } 1971 for (const auto *I : RD->fields()) { 1972 if (I->isUnnamedBitfield()) 1973 continue; 1974 1975 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1976 Value.getStructField(I->getFieldIndex()), 1977 Usage)) 1978 return false; 1979 } 1980 } 1981 1982 if (Value.isLValue()) { 1983 LValue LVal; 1984 LVal.setFrom(Info.Ctx, Value); 1985 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage); 1986 } 1987 1988 if (Value.isMemberPointer()) 1989 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 1990 1991 // Everything else is fine. 1992 return true; 1993 } 1994 1995 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 1996 // A null base expression indicates a null pointer. These are always 1997 // evaluatable, and they are false unless the offset is zero. 1998 if (!Value.getLValueBase()) { 1999 Result = !Value.getLValueOffset().isZero(); 2000 return true; 2001 } 2002 2003 // We have a non-null base. These are generally known to be true, but if it's 2004 // a weak declaration it can be null at runtime. 2005 Result = true; 2006 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2007 return !Decl || !Decl->isWeak(); 2008 } 2009 2010 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2011 switch (Val.getKind()) { 2012 case APValue::Uninitialized: 2013 return false; 2014 case APValue::Int: 2015 Result = Val.getInt().getBoolValue(); 2016 return true; 2017 case APValue::Float: 2018 Result = !Val.getFloat().isZero(); 2019 return true; 2020 case APValue::ComplexInt: 2021 Result = Val.getComplexIntReal().getBoolValue() || 2022 Val.getComplexIntImag().getBoolValue(); 2023 return true; 2024 case APValue::ComplexFloat: 2025 Result = !Val.getComplexFloatReal().isZero() || 2026 !Val.getComplexFloatImag().isZero(); 2027 return true; 2028 case APValue::LValue: 2029 return EvalPointerValueAsBool(Val, Result); 2030 case APValue::MemberPointer: 2031 Result = Val.getMemberPointerDecl(); 2032 return true; 2033 case APValue::Vector: 2034 case APValue::Array: 2035 case APValue::Struct: 2036 case APValue::Union: 2037 case APValue::AddrLabelDiff: 2038 return false; 2039 } 2040 2041 llvm_unreachable("unknown APValue kind"); 2042 } 2043 2044 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2045 EvalInfo &Info) { 2046 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2047 APValue Val; 2048 if (!Evaluate(Val, Info, E)) 2049 return false; 2050 return HandleConversionToBool(Val, Result); 2051 } 2052 2053 template<typename T> 2054 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2055 const T &SrcValue, QualType DestType) { 2056 Info.CCEDiag(E, diag::note_constexpr_overflow) 2057 << SrcValue << DestType; 2058 return Info.noteUndefinedBehavior(); 2059 } 2060 2061 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2062 QualType SrcType, const APFloat &Value, 2063 QualType DestType, APSInt &Result) { 2064 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2065 // Determine whether we are converting to unsigned or signed. 2066 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2067 2068 Result = APSInt(DestWidth, !DestSigned); 2069 bool ignored; 2070 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2071 & APFloat::opInvalidOp) 2072 return HandleOverflow(Info, E, Value, DestType); 2073 return true; 2074 } 2075 2076 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2077 QualType SrcType, QualType DestType, 2078 APFloat &Result) { 2079 APFloat Value = Result; 2080 bool ignored; 2081 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2082 APFloat::rmNearestTiesToEven, &ignored) 2083 & APFloat::opOverflow) 2084 return HandleOverflow(Info, E, Value, DestType); 2085 return true; 2086 } 2087 2088 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2089 QualType DestType, QualType SrcType, 2090 const APSInt &Value) { 2091 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2092 APSInt Result = Value; 2093 // Figure out if this is a truncate, extend or noop cast. 2094 // If the input is signed, do a sign extend, noop, or truncate. 2095 Result = Result.extOrTrunc(DestWidth); 2096 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2097 return Result; 2098 } 2099 2100 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2101 QualType SrcType, const APSInt &Value, 2102 QualType DestType, APFloat &Result) { 2103 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2104 if (Result.convertFromAPInt(Value, Value.isSigned(), 2105 APFloat::rmNearestTiesToEven) 2106 & APFloat::opOverflow) 2107 return HandleOverflow(Info, E, Value, DestType); 2108 return true; 2109 } 2110 2111 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2112 APValue &Value, const FieldDecl *FD) { 2113 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2114 2115 if (!Value.isInt()) { 2116 // Trying to store a pointer-cast-to-integer into a bitfield. 2117 // FIXME: In this case, we should provide the diagnostic for casting 2118 // a pointer to an integer. 2119 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2120 Info.FFDiag(E); 2121 return false; 2122 } 2123 2124 APSInt &Int = Value.getInt(); 2125 unsigned OldBitWidth = Int.getBitWidth(); 2126 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2127 if (NewBitWidth < OldBitWidth) 2128 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2129 return true; 2130 } 2131 2132 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2133 llvm::APInt &Res) { 2134 APValue SVal; 2135 if (!Evaluate(SVal, Info, E)) 2136 return false; 2137 if (SVal.isInt()) { 2138 Res = SVal.getInt(); 2139 return true; 2140 } 2141 if (SVal.isFloat()) { 2142 Res = SVal.getFloat().bitcastToAPInt(); 2143 return true; 2144 } 2145 if (SVal.isVector()) { 2146 QualType VecTy = E->getType(); 2147 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2148 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2149 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2150 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2151 Res = llvm::APInt::getNullValue(VecSize); 2152 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2153 APValue &Elt = SVal.getVectorElt(i); 2154 llvm::APInt EltAsInt; 2155 if (Elt.isInt()) { 2156 EltAsInt = Elt.getInt(); 2157 } else if (Elt.isFloat()) { 2158 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2159 } else { 2160 // Don't try to handle vectors of anything other than int or float 2161 // (not sure if it's possible to hit this case). 2162 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2163 return false; 2164 } 2165 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2166 if (BigEndian) 2167 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2168 else 2169 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2170 } 2171 return true; 2172 } 2173 // Give up if the input isn't an int, float, or vector. For example, we 2174 // reject "(v4i16)(intptr_t)&a". 2175 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2176 return false; 2177 } 2178 2179 /// Perform the given integer operation, which is known to need at most BitWidth 2180 /// bits, and check for overflow in the original type (if that type was not an 2181 /// unsigned type). 2182 template<typename Operation> 2183 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2184 const APSInt &LHS, const APSInt &RHS, 2185 unsigned BitWidth, Operation Op, 2186 APSInt &Result) { 2187 if (LHS.isUnsigned()) { 2188 Result = Op(LHS, RHS); 2189 return true; 2190 } 2191 2192 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2193 Result = Value.trunc(LHS.getBitWidth()); 2194 if (Result.extend(BitWidth) != Value) { 2195 if (Info.checkingForOverflow()) 2196 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2197 diag::warn_integer_constant_overflow) 2198 << Result.toString(10) << E->getType(); 2199 else 2200 return HandleOverflow(Info, E, Value, E->getType()); 2201 } 2202 return true; 2203 } 2204 2205 /// Perform the given binary integer operation. 2206 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2207 BinaryOperatorKind Opcode, APSInt RHS, 2208 APSInt &Result) { 2209 switch (Opcode) { 2210 default: 2211 Info.FFDiag(E); 2212 return false; 2213 case BO_Mul: 2214 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2215 std::multiplies<APSInt>(), Result); 2216 case BO_Add: 2217 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2218 std::plus<APSInt>(), Result); 2219 case BO_Sub: 2220 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2221 std::minus<APSInt>(), Result); 2222 case BO_And: Result = LHS & RHS; return true; 2223 case BO_Xor: Result = LHS ^ RHS; return true; 2224 case BO_Or: Result = LHS | RHS; return true; 2225 case BO_Div: 2226 case BO_Rem: 2227 if (RHS == 0) { 2228 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2229 return false; 2230 } 2231 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2232 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2233 // this operation and gives the two's complement result. 2234 if (RHS.isNegative() && RHS.isAllOnesValue() && 2235 LHS.isSigned() && LHS.isMinSignedValue()) 2236 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2237 E->getType()); 2238 return true; 2239 case BO_Shl: { 2240 if (Info.getLangOpts().OpenCL) 2241 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2242 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2243 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2244 RHS.isUnsigned()); 2245 else if (RHS.isSigned() && RHS.isNegative()) { 2246 // During constant-folding, a negative shift is an opposite shift. Such 2247 // a shift is not a constant expression. 2248 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2249 RHS = -RHS; 2250 goto shift_right; 2251 } 2252 shift_left: 2253 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2254 // the shifted type. 2255 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2256 if (SA != RHS) { 2257 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2258 << RHS << E->getType() << LHS.getBitWidth(); 2259 } else if (LHS.isSigned()) { 2260 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2261 // operand, and must not overflow the corresponding unsigned type. 2262 if (LHS.isNegative()) 2263 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2264 else if (LHS.countLeadingZeros() < SA) 2265 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2266 } 2267 Result = LHS << SA; 2268 return true; 2269 } 2270 case BO_Shr: { 2271 if (Info.getLangOpts().OpenCL) 2272 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2273 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2274 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2275 RHS.isUnsigned()); 2276 else if (RHS.isSigned() && RHS.isNegative()) { 2277 // During constant-folding, a negative shift is an opposite shift. Such a 2278 // shift is not a constant expression. 2279 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2280 RHS = -RHS; 2281 goto shift_left; 2282 } 2283 shift_right: 2284 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2285 // shifted type. 2286 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2287 if (SA != RHS) 2288 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2289 << RHS << E->getType() << LHS.getBitWidth(); 2290 Result = LHS >> SA; 2291 return true; 2292 } 2293 2294 case BO_LT: Result = LHS < RHS; return true; 2295 case BO_GT: Result = LHS > RHS; return true; 2296 case BO_LE: Result = LHS <= RHS; return true; 2297 case BO_GE: Result = LHS >= RHS; return true; 2298 case BO_EQ: Result = LHS == RHS; return true; 2299 case BO_NE: Result = LHS != RHS; return true; 2300 case BO_Cmp: 2301 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2302 } 2303 } 2304 2305 /// Perform the given binary floating-point operation, in-place, on LHS. 2306 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2307 APFloat &LHS, BinaryOperatorKind Opcode, 2308 const APFloat &RHS) { 2309 switch (Opcode) { 2310 default: 2311 Info.FFDiag(E); 2312 return false; 2313 case BO_Mul: 2314 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2315 break; 2316 case BO_Add: 2317 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2318 break; 2319 case BO_Sub: 2320 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2321 break; 2322 case BO_Div: 2323 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2324 break; 2325 } 2326 2327 if (LHS.isInfinity() || LHS.isNaN()) { 2328 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2329 return Info.noteUndefinedBehavior(); 2330 } 2331 return true; 2332 } 2333 2334 /// Cast an lvalue referring to a base subobject to a derived class, by 2335 /// truncating the lvalue's path to the given length. 2336 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2337 const RecordDecl *TruncatedType, 2338 unsigned TruncatedElements) { 2339 SubobjectDesignator &D = Result.Designator; 2340 2341 // Check we actually point to a derived class object. 2342 if (TruncatedElements == D.Entries.size()) 2343 return true; 2344 assert(TruncatedElements >= D.MostDerivedPathLength && 2345 "not casting to a derived class"); 2346 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2347 return false; 2348 2349 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2350 const RecordDecl *RD = TruncatedType; 2351 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2352 if (RD->isInvalidDecl()) return false; 2353 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2354 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2355 if (isVirtualBaseClass(D.Entries[I])) 2356 Result.Offset -= Layout.getVBaseClassOffset(Base); 2357 else 2358 Result.Offset -= Layout.getBaseClassOffset(Base); 2359 RD = Base; 2360 } 2361 D.Entries.resize(TruncatedElements); 2362 return true; 2363 } 2364 2365 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2366 const CXXRecordDecl *Derived, 2367 const CXXRecordDecl *Base, 2368 const ASTRecordLayout *RL = nullptr) { 2369 if (!RL) { 2370 if (Derived->isInvalidDecl()) return false; 2371 RL = &Info.Ctx.getASTRecordLayout(Derived); 2372 } 2373 2374 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2375 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2376 return true; 2377 } 2378 2379 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2380 const CXXRecordDecl *DerivedDecl, 2381 const CXXBaseSpecifier *Base) { 2382 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2383 2384 if (!Base->isVirtual()) 2385 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2386 2387 SubobjectDesignator &D = Obj.Designator; 2388 if (D.Invalid) 2389 return false; 2390 2391 // Extract most-derived object and corresponding type. 2392 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2393 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2394 return false; 2395 2396 // Find the virtual base class. 2397 if (DerivedDecl->isInvalidDecl()) return false; 2398 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2399 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2400 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2401 return true; 2402 } 2403 2404 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2405 QualType Type, LValue &Result) { 2406 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2407 PathE = E->path_end(); 2408 PathI != PathE; ++PathI) { 2409 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2410 *PathI)) 2411 return false; 2412 Type = (*PathI)->getType(); 2413 } 2414 return true; 2415 } 2416 2417 /// Update LVal to refer to the given field, which must be a member of the type 2418 /// currently described by LVal. 2419 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2420 const FieldDecl *FD, 2421 const ASTRecordLayout *RL = nullptr) { 2422 if (!RL) { 2423 if (FD->getParent()->isInvalidDecl()) return false; 2424 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2425 } 2426 2427 unsigned I = FD->getFieldIndex(); 2428 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2429 LVal.addDecl(Info, E, FD); 2430 return true; 2431 } 2432 2433 /// Update LVal to refer to the given indirect field. 2434 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2435 LValue &LVal, 2436 const IndirectFieldDecl *IFD) { 2437 for (const auto *C : IFD->chain()) 2438 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2439 return false; 2440 return true; 2441 } 2442 2443 /// Get the size of the given type in char units. 2444 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2445 QualType Type, CharUnits &Size) { 2446 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2447 // extension. 2448 if (Type->isVoidType() || Type->isFunctionType()) { 2449 Size = CharUnits::One(); 2450 return true; 2451 } 2452 2453 if (Type->isDependentType()) { 2454 Info.FFDiag(Loc); 2455 return false; 2456 } 2457 2458 if (!Type->isConstantSizeType()) { 2459 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2460 // FIXME: Better diagnostic. 2461 Info.FFDiag(Loc); 2462 return false; 2463 } 2464 2465 Size = Info.Ctx.getTypeSizeInChars(Type); 2466 return true; 2467 } 2468 2469 /// Update a pointer value to model pointer arithmetic. 2470 /// \param Info - Information about the ongoing evaluation. 2471 /// \param E - The expression being evaluated, for diagnostic purposes. 2472 /// \param LVal - The pointer value to be updated. 2473 /// \param EltTy - The pointee type represented by LVal. 2474 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2475 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2476 LValue &LVal, QualType EltTy, 2477 APSInt Adjustment) { 2478 CharUnits SizeOfPointee; 2479 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2480 return false; 2481 2482 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2483 return true; 2484 } 2485 2486 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2487 LValue &LVal, QualType EltTy, 2488 int64_t Adjustment) { 2489 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2490 APSInt::get(Adjustment)); 2491 } 2492 2493 /// Update an lvalue to refer to a component of a complex number. 2494 /// \param Info - Information about the ongoing evaluation. 2495 /// \param LVal - The lvalue to be updated. 2496 /// \param EltTy - The complex number's component type. 2497 /// \param Imag - False for the real component, true for the imaginary. 2498 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2499 LValue &LVal, QualType EltTy, 2500 bool Imag) { 2501 if (Imag) { 2502 CharUnits SizeOfComponent; 2503 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2504 return false; 2505 LVal.Offset += SizeOfComponent; 2506 } 2507 LVal.addComplex(Info, E, EltTy, Imag); 2508 return true; 2509 } 2510 2511 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 2512 QualType Type, const LValue &LVal, 2513 APValue &RVal); 2514 2515 /// Try to evaluate the initializer for a variable declaration. 2516 /// 2517 /// \param Info Information about the ongoing evaluation. 2518 /// \param E An expression to be used when printing diagnostics. 2519 /// \param VD The variable whose initializer should be obtained. 2520 /// \param Frame The frame in which the variable was created. Must be null 2521 /// if this variable is not local to the evaluation. 2522 /// \param Result Filled in with a pointer to the value of the variable. 2523 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2524 const VarDecl *VD, CallStackFrame *Frame, 2525 APValue *&Result, const LValue *LVal) { 2526 2527 // If this is a parameter to an active constexpr function call, perform 2528 // argument substitution. 2529 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2530 // Assume arguments of a potential constant expression are unknown 2531 // constant expressions. 2532 if (Info.checkingPotentialConstantExpression()) 2533 return false; 2534 if (!Frame || !Frame->Arguments) { 2535 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2536 return false; 2537 } 2538 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2539 return true; 2540 } 2541 2542 // If this is a local variable, dig out its value. 2543 if (Frame) { 2544 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 2545 : Frame->getCurrentTemporary(VD); 2546 if (!Result) { 2547 // Assume variables referenced within a lambda's call operator that were 2548 // not declared within the call operator are captures and during checking 2549 // of a potential constant expression, assume they are unknown constant 2550 // expressions. 2551 assert(isLambdaCallOperator(Frame->Callee) && 2552 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2553 "missing value for local variable"); 2554 if (Info.checkingPotentialConstantExpression()) 2555 return false; 2556 // FIXME: implement capture evaluation during constant expr evaluation. 2557 Info.FFDiag(E->getBeginLoc(), 2558 diag::note_unimplemented_constexpr_lambda_feature_ast) 2559 << "captures not currently allowed"; 2560 return false; 2561 } 2562 return true; 2563 } 2564 2565 // Dig out the initializer, and use the declaration which it's attached to. 2566 const Expr *Init = VD->getAnyInitializer(VD); 2567 if (!Init || Init->isValueDependent()) { 2568 // If we're checking a potential constant expression, the variable could be 2569 // initialized later. 2570 if (!Info.checkingPotentialConstantExpression()) 2571 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2572 return false; 2573 } 2574 2575 // If we're currently evaluating the initializer of this declaration, use that 2576 // in-flight value. 2577 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2578 Result = Info.EvaluatingDeclValue; 2579 return true; 2580 } 2581 2582 // Never evaluate the initializer of a weak variable. We can't be sure that 2583 // this is the definition which will be used. 2584 if (VD->isWeak()) { 2585 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2586 return false; 2587 } 2588 2589 // Check that we can fold the initializer. In C++, we will have already done 2590 // this in the cases where it matters for conformance. 2591 SmallVector<PartialDiagnosticAt, 8> Notes; 2592 if (!VD->evaluateValue(Notes)) { 2593 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2594 Notes.size() + 1) << VD; 2595 Info.Note(VD->getLocation(), diag::note_declared_at); 2596 Info.addNotes(Notes); 2597 return false; 2598 } else if (!VD->checkInitIsICE()) { 2599 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2600 Notes.size() + 1) << VD; 2601 Info.Note(VD->getLocation(), diag::note_declared_at); 2602 Info.addNotes(Notes); 2603 } 2604 2605 Result = VD->getEvaluatedValue(); 2606 return true; 2607 } 2608 2609 static bool IsConstNonVolatile(QualType T) { 2610 Qualifiers Quals = T.getQualifiers(); 2611 return Quals.hasConst() && !Quals.hasVolatile(); 2612 } 2613 2614 /// Get the base index of the given base class within an APValue representing 2615 /// the given derived class. 2616 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2617 const CXXRecordDecl *Base) { 2618 Base = Base->getCanonicalDecl(); 2619 unsigned Index = 0; 2620 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2621 E = Derived->bases_end(); I != E; ++I, ++Index) { 2622 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2623 return Index; 2624 } 2625 2626 llvm_unreachable("base class missing from derived class's bases list"); 2627 } 2628 2629 /// Extract the value of a character from a string literal. 2630 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2631 uint64_t Index) { 2632 // FIXME: Support MakeStringConstant 2633 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2634 std::string Str; 2635 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2636 assert(Index <= Str.size() && "Index too large"); 2637 return APSInt::getUnsigned(Str.c_str()[Index]); 2638 } 2639 2640 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2641 Lit = PE->getFunctionName(); 2642 const StringLiteral *S = cast<StringLiteral>(Lit); 2643 const ConstantArrayType *CAT = 2644 Info.Ctx.getAsConstantArrayType(S->getType()); 2645 assert(CAT && "string literal isn't an array"); 2646 QualType CharType = CAT->getElementType(); 2647 assert(CharType->isIntegerType() && "unexpected character type"); 2648 2649 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2650 CharType->isUnsignedIntegerType()); 2651 if (Index < S->getLength()) 2652 Value = S->getCodeUnit(Index); 2653 return Value; 2654 } 2655 2656 // Expand a string literal into an array of characters. 2657 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit, 2658 APValue &Result) { 2659 const StringLiteral *S = cast<StringLiteral>(Lit); 2660 const ConstantArrayType *CAT = 2661 Info.Ctx.getAsConstantArrayType(S->getType()); 2662 assert(CAT && "string literal isn't an array"); 2663 QualType CharType = CAT->getElementType(); 2664 assert(CharType->isIntegerType() && "unexpected character type"); 2665 2666 unsigned Elts = CAT->getSize().getZExtValue(); 2667 Result = APValue(APValue::UninitArray(), 2668 std::min(S->getLength(), Elts), Elts); 2669 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2670 CharType->isUnsignedIntegerType()); 2671 if (Result.hasArrayFiller()) 2672 Result.getArrayFiller() = APValue(Value); 2673 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2674 Value = S->getCodeUnit(I); 2675 Result.getArrayInitializedElt(I) = APValue(Value); 2676 } 2677 } 2678 2679 // Expand an array so that it has more than Index filled elements. 2680 static void expandArray(APValue &Array, unsigned Index) { 2681 unsigned Size = Array.getArraySize(); 2682 assert(Index < Size); 2683 2684 // Always at least double the number of elements for which we store a value. 2685 unsigned OldElts = Array.getArrayInitializedElts(); 2686 unsigned NewElts = std::max(Index+1, OldElts * 2); 2687 NewElts = std::min(Size, std::max(NewElts, 8u)); 2688 2689 // Copy the data across. 2690 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2691 for (unsigned I = 0; I != OldElts; ++I) 2692 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2693 for (unsigned I = OldElts; I != NewElts; ++I) 2694 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2695 if (NewValue.hasArrayFiller()) 2696 NewValue.getArrayFiller() = Array.getArrayFiller(); 2697 Array.swap(NewValue); 2698 } 2699 2700 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2701 /// conversion. If it's of class type, we may assume that the copy operation 2702 /// is trivial. Note that this is never true for a union type with fields 2703 /// (because the copy always "reads" the active member) and always true for 2704 /// a non-class type. 2705 static bool isReadByLvalueToRvalueConversion(QualType T) { 2706 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2707 if (!RD || (RD->isUnion() && !RD->field_empty())) 2708 return true; 2709 if (RD->isEmpty()) 2710 return false; 2711 2712 for (auto *Field : RD->fields()) 2713 if (isReadByLvalueToRvalueConversion(Field->getType())) 2714 return true; 2715 2716 for (auto &BaseSpec : RD->bases()) 2717 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2718 return true; 2719 2720 return false; 2721 } 2722 2723 /// Diagnose an attempt to read from any unreadable field within the specified 2724 /// type, which might be a class type. 2725 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2726 QualType T) { 2727 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2728 if (!RD) 2729 return false; 2730 2731 if (!RD->hasMutableFields()) 2732 return false; 2733 2734 for (auto *Field : RD->fields()) { 2735 // If we're actually going to read this field in some way, then it can't 2736 // be mutable. If we're in a union, then assigning to a mutable field 2737 // (even an empty one) can change the active member, so that's not OK. 2738 // FIXME: Add core issue number for the union case. 2739 if (Field->isMutable() && 2740 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2741 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2742 Info.Note(Field->getLocation(), diag::note_declared_at); 2743 return true; 2744 } 2745 2746 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2747 return true; 2748 } 2749 2750 for (auto &BaseSpec : RD->bases()) 2751 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2752 return true; 2753 2754 // All mutable fields were empty, and thus not actually read. 2755 return false; 2756 } 2757 2758 /// Kinds of access we can perform on an object, for diagnostics. 2759 enum AccessKinds { 2760 AK_Read, 2761 AK_Assign, 2762 AK_Increment, 2763 AK_Decrement 2764 }; 2765 2766 namespace { 2767 /// A handle to a complete object (an object that is not a subobject of 2768 /// another object). 2769 struct CompleteObject { 2770 /// The value of the complete object. 2771 APValue *Value; 2772 /// The type of the complete object. 2773 QualType Type; 2774 bool LifetimeStartedInEvaluation; 2775 2776 CompleteObject() : Value(nullptr) {} 2777 CompleteObject(APValue *Value, QualType Type, 2778 bool LifetimeStartedInEvaluation) 2779 : Value(Value), Type(Type), 2780 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) { 2781 assert(Value && "missing value for complete object"); 2782 } 2783 2784 explicit operator bool() const { return Value; } 2785 }; 2786 } // end anonymous namespace 2787 2788 /// Find the designated sub-object of an rvalue. 2789 template<typename SubobjectHandler> 2790 typename SubobjectHandler::result_type 2791 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2792 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2793 if (Sub.Invalid) 2794 // A diagnostic will have already been produced. 2795 return handler.failed(); 2796 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 2797 if (Info.getLangOpts().CPlusPlus11) 2798 Info.FFDiag(E, Sub.isOnePastTheEnd() 2799 ? diag::note_constexpr_access_past_end 2800 : diag::note_constexpr_access_unsized_array) 2801 << handler.AccessKind; 2802 else 2803 Info.FFDiag(E); 2804 return handler.failed(); 2805 } 2806 2807 APValue *O = Obj.Value; 2808 QualType ObjType = Obj.Type; 2809 const FieldDecl *LastField = nullptr; 2810 const bool MayReadMutableMembers = 2811 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14; 2812 2813 // Walk the designator's path to find the subobject. 2814 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 2815 if (O->isUninit()) { 2816 if (!Info.checkingPotentialConstantExpression()) 2817 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind; 2818 return handler.failed(); 2819 } 2820 2821 if (I == N) { 2822 // If we are reading an object of class type, there may still be more 2823 // things we need to check: if there are any mutable subobjects, we 2824 // cannot perform this read. (This only happens when performing a trivial 2825 // copy or assignment.) 2826 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 2827 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType)) 2828 return handler.failed(); 2829 2830 if (!handler.found(*O, ObjType)) 2831 return false; 2832 2833 // If we modified a bit-field, truncate it to the right width. 2834 if (handler.AccessKind != AK_Read && 2835 LastField && LastField->isBitField() && 2836 !truncateBitfieldValue(Info, E, *O, LastField)) 2837 return false; 2838 2839 return true; 2840 } 2841 2842 LastField = nullptr; 2843 if (ObjType->isArrayType()) { 2844 // Next subobject is an array element. 2845 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 2846 assert(CAT && "vla in literal type?"); 2847 uint64_t Index = Sub.Entries[I].ArrayIndex; 2848 if (CAT->getSize().ule(Index)) { 2849 // Note, it should not be possible to form a pointer with a valid 2850 // designator which points more than one past the end of the array. 2851 if (Info.getLangOpts().CPlusPlus11) 2852 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2853 << handler.AccessKind; 2854 else 2855 Info.FFDiag(E); 2856 return handler.failed(); 2857 } 2858 2859 ObjType = CAT->getElementType(); 2860 2861 // An array object is represented as either an Array APValue or as an 2862 // LValue which refers to a string literal. 2863 if (O->isLValue()) { 2864 assert(I == N - 1 && "extracting subobject of character?"); 2865 assert(!O->hasLValuePath() || O->getLValuePath().empty()); 2866 if (handler.AccessKind != AK_Read) 2867 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(), 2868 *O); 2869 else 2870 return handler.foundString(*O, ObjType, Index); 2871 } 2872 2873 if (O->getArrayInitializedElts() > Index) 2874 O = &O->getArrayInitializedElt(Index); 2875 else if (handler.AccessKind != AK_Read) { 2876 expandArray(*O, Index); 2877 O = &O->getArrayInitializedElt(Index); 2878 } else 2879 O = &O->getArrayFiller(); 2880 } else if (ObjType->isAnyComplexType()) { 2881 // Next subobject is a complex number. 2882 uint64_t Index = Sub.Entries[I].ArrayIndex; 2883 if (Index > 1) { 2884 if (Info.getLangOpts().CPlusPlus11) 2885 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2886 << handler.AccessKind; 2887 else 2888 Info.FFDiag(E); 2889 return handler.failed(); 2890 } 2891 2892 bool WasConstQualified = ObjType.isConstQualified(); 2893 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2894 if (WasConstQualified) 2895 ObjType.addConst(); 2896 2897 assert(I == N - 1 && "extracting subobject of scalar?"); 2898 if (O->isComplexInt()) { 2899 return handler.found(Index ? O->getComplexIntImag() 2900 : O->getComplexIntReal(), ObjType); 2901 } else { 2902 assert(O->isComplexFloat()); 2903 return handler.found(Index ? O->getComplexFloatImag() 2904 : O->getComplexFloatReal(), ObjType); 2905 } 2906 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 2907 // In C++14 onwards, it is permitted to read a mutable member whose 2908 // lifetime began within the evaluation. 2909 // FIXME: Should we also allow this in C++11? 2910 if (Field->isMutable() && handler.AccessKind == AK_Read && 2911 !MayReadMutableMembers) { 2912 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 2913 << Field; 2914 Info.Note(Field->getLocation(), diag::note_declared_at); 2915 return handler.failed(); 2916 } 2917 2918 // Next subobject is a class, struct or union field. 2919 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 2920 if (RD->isUnion()) { 2921 const FieldDecl *UnionField = O->getUnionField(); 2922 if (!UnionField || 2923 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 2924 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 2925 << handler.AccessKind << Field << !UnionField << UnionField; 2926 return handler.failed(); 2927 } 2928 O = &O->getUnionValue(); 2929 } else 2930 O = &O->getStructField(Field->getFieldIndex()); 2931 2932 bool WasConstQualified = ObjType.isConstQualified(); 2933 ObjType = Field->getType(); 2934 if (WasConstQualified && !Field->isMutable()) 2935 ObjType.addConst(); 2936 2937 if (ObjType.isVolatileQualified()) { 2938 if (Info.getLangOpts().CPlusPlus) { 2939 // FIXME: Include a description of the path to the volatile subobject. 2940 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2941 << handler.AccessKind << 2 << Field; 2942 Info.Note(Field->getLocation(), diag::note_declared_at); 2943 } else { 2944 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2945 } 2946 return handler.failed(); 2947 } 2948 2949 LastField = Field; 2950 } else { 2951 // Next subobject is a base class. 2952 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 2953 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 2954 O = &O->getStructBase(getBaseIndex(Derived, Base)); 2955 2956 bool WasConstQualified = ObjType.isConstQualified(); 2957 ObjType = Info.Ctx.getRecordType(Base); 2958 if (WasConstQualified) 2959 ObjType.addConst(); 2960 } 2961 } 2962 } 2963 2964 namespace { 2965 struct ExtractSubobjectHandler { 2966 EvalInfo &Info; 2967 APValue &Result; 2968 2969 static const AccessKinds AccessKind = AK_Read; 2970 2971 typedef bool result_type; 2972 bool failed() { return false; } 2973 bool found(APValue &Subobj, QualType SubobjType) { 2974 Result = Subobj; 2975 return true; 2976 } 2977 bool found(APSInt &Value, QualType SubobjType) { 2978 Result = APValue(Value); 2979 return true; 2980 } 2981 bool found(APFloat &Value, QualType SubobjType) { 2982 Result = APValue(Value); 2983 return true; 2984 } 2985 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2986 Result = APValue(extractStringLiteralCharacter( 2987 Info, Subobj.getLValueBase().get<const Expr *>(), Character)); 2988 return true; 2989 } 2990 }; 2991 } // end anonymous namespace 2992 2993 const AccessKinds ExtractSubobjectHandler::AccessKind; 2994 2995 /// Extract the designated sub-object of an rvalue. 2996 static bool extractSubobject(EvalInfo &Info, const Expr *E, 2997 const CompleteObject &Obj, 2998 const SubobjectDesignator &Sub, 2999 APValue &Result) { 3000 ExtractSubobjectHandler Handler = { Info, Result }; 3001 return findSubobject(Info, E, Obj, Sub, Handler); 3002 } 3003 3004 namespace { 3005 struct ModifySubobjectHandler { 3006 EvalInfo &Info; 3007 APValue &NewVal; 3008 const Expr *E; 3009 3010 typedef bool result_type; 3011 static const AccessKinds AccessKind = AK_Assign; 3012 3013 bool checkConst(QualType QT) { 3014 // Assigning to a const object has undefined behavior. 3015 if (QT.isConstQualified()) { 3016 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3017 return false; 3018 } 3019 return true; 3020 } 3021 3022 bool failed() { return false; } 3023 bool found(APValue &Subobj, QualType SubobjType) { 3024 if (!checkConst(SubobjType)) 3025 return false; 3026 // We've been given ownership of NewVal, so just swap it in. 3027 Subobj.swap(NewVal); 3028 return true; 3029 } 3030 bool found(APSInt &Value, QualType SubobjType) { 3031 if (!checkConst(SubobjType)) 3032 return false; 3033 if (!NewVal.isInt()) { 3034 // Maybe trying to write a cast pointer value into a complex? 3035 Info.FFDiag(E); 3036 return false; 3037 } 3038 Value = NewVal.getInt(); 3039 return true; 3040 } 3041 bool found(APFloat &Value, QualType SubobjType) { 3042 if (!checkConst(SubobjType)) 3043 return false; 3044 Value = NewVal.getFloat(); 3045 return true; 3046 } 3047 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3048 llvm_unreachable("shouldn't encounter string elements with ExpandArrays"); 3049 } 3050 }; 3051 } // end anonymous namespace 3052 3053 const AccessKinds ModifySubobjectHandler::AccessKind; 3054 3055 /// Update the designated sub-object of an rvalue to the given value. 3056 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3057 const CompleteObject &Obj, 3058 const SubobjectDesignator &Sub, 3059 APValue &NewVal) { 3060 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3061 return findSubobject(Info, E, Obj, Sub, Handler); 3062 } 3063 3064 /// Find the position where two subobject designators diverge, or equivalently 3065 /// the length of the common initial subsequence. 3066 static unsigned FindDesignatorMismatch(QualType ObjType, 3067 const SubobjectDesignator &A, 3068 const SubobjectDesignator &B, 3069 bool &WasArrayIndex) { 3070 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3071 for (/**/; I != N; ++I) { 3072 if (!ObjType.isNull() && 3073 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3074 // Next subobject is an array element. 3075 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) { 3076 WasArrayIndex = true; 3077 return I; 3078 } 3079 if (ObjType->isAnyComplexType()) 3080 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3081 else 3082 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3083 } else { 3084 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) { 3085 WasArrayIndex = false; 3086 return I; 3087 } 3088 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3089 // Next subobject is a field. 3090 ObjType = FD->getType(); 3091 else 3092 // Next subobject is a base class. 3093 ObjType = QualType(); 3094 } 3095 } 3096 WasArrayIndex = false; 3097 return I; 3098 } 3099 3100 /// Determine whether the given subobject designators refer to elements of the 3101 /// same array object. 3102 static bool AreElementsOfSameArray(QualType ObjType, 3103 const SubobjectDesignator &A, 3104 const SubobjectDesignator &B) { 3105 if (A.Entries.size() != B.Entries.size()) 3106 return false; 3107 3108 bool IsArray = A.MostDerivedIsArrayElement; 3109 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3110 // A is a subobject of the array element. 3111 return false; 3112 3113 // If A (and B) designates an array element, the last entry will be the array 3114 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3115 // of length 1' case, and the entire path must match. 3116 bool WasArrayIndex; 3117 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3118 return CommonLength >= A.Entries.size() - IsArray; 3119 } 3120 3121 /// Find the complete object to which an LValue refers. 3122 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3123 AccessKinds AK, const LValue &LVal, 3124 QualType LValType) { 3125 if (!LVal.Base) { 3126 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3127 return CompleteObject(); 3128 } 3129 3130 CallStackFrame *Frame = nullptr; 3131 if (LVal.getLValueCallIndex()) { 3132 Frame = Info.getCallFrame(LVal.getLValueCallIndex()); 3133 if (!Frame) { 3134 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3135 << AK << LVal.Base.is<const ValueDecl*>(); 3136 NoteLValueLocation(Info, LVal.Base); 3137 return CompleteObject(); 3138 } 3139 } 3140 3141 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3142 // is not a constant expression (even if the object is non-volatile). We also 3143 // apply this rule to C++98, in order to conform to the expected 'volatile' 3144 // semantics. 3145 if (LValType.isVolatileQualified()) { 3146 if (Info.getLangOpts().CPlusPlus) 3147 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3148 << AK << LValType; 3149 else 3150 Info.FFDiag(E); 3151 return CompleteObject(); 3152 } 3153 3154 // Compute value storage location and type of base object. 3155 APValue *BaseVal = nullptr; 3156 QualType BaseType = getType(LVal.Base); 3157 bool LifetimeStartedInEvaluation = Frame; 3158 3159 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3160 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3161 // In C++11, constexpr, non-volatile variables initialized with constant 3162 // expressions are constant expressions too. Inside constexpr functions, 3163 // parameters are constant expressions even if they're non-const. 3164 // In C++1y, objects local to a constant expression (those with a Frame) are 3165 // both readable and writable inside constant expressions. 3166 // In C, such things can also be folded, although they are not ICEs. 3167 const VarDecl *VD = dyn_cast<VarDecl>(D); 3168 if (VD) { 3169 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3170 VD = VDef; 3171 } 3172 if (!VD || VD->isInvalidDecl()) { 3173 Info.FFDiag(E); 3174 return CompleteObject(); 3175 } 3176 3177 // Accesses of volatile-qualified objects are not allowed. 3178 if (BaseType.isVolatileQualified()) { 3179 if (Info.getLangOpts().CPlusPlus) { 3180 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3181 << AK << 1 << VD; 3182 Info.Note(VD->getLocation(), diag::note_declared_at); 3183 } else { 3184 Info.FFDiag(E); 3185 } 3186 return CompleteObject(); 3187 } 3188 3189 // Unless we're looking at a local variable or argument in a constexpr call, 3190 // the variable we're reading must be const. 3191 if (!Frame) { 3192 if (Info.getLangOpts().CPlusPlus14 && 3193 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) { 3194 // OK, we can read and modify an object if we're in the process of 3195 // evaluating its initializer, because its lifetime began in this 3196 // evaluation. 3197 } else if (AK != AK_Read) { 3198 // All the remaining cases only permit reading. 3199 Info.FFDiag(E, diag::note_constexpr_modify_global); 3200 return CompleteObject(); 3201 } else if (VD->isConstexpr()) { 3202 // OK, we can read this variable. 3203 } else if (BaseType->isIntegralOrEnumerationType()) { 3204 // In OpenCL if a variable is in constant address space it is a const value. 3205 if (!(BaseType.isConstQualified() || 3206 (Info.getLangOpts().OpenCL && 3207 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3208 if (Info.getLangOpts().CPlusPlus) { 3209 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3210 Info.Note(VD->getLocation(), diag::note_declared_at); 3211 } else { 3212 Info.FFDiag(E); 3213 } 3214 return CompleteObject(); 3215 } 3216 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3217 // We support folding of const floating-point types, in order to make 3218 // static const data members of such types (supported as an extension) 3219 // more useful. 3220 if (Info.getLangOpts().CPlusPlus11) { 3221 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3222 Info.Note(VD->getLocation(), diag::note_declared_at); 3223 } else { 3224 Info.CCEDiag(E); 3225 } 3226 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3227 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3228 // Keep evaluating to see what we can do. 3229 } else { 3230 // FIXME: Allow folding of values of any literal type in all languages. 3231 if (Info.checkingPotentialConstantExpression() && 3232 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3233 // The definition of this variable could be constexpr. We can't 3234 // access it right now, but may be able to in future. 3235 } else if (Info.getLangOpts().CPlusPlus11) { 3236 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3237 Info.Note(VD->getLocation(), diag::note_declared_at); 3238 } else { 3239 Info.FFDiag(E); 3240 } 3241 return CompleteObject(); 3242 } 3243 } 3244 3245 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3246 return CompleteObject(); 3247 } else { 3248 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3249 3250 if (!Frame) { 3251 if (const MaterializeTemporaryExpr *MTE = 3252 dyn_cast<MaterializeTemporaryExpr>(Base)) { 3253 assert(MTE->getStorageDuration() == SD_Static && 3254 "should have a frame for a non-global materialized temporary"); 3255 3256 // Per C++1y [expr.const]p2: 3257 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3258 // - a [...] glvalue of integral or enumeration type that refers to 3259 // a non-volatile const object [...] 3260 // [...] 3261 // - a [...] glvalue of literal type that refers to a non-volatile 3262 // object whose lifetime began within the evaluation of e. 3263 // 3264 // C++11 misses the 'began within the evaluation of e' check and 3265 // instead allows all temporaries, including things like: 3266 // int &&r = 1; 3267 // int x = ++r; 3268 // constexpr int k = r; 3269 // Therefore we use the C++14 rules in C++11 too. 3270 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3271 const ValueDecl *ED = MTE->getExtendingDecl(); 3272 if (!(BaseType.isConstQualified() && 3273 BaseType->isIntegralOrEnumerationType()) && 3274 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 3275 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3276 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3277 return CompleteObject(); 3278 } 3279 3280 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3281 assert(BaseVal && "got reference to unevaluated temporary"); 3282 LifetimeStartedInEvaluation = true; 3283 } else { 3284 Info.FFDiag(E); 3285 return CompleteObject(); 3286 } 3287 } else { 3288 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3289 assert(BaseVal && "missing value for temporary"); 3290 } 3291 3292 // Volatile temporary objects cannot be accessed in constant expressions. 3293 if (BaseType.isVolatileQualified()) { 3294 if (Info.getLangOpts().CPlusPlus) { 3295 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3296 << AK << 0; 3297 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here); 3298 } else { 3299 Info.FFDiag(E); 3300 } 3301 return CompleteObject(); 3302 } 3303 } 3304 3305 // During the construction of an object, it is not yet 'const'. 3306 // FIXME: This doesn't do quite the right thing for const subobjects of the 3307 // object under construction. 3308 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), 3309 LVal.getLValueCallIndex(), 3310 LVal.getLValueVersion())) { 3311 BaseType = Info.Ctx.getCanonicalType(BaseType); 3312 BaseType.removeLocalConst(); 3313 LifetimeStartedInEvaluation = true; 3314 } 3315 3316 // In C++14, we can't safely access any mutable state when we might be 3317 // evaluating after an unmodeled side effect. 3318 // 3319 // FIXME: Not all local state is mutable. Allow local constant subobjects 3320 // to be read here (but take care with 'mutable' fields). 3321 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3322 Info.EvalStatus.HasSideEffects) || 3323 (AK != AK_Read && Info.IsSpeculativelyEvaluating)) 3324 return CompleteObject(); 3325 3326 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation); 3327 } 3328 3329 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3330 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3331 /// glvalue referred to by an entity of reference type. 3332 /// 3333 /// \param Info - Information about the ongoing evaluation. 3334 /// \param Conv - The expression for which we are performing the conversion. 3335 /// Used for diagnostics. 3336 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3337 /// case of a non-class type). 3338 /// \param LVal - The glvalue on which we are attempting to perform this action. 3339 /// \param RVal - The produced value will be placed here. 3340 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 3341 QualType Type, 3342 const LValue &LVal, APValue &RVal) { 3343 if (LVal.Designator.Invalid) 3344 return false; 3345 3346 // Check for special cases where there is no existing APValue to look at. 3347 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3348 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 3349 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3350 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3351 // initializer until now for such expressions. Such an expression can't be 3352 // an ICE in C, so this only matters for fold. 3353 if (Type.isVolatileQualified()) { 3354 Info.FFDiag(Conv); 3355 return false; 3356 } 3357 APValue Lit; 3358 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3359 return false; 3360 CompleteObject LitObj(&Lit, Base->getType(), false); 3361 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 3362 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3363 // We represent a string literal array as an lvalue pointing at the 3364 // corresponding expression, rather than building an array of chars. 3365 // FIXME: Support ObjCEncodeExpr, MakeStringConstant 3366 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0); 3367 CompleteObject StrObj(&Str, Base->getType(), false); 3368 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal); 3369 } 3370 } 3371 3372 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 3373 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 3374 } 3375 3376 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3377 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3378 QualType LValType, APValue &Val) { 3379 if (LVal.Designator.Invalid) 3380 return false; 3381 3382 if (!Info.getLangOpts().CPlusPlus14) { 3383 Info.FFDiag(E); 3384 return false; 3385 } 3386 3387 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3388 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3389 } 3390 3391 namespace { 3392 struct CompoundAssignSubobjectHandler { 3393 EvalInfo &Info; 3394 const Expr *E; 3395 QualType PromotedLHSType; 3396 BinaryOperatorKind Opcode; 3397 const APValue &RHS; 3398 3399 static const AccessKinds AccessKind = AK_Assign; 3400 3401 typedef bool result_type; 3402 3403 bool checkConst(QualType QT) { 3404 // Assigning to a const object has undefined behavior. 3405 if (QT.isConstQualified()) { 3406 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3407 return false; 3408 } 3409 return true; 3410 } 3411 3412 bool failed() { return false; } 3413 bool found(APValue &Subobj, QualType SubobjType) { 3414 switch (Subobj.getKind()) { 3415 case APValue::Int: 3416 return found(Subobj.getInt(), SubobjType); 3417 case APValue::Float: 3418 return found(Subobj.getFloat(), SubobjType); 3419 case APValue::ComplexInt: 3420 case APValue::ComplexFloat: 3421 // FIXME: Implement complex compound assignment. 3422 Info.FFDiag(E); 3423 return false; 3424 case APValue::LValue: 3425 return foundPointer(Subobj, SubobjType); 3426 default: 3427 // FIXME: can this happen? 3428 Info.FFDiag(E); 3429 return false; 3430 } 3431 } 3432 bool found(APSInt &Value, QualType SubobjType) { 3433 if (!checkConst(SubobjType)) 3434 return false; 3435 3436 if (!SubobjType->isIntegerType() || !RHS.isInt()) { 3437 // We don't support compound assignment on integer-cast-to-pointer 3438 // values. 3439 Info.FFDiag(E); 3440 return false; 3441 } 3442 3443 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType, 3444 SubobjType, Value); 3445 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3446 return false; 3447 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3448 return true; 3449 } 3450 bool found(APFloat &Value, QualType SubobjType) { 3451 return checkConst(SubobjType) && 3452 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3453 Value) && 3454 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3455 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3456 } 3457 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3458 if (!checkConst(SubobjType)) 3459 return false; 3460 3461 QualType PointeeType; 3462 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3463 PointeeType = PT->getPointeeType(); 3464 3465 if (PointeeType.isNull() || !RHS.isInt() || 3466 (Opcode != BO_Add && Opcode != BO_Sub)) { 3467 Info.FFDiag(E); 3468 return false; 3469 } 3470 3471 APSInt Offset = RHS.getInt(); 3472 if (Opcode == BO_Sub) 3473 negateAsSigned(Offset); 3474 3475 LValue LVal; 3476 LVal.setFrom(Info.Ctx, Subobj); 3477 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3478 return false; 3479 LVal.moveInto(Subobj); 3480 return true; 3481 } 3482 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3483 llvm_unreachable("shouldn't encounter string elements here"); 3484 } 3485 }; 3486 } // end anonymous namespace 3487 3488 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3489 3490 /// Perform a compound assignment of LVal <op>= RVal. 3491 static bool handleCompoundAssignment( 3492 EvalInfo &Info, const Expr *E, 3493 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3494 BinaryOperatorKind Opcode, const APValue &RVal) { 3495 if (LVal.Designator.Invalid) 3496 return false; 3497 3498 if (!Info.getLangOpts().CPlusPlus14) { 3499 Info.FFDiag(E); 3500 return false; 3501 } 3502 3503 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3504 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3505 RVal }; 3506 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3507 } 3508 3509 namespace { 3510 struct IncDecSubobjectHandler { 3511 EvalInfo &Info; 3512 const UnaryOperator *E; 3513 AccessKinds AccessKind; 3514 APValue *Old; 3515 3516 typedef bool result_type; 3517 3518 bool checkConst(QualType QT) { 3519 // Assigning to a const object has undefined behavior. 3520 if (QT.isConstQualified()) { 3521 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3522 return false; 3523 } 3524 return true; 3525 } 3526 3527 bool failed() { return false; } 3528 bool found(APValue &Subobj, QualType SubobjType) { 3529 // Stash the old value. Also clear Old, so we don't clobber it later 3530 // if we're post-incrementing a complex. 3531 if (Old) { 3532 *Old = Subobj; 3533 Old = nullptr; 3534 } 3535 3536 switch (Subobj.getKind()) { 3537 case APValue::Int: 3538 return found(Subobj.getInt(), SubobjType); 3539 case APValue::Float: 3540 return found(Subobj.getFloat(), SubobjType); 3541 case APValue::ComplexInt: 3542 return found(Subobj.getComplexIntReal(), 3543 SubobjType->castAs<ComplexType>()->getElementType() 3544 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3545 case APValue::ComplexFloat: 3546 return found(Subobj.getComplexFloatReal(), 3547 SubobjType->castAs<ComplexType>()->getElementType() 3548 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3549 case APValue::LValue: 3550 return foundPointer(Subobj, SubobjType); 3551 default: 3552 // FIXME: can this happen? 3553 Info.FFDiag(E); 3554 return false; 3555 } 3556 } 3557 bool found(APSInt &Value, QualType SubobjType) { 3558 if (!checkConst(SubobjType)) 3559 return false; 3560 3561 if (!SubobjType->isIntegerType()) { 3562 // We don't support increment / decrement on integer-cast-to-pointer 3563 // values. 3564 Info.FFDiag(E); 3565 return false; 3566 } 3567 3568 if (Old) *Old = APValue(Value); 3569 3570 // bool arithmetic promotes to int, and the conversion back to bool 3571 // doesn't reduce mod 2^n, so special-case it. 3572 if (SubobjType->isBooleanType()) { 3573 if (AccessKind == AK_Increment) 3574 Value = 1; 3575 else 3576 Value = !Value; 3577 return true; 3578 } 3579 3580 bool WasNegative = Value.isNegative(); 3581 if (AccessKind == AK_Increment) { 3582 ++Value; 3583 3584 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 3585 APSInt ActualValue(Value, /*IsUnsigned*/true); 3586 return HandleOverflow(Info, E, ActualValue, SubobjType); 3587 } 3588 } else { 3589 --Value; 3590 3591 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 3592 unsigned BitWidth = Value.getBitWidth(); 3593 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3594 ActualValue.setBit(BitWidth); 3595 return HandleOverflow(Info, E, ActualValue, SubobjType); 3596 } 3597 } 3598 return true; 3599 } 3600 bool found(APFloat &Value, QualType SubobjType) { 3601 if (!checkConst(SubobjType)) 3602 return false; 3603 3604 if (Old) *Old = APValue(Value); 3605 3606 APFloat One(Value.getSemantics(), 1); 3607 if (AccessKind == AK_Increment) 3608 Value.add(One, APFloat::rmNearestTiesToEven); 3609 else 3610 Value.subtract(One, APFloat::rmNearestTiesToEven); 3611 return true; 3612 } 3613 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3614 if (!checkConst(SubobjType)) 3615 return false; 3616 3617 QualType PointeeType; 3618 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3619 PointeeType = PT->getPointeeType(); 3620 else { 3621 Info.FFDiag(E); 3622 return false; 3623 } 3624 3625 LValue LVal; 3626 LVal.setFrom(Info.Ctx, Subobj); 3627 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3628 AccessKind == AK_Increment ? 1 : -1)) 3629 return false; 3630 LVal.moveInto(Subobj); 3631 return true; 3632 } 3633 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3634 llvm_unreachable("shouldn't encounter string elements here"); 3635 } 3636 }; 3637 } // end anonymous namespace 3638 3639 /// Perform an increment or decrement on LVal. 3640 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3641 QualType LValType, bool IsIncrement, APValue *Old) { 3642 if (LVal.Designator.Invalid) 3643 return false; 3644 3645 if (!Info.getLangOpts().CPlusPlus14) { 3646 Info.FFDiag(E); 3647 return false; 3648 } 3649 3650 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3651 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3652 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 3653 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3654 } 3655 3656 /// Build an lvalue for the object argument of a member function call. 3657 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3658 LValue &This) { 3659 if (Object->getType()->isPointerType()) 3660 return EvaluatePointer(Object, This, Info); 3661 3662 if (Object->isGLValue()) 3663 return EvaluateLValue(Object, This, Info); 3664 3665 if (Object->getType()->isLiteralType(Info.Ctx)) 3666 return EvaluateTemporary(Object, This, Info); 3667 3668 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3669 return false; 3670 } 3671 3672 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3673 /// lvalue referring to the result. 3674 /// 3675 /// \param Info - Information about the ongoing evaluation. 3676 /// \param LV - An lvalue referring to the base of the member pointer. 3677 /// \param RHS - The member pointer expression. 3678 /// \param IncludeMember - Specifies whether the member itself is included in 3679 /// the resulting LValue subobject designator. This is not possible when 3680 /// creating a bound member function. 3681 /// \return The field or method declaration to which the member pointer refers, 3682 /// or 0 if evaluation fails. 3683 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3684 QualType LVType, 3685 LValue &LV, 3686 const Expr *RHS, 3687 bool IncludeMember = true) { 3688 MemberPtr MemPtr; 3689 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3690 return nullptr; 3691 3692 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3693 // member value, the behavior is undefined. 3694 if (!MemPtr.getDecl()) { 3695 // FIXME: Specific diagnostic. 3696 Info.FFDiag(RHS); 3697 return nullptr; 3698 } 3699 3700 if (MemPtr.isDerivedMember()) { 3701 // This is a member of some derived class. Truncate LV appropriately. 3702 // The end of the derived-to-base path for the base object must match the 3703 // derived-to-base path for the member pointer. 3704 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3705 LV.Designator.Entries.size()) { 3706 Info.FFDiag(RHS); 3707 return nullptr; 3708 } 3709 unsigned PathLengthToMember = 3710 LV.Designator.Entries.size() - MemPtr.Path.size(); 3711 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3712 const CXXRecordDecl *LVDecl = getAsBaseClass( 3713 LV.Designator.Entries[PathLengthToMember + I]); 3714 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3715 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3716 Info.FFDiag(RHS); 3717 return nullptr; 3718 } 3719 } 3720 3721 // Truncate the lvalue to the appropriate derived class. 3722 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3723 PathLengthToMember)) 3724 return nullptr; 3725 } else if (!MemPtr.Path.empty()) { 3726 // Extend the LValue path with the member pointer's path. 3727 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3728 MemPtr.Path.size() + IncludeMember); 3729 3730 // Walk down to the appropriate base class. 3731 if (const PointerType *PT = LVType->getAs<PointerType>()) 3732 LVType = PT->getPointeeType(); 3733 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3734 assert(RD && "member pointer access on non-class-type expression"); 3735 // The first class in the path is that of the lvalue. 3736 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3737 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3738 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3739 return nullptr; 3740 RD = Base; 3741 } 3742 // Finally cast to the class containing the member. 3743 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3744 MemPtr.getContainingRecord())) 3745 return nullptr; 3746 } 3747 3748 // Add the member. Note that we cannot build bound member functions here. 3749 if (IncludeMember) { 3750 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3751 if (!HandleLValueMember(Info, RHS, LV, FD)) 3752 return nullptr; 3753 } else if (const IndirectFieldDecl *IFD = 3754 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3755 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3756 return nullptr; 3757 } else { 3758 llvm_unreachable("can't construct reference to bound member function"); 3759 } 3760 } 3761 3762 return MemPtr.getDecl(); 3763 } 3764 3765 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3766 const BinaryOperator *BO, 3767 LValue &LV, 3768 bool IncludeMember = true) { 3769 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3770 3771 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3772 if (Info.noteFailure()) { 3773 MemberPtr MemPtr; 3774 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3775 } 3776 return nullptr; 3777 } 3778 3779 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3780 BO->getRHS(), IncludeMember); 3781 } 3782 3783 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3784 /// the provided lvalue, which currently refers to the base object. 3785 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3786 LValue &Result) { 3787 SubobjectDesignator &D = Result.Designator; 3788 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3789 return false; 3790 3791 QualType TargetQT = E->getType(); 3792 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 3793 TargetQT = PT->getPointeeType(); 3794 3795 // Check this cast lands within the final derived-to-base subobject path. 3796 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 3797 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3798 << D.MostDerivedType << TargetQT; 3799 return false; 3800 } 3801 3802 // Check the type of the final cast. We don't need to check the path, 3803 // since a cast can only be formed if the path is unique. 3804 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 3805 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 3806 const CXXRecordDecl *FinalType; 3807 if (NewEntriesSize == D.MostDerivedPathLength) 3808 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 3809 else 3810 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 3811 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 3812 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3813 << D.MostDerivedType << TargetQT; 3814 return false; 3815 } 3816 3817 // Truncate the lvalue to the appropriate derived class. 3818 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 3819 } 3820 3821 namespace { 3822 enum EvalStmtResult { 3823 /// Evaluation failed. 3824 ESR_Failed, 3825 /// Hit a 'return' statement. 3826 ESR_Returned, 3827 /// Evaluation succeeded. 3828 ESR_Succeeded, 3829 /// Hit a 'continue' statement. 3830 ESR_Continue, 3831 /// Hit a 'break' statement. 3832 ESR_Break, 3833 /// Still scanning for 'case' or 'default' statement. 3834 ESR_CaseNotFound 3835 }; 3836 } 3837 3838 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 3839 // We don't need to evaluate the initializer for a static local. 3840 if (!VD->hasLocalStorage()) 3841 return true; 3842 3843 LValue Result; 3844 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall); 3845 3846 const Expr *InitE = VD->getInit(); 3847 if (!InitE) { 3848 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized) 3849 << false << VD->getType(); 3850 Val = APValue(); 3851 return false; 3852 } 3853 3854 if (InitE->isValueDependent()) 3855 return false; 3856 3857 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 3858 // Wipe out any partially-computed value, to allow tracking that this 3859 // evaluation failed. 3860 Val = APValue(); 3861 return false; 3862 } 3863 3864 return true; 3865 } 3866 3867 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 3868 bool OK = true; 3869 3870 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 3871 OK &= EvaluateVarDecl(Info, VD); 3872 3873 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 3874 for (auto *BD : DD->bindings()) 3875 if (auto *VD = BD->getHoldingVar()) 3876 OK &= EvaluateDecl(Info, VD); 3877 3878 return OK; 3879 } 3880 3881 3882 /// Evaluate a condition (either a variable declaration or an expression). 3883 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 3884 const Expr *Cond, bool &Result) { 3885 FullExpressionRAII Scope(Info); 3886 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 3887 return false; 3888 return EvaluateAsBooleanCondition(Cond, Result, Info); 3889 } 3890 3891 namespace { 3892 /// A location where the result (returned value) of evaluating a 3893 /// statement should be stored. 3894 struct StmtResult { 3895 /// The APValue that should be filled in with the returned value. 3896 APValue &Value; 3897 /// The location containing the result, if any (used to support RVO). 3898 const LValue *Slot; 3899 }; 3900 3901 struct TempVersionRAII { 3902 CallStackFrame &Frame; 3903 3904 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 3905 Frame.pushTempVersion(); 3906 } 3907 3908 ~TempVersionRAII() { 3909 Frame.popTempVersion(); 3910 } 3911 }; 3912 3913 } 3914 3915 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3916 const Stmt *S, 3917 const SwitchCase *SC = nullptr); 3918 3919 /// Evaluate the body of a loop, and translate the result as appropriate. 3920 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 3921 const Stmt *Body, 3922 const SwitchCase *Case = nullptr) { 3923 BlockScopeRAII Scope(Info); 3924 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 3925 case ESR_Break: 3926 return ESR_Succeeded; 3927 case ESR_Succeeded: 3928 case ESR_Continue: 3929 return ESR_Continue; 3930 case ESR_Failed: 3931 case ESR_Returned: 3932 case ESR_CaseNotFound: 3933 return ESR; 3934 } 3935 llvm_unreachable("Invalid EvalStmtResult!"); 3936 } 3937 3938 /// Evaluate a switch statement. 3939 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 3940 const SwitchStmt *SS) { 3941 BlockScopeRAII Scope(Info); 3942 3943 // Evaluate the switch condition. 3944 APSInt Value; 3945 { 3946 FullExpressionRAII Scope(Info); 3947 if (const Stmt *Init = SS->getInit()) { 3948 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3949 if (ESR != ESR_Succeeded) 3950 return ESR; 3951 } 3952 if (SS->getConditionVariable() && 3953 !EvaluateDecl(Info, SS->getConditionVariable())) 3954 return ESR_Failed; 3955 if (!EvaluateInteger(SS->getCond(), Value, Info)) 3956 return ESR_Failed; 3957 } 3958 3959 // Find the switch case corresponding to the value of the condition. 3960 // FIXME: Cache this lookup. 3961 const SwitchCase *Found = nullptr; 3962 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 3963 SC = SC->getNextSwitchCase()) { 3964 if (isa<DefaultStmt>(SC)) { 3965 Found = SC; 3966 continue; 3967 } 3968 3969 const CaseStmt *CS = cast<CaseStmt>(SC); 3970 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 3971 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 3972 : LHS; 3973 if (LHS <= Value && Value <= RHS) { 3974 Found = SC; 3975 break; 3976 } 3977 } 3978 3979 if (!Found) 3980 return ESR_Succeeded; 3981 3982 // Search the switch body for the switch case and evaluate it from there. 3983 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 3984 case ESR_Break: 3985 return ESR_Succeeded; 3986 case ESR_Succeeded: 3987 case ESR_Continue: 3988 case ESR_Failed: 3989 case ESR_Returned: 3990 return ESR; 3991 case ESR_CaseNotFound: 3992 // This can only happen if the switch case is nested within a statement 3993 // expression. We have no intention of supporting that. 3994 Info.FFDiag(Found->getBeginLoc(), 3995 diag::note_constexpr_stmt_expr_unsupported); 3996 return ESR_Failed; 3997 } 3998 llvm_unreachable("Invalid EvalStmtResult!"); 3999 } 4000 4001 // Evaluate a statement. 4002 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4003 const Stmt *S, const SwitchCase *Case) { 4004 if (!Info.nextStep(S)) 4005 return ESR_Failed; 4006 4007 // If we're hunting down a 'case' or 'default' label, recurse through 4008 // substatements until we hit the label. 4009 if (Case) { 4010 // FIXME: We don't start the lifetime of objects whose initialization we 4011 // jump over. However, such objects must be of class type with a trivial 4012 // default constructor that initialize all subobjects, so must be empty, 4013 // so this almost never matters. 4014 switch (S->getStmtClass()) { 4015 case Stmt::CompoundStmtClass: 4016 // FIXME: Precompute which substatement of a compound statement we 4017 // would jump to, and go straight there rather than performing a 4018 // linear scan each time. 4019 case Stmt::LabelStmtClass: 4020 case Stmt::AttributedStmtClass: 4021 case Stmt::DoStmtClass: 4022 break; 4023 4024 case Stmt::CaseStmtClass: 4025 case Stmt::DefaultStmtClass: 4026 if (Case == S) 4027 Case = nullptr; 4028 break; 4029 4030 case Stmt::IfStmtClass: { 4031 // FIXME: Precompute which side of an 'if' we would jump to, and go 4032 // straight there rather than scanning both sides. 4033 const IfStmt *IS = cast<IfStmt>(S); 4034 4035 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4036 // preceded by our switch label. 4037 BlockScopeRAII Scope(Info); 4038 4039 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4040 if (ESR != ESR_CaseNotFound || !IS->getElse()) 4041 return ESR; 4042 return EvaluateStmt(Result, Info, IS->getElse(), Case); 4043 } 4044 4045 case Stmt::WhileStmtClass: { 4046 EvalStmtResult ESR = 4047 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4048 if (ESR != ESR_Continue) 4049 return ESR; 4050 break; 4051 } 4052 4053 case Stmt::ForStmtClass: { 4054 const ForStmt *FS = cast<ForStmt>(S); 4055 EvalStmtResult ESR = 4056 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4057 if (ESR != ESR_Continue) 4058 return ESR; 4059 if (FS->getInc()) { 4060 FullExpressionRAII IncScope(Info); 4061 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4062 return ESR_Failed; 4063 } 4064 break; 4065 } 4066 4067 case Stmt::DeclStmtClass: 4068 // FIXME: If the variable has initialization that can't be jumped over, 4069 // bail out of any immediately-surrounding compound-statement too. 4070 default: 4071 return ESR_CaseNotFound; 4072 } 4073 } 4074 4075 switch (S->getStmtClass()) { 4076 default: 4077 if (const Expr *E = dyn_cast<Expr>(S)) { 4078 // Don't bother evaluating beyond an expression-statement which couldn't 4079 // be evaluated. 4080 FullExpressionRAII Scope(Info); 4081 if (!EvaluateIgnoredValue(Info, E)) 4082 return ESR_Failed; 4083 return ESR_Succeeded; 4084 } 4085 4086 Info.FFDiag(S->getBeginLoc()); 4087 return ESR_Failed; 4088 4089 case Stmt::NullStmtClass: 4090 return ESR_Succeeded; 4091 4092 case Stmt::DeclStmtClass: { 4093 const DeclStmt *DS = cast<DeclStmt>(S); 4094 for (const auto *DclIt : DS->decls()) { 4095 // Each declaration initialization is its own full-expression. 4096 // FIXME: This isn't quite right; if we're performing aggregate 4097 // initialization, each braced subexpression is its own full-expression. 4098 FullExpressionRAII Scope(Info); 4099 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 4100 return ESR_Failed; 4101 } 4102 return ESR_Succeeded; 4103 } 4104 4105 case Stmt::ReturnStmtClass: { 4106 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4107 FullExpressionRAII Scope(Info); 4108 if (RetExpr && 4109 !(Result.Slot 4110 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4111 : Evaluate(Result.Value, Info, RetExpr))) 4112 return ESR_Failed; 4113 return ESR_Returned; 4114 } 4115 4116 case Stmt::CompoundStmtClass: { 4117 BlockScopeRAII Scope(Info); 4118 4119 const CompoundStmt *CS = cast<CompoundStmt>(S); 4120 for (const auto *BI : CS->body()) { 4121 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4122 if (ESR == ESR_Succeeded) 4123 Case = nullptr; 4124 else if (ESR != ESR_CaseNotFound) 4125 return ESR; 4126 } 4127 return Case ? ESR_CaseNotFound : ESR_Succeeded; 4128 } 4129 4130 case Stmt::IfStmtClass: { 4131 const IfStmt *IS = cast<IfStmt>(S); 4132 4133 // Evaluate the condition, as either a var decl or as an expression. 4134 BlockScopeRAII Scope(Info); 4135 if (const Stmt *Init = IS->getInit()) { 4136 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4137 if (ESR != ESR_Succeeded) 4138 return ESR; 4139 } 4140 bool Cond; 4141 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4142 return ESR_Failed; 4143 4144 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4145 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4146 if (ESR != ESR_Succeeded) 4147 return ESR; 4148 } 4149 return ESR_Succeeded; 4150 } 4151 4152 case Stmt::WhileStmtClass: { 4153 const WhileStmt *WS = cast<WhileStmt>(S); 4154 while (true) { 4155 BlockScopeRAII Scope(Info); 4156 bool Continue; 4157 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4158 Continue)) 4159 return ESR_Failed; 4160 if (!Continue) 4161 break; 4162 4163 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4164 if (ESR != ESR_Continue) 4165 return ESR; 4166 } 4167 return ESR_Succeeded; 4168 } 4169 4170 case Stmt::DoStmtClass: { 4171 const DoStmt *DS = cast<DoStmt>(S); 4172 bool Continue; 4173 do { 4174 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4175 if (ESR != ESR_Continue) 4176 return ESR; 4177 Case = nullptr; 4178 4179 FullExpressionRAII CondScope(Info); 4180 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 4181 return ESR_Failed; 4182 } while (Continue); 4183 return ESR_Succeeded; 4184 } 4185 4186 case Stmt::ForStmtClass: { 4187 const ForStmt *FS = cast<ForStmt>(S); 4188 BlockScopeRAII Scope(Info); 4189 if (FS->getInit()) { 4190 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4191 if (ESR != ESR_Succeeded) 4192 return ESR; 4193 } 4194 while (true) { 4195 BlockScopeRAII Scope(Info); 4196 bool Continue = true; 4197 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4198 FS->getCond(), Continue)) 4199 return ESR_Failed; 4200 if (!Continue) 4201 break; 4202 4203 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4204 if (ESR != ESR_Continue) 4205 return ESR; 4206 4207 if (FS->getInc()) { 4208 FullExpressionRAII IncScope(Info); 4209 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4210 return ESR_Failed; 4211 } 4212 } 4213 return ESR_Succeeded; 4214 } 4215 4216 case Stmt::CXXForRangeStmtClass: { 4217 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4218 BlockScopeRAII Scope(Info); 4219 4220 // Initialize the __range variable. 4221 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4222 if (ESR != ESR_Succeeded) 4223 return ESR; 4224 4225 // Create the __begin and __end iterators. 4226 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4227 if (ESR != ESR_Succeeded) 4228 return ESR; 4229 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4230 if (ESR != ESR_Succeeded) 4231 return ESR; 4232 4233 while (true) { 4234 // Condition: __begin != __end. 4235 { 4236 bool Continue = true; 4237 FullExpressionRAII CondExpr(Info); 4238 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4239 return ESR_Failed; 4240 if (!Continue) 4241 break; 4242 } 4243 4244 // User's variable declaration, initialized by *__begin. 4245 BlockScopeRAII InnerScope(Info); 4246 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4247 if (ESR != ESR_Succeeded) 4248 return ESR; 4249 4250 // Loop body. 4251 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4252 if (ESR != ESR_Continue) 4253 return ESR; 4254 4255 // Increment: ++__begin 4256 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4257 return ESR_Failed; 4258 } 4259 4260 return ESR_Succeeded; 4261 } 4262 4263 case Stmt::SwitchStmtClass: 4264 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4265 4266 case Stmt::ContinueStmtClass: 4267 return ESR_Continue; 4268 4269 case Stmt::BreakStmtClass: 4270 return ESR_Break; 4271 4272 case Stmt::LabelStmtClass: 4273 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4274 4275 case Stmt::AttributedStmtClass: 4276 // As a general principle, C++11 attributes can be ignored without 4277 // any semantic impact. 4278 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4279 Case); 4280 4281 case Stmt::CaseStmtClass: 4282 case Stmt::DefaultStmtClass: 4283 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4284 } 4285 } 4286 4287 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4288 /// default constructor. If so, we'll fold it whether or not it's marked as 4289 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4290 /// so we need special handling. 4291 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4292 const CXXConstructorDecl *CD, 4293 bool IsValueInitialization) { 4294 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4295 return false; 4296 4297 // Value-initialization does not call a trivial default constructor, so such a 4298 // call is a core constant expression whether or not the constructor is 4299 // constexpr. 4300 if (!CD->isConstexpr() && !IsValueInitialization) { 4301 if (Info.getLangOpts().CPlusPlus11) { 4302 // FIXME: If DiagDecl is an implicitly-declared special member function, 4303 // we should be much more explicit about why it's not constexpr. 4304 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4305 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4306 Info.Note(CD->getLocation(), diag::note_declared_at); 4307 } else { 4308 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4309 } 4310 } 4311 return true; 4312 } 4313 4314 /// CheckConstexprFunction - Check that a function can be called in a constant 4315 /// expression. 4316 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4317 const FunctionDecl *Declaration, 4318 const FunctionDecl *Definition, 4319 const Stmt *Body) { 4320 // Potential constant expressions can contain calls to declared, but not yet 4321 // defined, constexpr functions. 4322 if (Info.checkingPotentialConstantExpression() && !Definition && 4323 Declaration->isConstexpr()) 4324 return false; 4325 4326 // Bail out with no diagnostic if the function declaration itself is invalid. 4327 // We will have produced a relevant diagnostic while parsing it. 4328 if (Declaration->isInvalidDecl()) 4329 return false; 4330 4331 // Can we evaluate this function call? 4332 if (Definition && Definition->isConstexpr() && 4333 !Definition->isInvalidDecl() && Body) 4334 return true; 4335 4336 if (Info.getLangOpts().CPlusPlus11) { 4337 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4338 4339 // If this function is not constexpr because it is an inherited 4340 // non-constexpr constructor, diagnose that directly. 4341 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4342 if (CD && CD->isInheritingConstructor()) { 4343 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4344 if (!Inherited->isConstexpr()) 4345 DiagDecl = CD = Inherited; 4346 } 4347 4348 // FIXME: If DiagDecl is an implicitly-declared special member function 4349 // or an inheriting constructor, we should be much more explicit about why 4350 // it's not constexpr. 4351 if (CD && CD->isInheritingConstructor()) 4352 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4353 << CD->getInheritedConstructor().getConstructor()->getParent(); 4354 else 4355 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4356 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4357 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4358 } else { 4359 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4360 } 4361 return false; 4362 } 4363 4364 /// Determine if a class has any fields that might need to be copied by a 4365 /// trivial copy or move operation. 4366 static bool hasFields(const CXXRecordDecl *RD) { 4367 if (!RD || RD->isEmpty()) 4368 return false; 4369 for (auto *FD : RD->fields()) { 4370 if (FD->isUnnamedBitfield()) 4371 continue; 4372 return true; 4373 } 4374 for (auto &Base : RD->bases()) 4375 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 4376 return true; 4377 return false; 4378 } 4379 4380 namespace { 4381 typedef SmallVector<APValue, 8> ArgVector; 4382 } 4383 4384 /// EvaluateArgs - Evaluate the arguments to a function call. 4385 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 4386 EvalInfo &Info) { 4387 bool Success = true; 4388 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 4389 I != E; ++I) { 4390 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 4391 // If we're checking for a potential constant expression, evaluate all 4392 // initializers even if some of them fail. 4393 if (!Info.noteFailure()) 4394 return false; 4395 Success = false; 4396 } 4397 } 4398 return Success; 4399 } 4400 4401 /// Evaluate a function call. 4402 static bool HandleFunctionCall(SourceLocation CallLoc, 4403 const FunctionDecl *Callee, const LValue *This, 4404 ArrayRef<const Expr*> Args, const Stmt *Body, 4405 EvalInfo &Info, APValue &Result, 4406 const LValue *ResultSlot) { 4407 ArgVector ArgValues(Args.size()); 4408 if (!EvaluateArgs(Args, ArgValues, Info)) 4409 return false; 4410 4411 if (!Info.CheckCallLimit(CallLoc)) 4412 return false; 4413 4414 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 4415 4416 // For a trivial copy or move assignment, perform an APValue copy. This is 4417 // essential for unions, where the operations performed by the assignment 4418 // operator cannot be represented as statements. 4419 // 4420 // Skip this for non-union classes with no fields; in that case, the defaulted 4421 // copy/move does not actually read the object. 4422 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 4423 if (MD && MD->isDefaulted() && 4424 (MD->getParent()->isUnion() || 4425 (MD->isTrivial() && hasFields(MD->getParent())))) { 4426 assert(This && 4427 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 4428 LValue RHS; 4429 RHS.setFrom(Info.Ctx, ArgValues[0]); 4430 APValue RHSValue; 4431 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 4432 RHS, RHSValue)) 4433 return false; 4434 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx), 4435 RHSValue)) 4436 return false; 4437 This->moveInto(Result); 4438 return true; 4439 } else if (MD && isLambdaCallOperator(MD)) { 4440 // We're in a lambda; determine the lambda capture field maps unless we're 4441 // just constexpr checking a lambda's call operator. constexpr checking is 4442 // done before the captures have been added to the closure object (unless 4443 // we're inferring constexpr-ness), so we don't have access to them in this 4444 // case. But since we don't need the captures to constexpr check, we can 4445 // just ignore them. 4446 if (!Info.checkingPotentialConstantExpression()) 4447 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 4448 Frame.LambdaThisCaptureField); 4449 } 4450 4451 StmtResult Ret = {Result, ResultSlot}; 4452 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 4453 if (ESR == ESR_Succeeded) { 4454 if (Callee->getReturnType()->isVoidType()) 4455 return true; 4456 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 4457 } 4458 return ESR == ESR_Returned; 4459 } 4460 4461 /// Evaluate a constructor call. 4462 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4463 APValue *ArgValues, 4464 const CXXConstructorDecl *Definition, 4465 EvalInfo &Info, APValue &Result) { 4466 SourceLocation CallLoc = E->getExprLoc(); 4467 if (!Info.CheckCallLimit(CallLoc)) 4468 return false; 4469 4470 const CXXRecordDecl *RD = Definition->getParent(); 4471 if (RD->getNumVBases()) { 4472 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 4473 return false; 4474 } 4475 4476 EvalInfo::EvaluatingConstructorRAII EvalObj( 4477 Info, {This.getLValueBase(), 4478 {This.getLValueCallIndex(), This.getLValueVersion()}}); 4479 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 4480 4481 // FIXME: Creating an APValue just to hold a nonexistent return value is 4482 // wasteful. 4483 APValue RetVal; 4484 StmtResult Ret = {RetVal, nullptr}; 4485 4486 // If it's a delegating constructor, delegate. 4487 if (Definition->isDelegatingConstructor()) { 4488 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 4489 { 4490 FullExpressionRAII InitScope(Info); 4491 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 4492 return false; 4493 } 4494 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4495 } 4496 4497 // For a trivial copy or move constructor, perform an APValue copy. This is 4498 // essential for unions (or classes with anonymous union members), where the 4499 // operations performed by the constructor cannot be represented by 4500 // ctor-initializers. 4501 // 4502 // Skip this for empty non-union classes; we should not perform an 4503 // lvalue-to-rvalue conversion on them because their copy constructor does not 4504 // actually read them. 4505 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 4506 (Definition->getParent()->isUnion() || 4507 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 4508 LValue RHS; 4509 RHS.setFrom(Info.Ctx, ArgValues[0]); 4510 return handleLValueToRValueConversion( 4511 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 4512 RHS, Result); 4513 } 4514 4515 // Reserve space for the struct members. 4516 if (!RD->isUnion() && Result.isUninit()) 4517 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4518 std::distance(RD->field_begin(), RD->field_end())); 4519 4520 if (RD->isInvalidDecl()) return false; 4521 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 4522 4523 // A scope for temporaries lifetime-extended by reference members. 4524 BlockScopeRAII LifetimeExtendedScope(Info); 4525 4526 bool Success = true; 4527 unsigned BasesSeen = 0; 4528 #ifndef NDEBUG 4529 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 4530 #endif 4531 for (const auto *I : Definition->inits()) { 4532 LValue Subobject = This; 4533 LValue SubobjectParent = This; 4534 APValue *Value = &Result; 4535 4536 // Determine the subobject to initialize. 4537 FieldDecl *FD = nullptr; 4538 if (I->isBaseInitializer()) { 4539 QualType BaseType(I->getBaseClass(), 0); 4540 #ifndef NDEBUG 4541 // Non-virtual base classes are initialized in the order in the class 4542 // definition. We have already checked for virtual base classes. 4543 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 4544 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 4545 "base class initializers not in expected order"); 4546 ++BaseIt; 4547 #endif 4548 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 4549 BaseType->getAsCXXRecordDecl(), &Layout)) 4550 return false; 4551 Value = &Result.getStructBase(BasesSeen++); 4552 } else if ((FD = I->getMember())) { 4553 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 4554 return false; 4555 if (RD->isUnion()) { 4556 Result = APValue(FD); 4557 Value = &Result.getUnionValue(); 4558 } else { 4559 Value = &Result.getStructField(FD->getFieldIndex()); 4560 } 4561 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 4562 // Walk the indirect field decl's chain to find the object to initialize, 4563 // and make sure we've initialized every step along it. 4564 auto IndirectFieldChain = IFD->chain(); 4565 for (auto *C : IndirectFieldChain) { 4566 FD = cast<FieldDecl>(C); 4567 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 4568 // Switch the union field if it differs. This happens if we had 4569 // preceding zero-initialization, and we're now initializing a union 4570 // subobject other than the first. 4571 // FIXME: In this case, the values of the other subobjects are 4572 // specified, since zero-initialization sets all padding bits to zero. 4573 if (Value->isUninit() || 4574 (Value->isUnion() && Value->getUnionField() != FD)) { 4575 if (CD->isUnion()) 4576 *Value = APValue(FD); 4577 else 4578 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 4579 std::distance(CD->field_begin(), CD->field_end())); 4580 } 4581 // Store Subobject as its parent before updating it for the last element 4582 // in the chain. 4583 if (C == IndirectFieldChain.back()) 4584 SubobjectParent = Subobject; 4585 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 4586 return false; 4587 if (CD->isUnion()) 4588 Value = &Value->getUnionValue(); 4589 else 4590 Value = &Value->getStructField(FD->getFieldIndex()); 4591 } 4592 } else { 4593 llvm_unreachable("unknown base initializer kind"); 4594 } 4595 4596 // Need to override This for implicit field initializers as in this case 4597 // This refers to innermost anonymous struct/union containing initializer, 4598 // not to currently constructed class. 4599 const Expr *Init = I->getInit(); 4600 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 4601 isa<CXXDefaultInitExpr>(Init)); 4602 FullExpressionRAII InitScope(Info); 4603 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 4604 (FD && FD->isBitField() && 4605 !truncateBitfieldValue(Info, Init, *Value, FD))) { 4606 // If we're checking for a potential constant expression, evaluate all 4607 // initializers even if some of them fail. 4608 if (!Info.noteFailure()) 4609 return false; 4610 Success = false; 4611 } 4612 } 4613 4614 return Success && 4615 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4616 } 4617 4618 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4619 ArrayRef<const Expr*> Args, 4620 const CXXConstructorDecl *Definition, 4621 EvalInfo &Info, APValue &Result) { 4622 ArgVector ArgValues(Args.size()); 4623 if (!EvaluateArgs(Args, ArgValues, Info)) 4624 return false; 4625 4626 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 4627 Info, Result); 4628 } 4629 4630 //===----------------------------------------------------------------------===// 4631 // Generic Evaluation 4632 //===----------------------------------------------------------------------===// 4633 namespace { 4634 4635 template <class Derived> 4636 class ExprEvaluatorBase 4637 : public ConstStmtVisitor<Derived, bool> { 4638 private: 4639 Derived &getDerived() { return static_cast<Derived&>(*this); } 4640 bool DerivedSuccess(const APValue &V, const Expr *E) { 4641 return getDerived().Success(V, E); 4642 } 4643 bool DerivedZeroInitialization(const Expr *E) { 4644 return getDerived().ZeroInitialization(E); 4645 } 4646 4647 // Check whether a conditional operator with a non-constant condition is a 4648 // potential constant expression. If neither arm is a potential constant 4649 // expression, then the conditional operator is not either. 4650 template<typename ConditionalOperator> 4651 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 4652 assert(Info.checkingPotentialConstantExpression()); 4653 4654 // Speculatively evaluate both arms. 4655 SmallVector<PartialDiagnosticAt, 8> Diag; 4656 { 4657 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4658 StmtVisitorTy::Visit(E->getFalseExpr()); 4659 if (Diag.empty()) 4660 return; 4661 } 4662 4663 { 4664 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4665 Diag.clear(); 4666 StmtVisitorTy::Visit(E->getTrueExpr()); 4667 if (Diag.empty()) 4668 return; 4669 } 4670 4671 Error(E, diag::note_constexpr_conditional_never_const); 4672 } 4673 4674 4675 template<typename ConditionalOperator> 4676 bool HandleConditionalOperator(const ConditionalOperator *E) { 4677 bool BoolResult; 4678 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 4679 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 4680 CheckPotentialConstantConditional(E); 4681 return false; 4682 } 4683 if (Info.noteFailure()) { 4684 StmtVisitorTy::Visit(E->getTrueExpr()); 4685 StmtVisitorTy::Visit(E->getFalseExpr()); 4686 } 4687 return false; 4688 } 4689 4690 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 4691 return StmtVisitorTy::Visit(EvalExpr); 4692 } 4693 4694 protected: 4695 EvalInfo &Info; 4696 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 4697 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 4698 4699 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 4700 return Info.CCEDiag(E, D); 4701 } 4702 4703 bool ZeroInitialization(const Expr *E) { return Error(E); } 4704 4705 public: 4706 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 4707 4708 EvalInfo &getEvalInfo() { return Info; } 4709 4710 /// Report an evaluation error. This should only be called when an error is 4711 /// first discovered. When propagating an error, just return false. 4712 bool Error(const Expr *E, diag::kind D) { 4713 Info.FFDiag(E, D); 4714 return false; 4715 } 4716 bool Error(const Expr *E) { 4717 return Error(E, diag::note_invalid_subexpr_in_const_expr); 4718 } 4719 4720 bool VisitStmt(const Stmt *) { 4721 llvm_unreachable("Expression evaluator should not be called on stmts"); 4722 } 4723 bool VisitExpr(const Expr *E) { 4724 return Error(E); 4725 } 4726 4727 bool VisitParenExpr(const ParenExpr *E) 4728 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4729 bool VisitUnaryExtension(const UnaryOperator *E) 4730 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4731 bool VisitUnaryPlus(const UnaryOperator *E) 4732 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4733 bool VisitChooseExpr(const ChooseExpr *E) 4734 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 4735 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 4736 { return StmtVisitorTy::Visit(E->getResultExpr()); } 4737 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 4738 { return StmtVisitorTy::Visit(E->getReplacement()); } 4739 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 4740 TempVersionRAII RAII(*Info.CurrentCall); 4741 return StmtVisitorTy::Visit(E->getExpr()); 4742 } 4743 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 4744 TempVersionRAII RAII(*Info.CurrentCall); 4745 // The initializer may not have been parsed yet, or might be erroneous. 4746 if (!E->getExpr()) 4747 return Error(E); 4748 return StmtVisitorTy::Visit(E->getExpr()); 4749 } 4750 // We cannot create any objects for which cleanups are required, so there is 4751 // nothing to do here; all cleanups must come from unevaluated subexpressions. 4752 bool VisitExprWithCleanups(const ExprWithCleanups *E) 4753 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4754 4755 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 4756 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 4757 return static_cast<Derived*>(this)->VisitCastExpr(E); 4758 } 4759 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 4760 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 4761 return static_cast<Derived*>(this)->VisitCastExpr(E); 4762 } 4763 4764 bool VisitBinaryOperator(const BinaryOperator *E) { 4765 switch (E->getOpcode()) { 4766 default: 4767 return Error(E); 4768 4769 case BO_Comma: 4770 VisitIgnoredValue(E->getLHS()); 4771 return StmtVisitorTy::Visit(E->getRHS()); 4772 4773 case BO_PtrMemD: 4774 case BO_PtrMemI: { 4775 LValue Obj; 4776 if (!HandleMemberPointerAccess(Info, E, Obj)) 4777 return false; 4778 APValue Result; 4779 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 4780 return false; 4781 return DerivedSuccess(Result, E); 4782 } 4783 } 4784 } 4785 4786 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 4787 // Evaluate and cache the common expression. We treat it as a temporary, 4788 // even though it's not quite the same thing. 4789 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 4790 Info, E->getCommon())) 4791 return false; 4792 4793 return HandleConditionalOperator(E); 4794 } 4795 4796 bool VisitConditionalOperator(const ConditionalOperator *E) { 4797 bool IsBcpCall = false; 4798 // If the condition (ignoring parens) is a __builtin_constant_p call, 4799 // the result is a constant expression if it can be folded without 4800 // side-effects. This is an important GNU extension. See GCC PR38377 4801 // for discussion. 4802 if (const CallExpr *CallCE = 4803 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 4804 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 4805 IsBcpCall = true; 4806 4807 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 4808 // constant expression; we can't check whether it's potentially foldable. 4809 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 4810 return false; 4811 4812 FoldConstant Fold(Info, IsBcpCall); 4813 if (!HandleConditionalOperator(E)) { 4814 Fold.keepDiagnostics(); 4815 return false; 4816 } 4817 4818 return true; 4819 } 4820 4821 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 4822 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 4823 return DerivedSuccess(*Value, E); 4824 4825 const Expr *Source = E->getSourceExpr(); 4826 if (!Source) 4827 return Error(E); 4828 if (Source == E) { // sanity checking. 4829 assert(0 && "OpaqueValueExpr recursively refers to itself"); 4830 return Error(E); 4831 } 4832 return StmtVisitorTy::Visit(Source); 4833 } 4834 4835 bool VisitCallExpr(const CallExpr *E) { 4836 APValue Result; 4837 if (!handleCallExpr(E, Result, nullptr)) 4838 return false; 4839 return DerivedSuccess(Result, E); 4840 } 4841 4842 bool handleCallExpr(const CallExpr *E, APValue &Result, 4843 const LValue *ResultSlot) { 4844 const Expr *Callee = E->getCallee()->IgnoreParens(); 4845 QualType CalleeType = Callee->getType(); 4846 4847 const FunctionDecl *FD = nullptr; 4848 LValue *This = nullptr, ThisVal; 4849 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 4850 bool HasQualifier = false; 4851 4852 // Extract function decl and 'this' pointer from the callee. 4853 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 4854 const ValueDecl *Member = nullptr; 4855 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 4856 // Explicit bound member calls, such as x.f() or p->g(); 4857 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 4858 return false; 4859 Member = ME->getMemberDecl(); 4860 This = &ThisVal; 4861 HasQualifier = ME->hasQualifier(); 4862 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 4863 // Indirect bound member calls ('.*' or '->*'). 4864 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false); 4865 if (!Member) return false; 4866 This = &ThisVal; 4867 } else 4868 return Error(Callee); 4869 4870 FD = dyn_cast<FunctionDecl>(Member); 4871 if (!FD) 4872 return Error(Callee); 4873 } else if (CalleeType->isFunctionPointerType()) { 4874 LValue Call; 4875 if (!EvaluatePointer(Callee, Call, Info)) 4876 return false; 4877 4878 if (!Call.getLValueOffset().isZero()) 4879 return Error(Callee); 4880 FD = dyn_cast_or_null<FunctionDecl>( 4881 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 4882 if (!FD) 4883 return Error(Callee); 4884 // Don't call function pointers which have been cast to some other type. 4885 // Per DR (no number yet), the caller and callee can differ in noexcept. 4886 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 4887 CalleeType->getPointeeType(), FD->getType())) { 4888 return Error(E); 4889 } 4890 4891 // Overloaded operator calls to member functions are represented as normal 4892 // calls with '*this' as the first argument. 4893 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 4894 if (MD && !MD->isStatic()) { 4895 // FIXME: When selecting an implicit conversion for an overloaded 4896 // operator delete, we sometimes try to evaluate calls to conversion 4897 // operators without a 'this' parameter! 4898 if (Args.empty()) 4899 return Error(E); 4900 4901 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 4902 return false; 4903 This = &ThisVal; 4904 Args = Args.slice(1); 4905 } else if (MD && MD->isLambdaStaticInvoker()) { 4906 // Map the static invoker for the lambda back to the call operator. 4907 // Conveniently, we don't have to slice out the 'this' argument (as is 4908 // being done for the non-static case), since a static member function 4909 // doesn't have an implicit argument passed in. 4910 const CXXRecordDecl *ClosureClass = MD->getParent(); 4911 assert( 4912 ClosureClass->captures_begin() == ClosureClass->captures_end() && 4913 "Number of captures must be zero for conversion to function-ptr"); 4914 4915 const CXXMethodDecl *LambdaCallOp = 4916 ClosureClass->getLambdaCallOperator(); 4917 4918 // Set 'FD', the function that will be called below, to the call 4919 // operator. If the closure object represents a generic lambda, find 4920 // the corresponding specialization of the call operator. 4921 4922 if (ClosureClass->isGenericLambda()) { 4923 assert(MD->isFunctionTemplateSpecialization() && 4924 "A generic lambda's static-invoker function must be a " 4925 "template specialization"); 4926 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 4927 FunctionTemplateDecl *CallOpTemplate = 4928 LambdaCallOp->getDescribedFunctionTemplate(); 4929 void *InsertPos = nullptr; 4930 FunctionDecl *CorrespondingCallOpSpecialization = 4931 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 4932 assert(CorrespondingCallOpSpecialization && 4933 "We must always have a function call operator specialization " 4934 "that corresponds to our static invoker specialization"); 4935 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 4936 } else 4937 FD = LambdaCallOp; 4938 } 4939 4940 4941 } else 4942 return Error(E); 4943 4944 if (This && !This->checkSubobject(Info, E, CSK_This)) 4945 return false; 4946 4947 // DR1358 allows virtual constexpr functions in some cases. Don't allow 4948 // calls to such functions in constant expressions. 4949 if (This && !HasQualifier && 4950 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual()) 4951 return Error(E, diag::note_constexpr_virtual_call); 4952 4953 const FunctionDecl *Definition = nullptr; 4954 Stmt *Body = FD->getBody(Definition); 4955 4956 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 4957 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 4958 Result, ResultSlot)) 4959 return false; 4960 4961 return true; 4962 } 4963 4964 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 4965 return StmtVisitorTy::Visit(E->getInitializer()); 4966 } 4967 bool VisitInitListExpr(const InitListExpr *E) { 4968 if (E->getNumInits() == 0) 4969 return DerivedZeroInitialization(E); 4970 if (E->getNumInits() == 1) 4971 return StmtVisitorTy::Visit(E->getInit(0)); 4972 return Error(E); 4973 } 4974 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 4975 return DerivedZeroInitialization(E); 4976 } 4977 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 4978 return DerivedZeroInitialization(E); 4979 } 4980 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 4981 return DerivedZeroInitialization(E); 4982 } 4983 4984 /// A member expression where the object is a prvalue is itself a prvalue. 4985 bool VisitMemberExpr(const MemberExpr *E) { 4986 assert(!E->isArrow() && "missing call to bound member function?"); 4987 4988 APValue Val; 4989 if (!Evaluate(Val, Info, E->getBase())) 4990 return false; 4991 4992 QualType BaseTy = E->getBase()->getType(); 4993 4994 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 4995 if (!FD) return Error(E); 4996 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 4997 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 4998 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 4999 5000 CompleteObject Obj(&Val, BaseTy, true); 5001 SubobjectDesignator Designator(BaseTy); 5002 Designator.addDeclUnchecked(FD); 5003 5004 APValue Result; 5005 return extractSubobject(Info, E, Obj, Designator, Result) && 5006 DerivedSuccess(Result, E); 5007 } 5008 5009 bool VisitCastExpr(const CastExpr *E) { 5010 switch (E->getCastKind()) { 5011 default: 5012 break; 5013 5014 case CK_AtomicToNonAtomic: { 5015 APValue AtomicVal; 5016 // This does not need to be done in place even for class/array types: 5017 // atomic-to-non-atomic conversion implies copying the object 5018 // representation. 5019 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 5020 return false; 5021 return DerivedSuccess(AtomicVal, E); 5022 } 5023 5024 case CK_NoOp: 5025 case CK_UserDefinedConversion: 5026 return StmtVisitorTy::Visit(E->getSubExpr()); 5027 5028 case CK_LValueToRValue: { 5029 LValue LVal; 5030 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 5031 return false; 5032 APValue RVal; 5033 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5034 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5035 LVal, RVal)) 5036 return false; 5037 return DerivedSuccess(RVal, E); 5038 } 5039 } 5040 5041 return Error(E); 5042 } 5043 5044 bool VisitUnaryPostInc(const UnaryOperator *UO) { 5045 return VisitUnaryPostIncDec(UO); 5046 } 5047 bool VisitUnaryPostDec(const UnaryOperator *UO) { 5048 return VisitUnaryPostIncDec(UO); 5049 } 5050 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 5051 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5052 return Error(UO); 5053 5054 LValue LVal; 5055 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 5056 return false; 5057 APValue RVal; 5058 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 5059 UO->isIncrementOp(), &RVal)) 5060 return false; 5061 return DerivedSuccess(RVal, UO); 5062 } 5063 5064 bool VisitStmtExpr(const StmtExpr *E) { 5065 // We will have checked the full-expressions inside the statement expression 5066 // when they were completed, and don't need to check them again now. 5067 if (Info.checkingForOverflow()) 5068 return Error(E); 5069 5070 BlockScopeRAII Scope(Info); 5071 const CompoundStmt *CS = E->getSubStmt(); 5072 if (CS->body_empty()) 5073 return true; 5074 5075 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 5076 BE = CS->body_end(); 5077 /**/; ++BI) { 5078 if (BI + 1 == BE) { 5079 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 5080 if (!FinalExpr) { 5081 Info.FFDiag((*BI)->getBeginLoc(), 5082 diag::note_constexpr_stmt_expr_unsupported); 5083 return false; 5084 } 5085 return this->Visit(FinalExpr); 5086 } 5087 5088 APValue ReturnValue; 5089 StmtResult Result = { ReturnValue, nullptr }; 5090 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 5091 if (ESR != ESR_Succeeded) { 5092 // FIXME: If the statement-expression terminated due to 'return', 5093 // 'break', or 'continue', it would be nice to propagate that to 5094 // the outer statement evaluation rather than bailing out. 5095 if (ESR != ESR_Failed) 5096 Info.FFDiag((*BI)->getBeginLoc(), 5097 diag::note_constexpr_stmt_expr_unsupported); 5098 return false; 5099 } 5100 } 5101 5102 llvm_unreachable("Return from function from the loop above."); 5103 } 5104 5105 /// Visit a value which is evaluated, but whose value is ignored. 5106 void VisitIgnoredValue(const Expr *E) { 5107 EvaluateIgnoredValue(Info, E); 5108 } 5109 5110 /// Potentially visit a MemberExpr's base expression. 5111 void VisitIgnoredBaseExpression(const Expr *E) { 5112 // While MSVC doesn't evaluate the base expression, it does diagnose the 5113 // presence of side-effecting behavior. 5114 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 5115 return; 5116 VisitIgnoredValue(E); 5117 } 5118 }; 5119 5120 } // namespace 5121 5122 //===----------------------------------------------------------------------===// 5123 // Common base class for lvalue and temporary evaluation. 5124 //===----------------------------------------------------------------------===// 5125 namespace { 5126 template<class Derived> 5127 class LValueExprEvaluatorBase 5128 : public ExprEvaluatorBase<Derived> { 5129 protected: 5130 LValue &Result; 5131 bool InvalidBaseOK; 5132 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 5133 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 5134 5135 bool Success(APValue::LValueBase B) { 5136 Result.set(B); 5137 return true; 5138 } 5139 5140 bool evaluatePointer(const Expr *E, LValue &Result) { 5141 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 5142 } 5143 5144 public: 5145 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 5146 : ExprEvaluatorBaseTy(Info), Result(Result), 5147 InvalidBaseOK(InvalidBaseOK) {} 5148 5149 bool Success(const APValue &V, const Expr *E) { 5150 Result.setFrom(this->Info.Ctx, V); 5151 return true; 5152 } 5153 5154 bool VisitMemberExpr(const MemberExpr *E) { 5155 // Handle non-static data members. 5156 QualType BaseTy; 5157 bool EvalOK; 5158 if (E->isArrow()) { 5159 EvalOK = evaluatePointer(E->getBase(), Result); 5160 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 5161 } else if (E->getBase()->isRValue()) { 5162 assert(E->getBase()->getType()->isRecordType()); 5163 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 5164 BaseTy = E->getBase()->getType(); 5165 } else { 5166 EvalOK = this->Visit(E->getBase()); 5167 BaseTy = E->getBase()->getType(); 5168 } 5169 if (!EvalOK) { 5170 if (!InvalidBaseOK) 5171 return false; 5172 Result.setInvalid(E); 5173 return true; 5174 } 5175 5176 const ValueDecl *MD = E->getMemberDecl(); 5177 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 5178 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 5179 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 5180 (void)BaseTy; 5181 if (!HandleLValueMember(this->Info, E, Result, FD)) 5182 return false; 5183 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 5184 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 5185 return false; 5186 } else 5187 return this->Error(E); 5188 5189 if (MD->getType()->isReferenceType()) { 5190 APValue RefValue; 5191 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 5192 RefValue)) 5193 return false; 5194 return Success(RefValue, E); 5195 } 5196 return true; 5197 } 5198 5199 bool VisitBinaryOperator(const BinaryOperator *E) { 5200 switch (E->getOpcode()) { 5201 default: 5202 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5203 5204 case BO_PtrMemD: 5205 case BO_PtrMemI: 5206 return HandleMemberPointerAccess(this->Info, E, Result); 5207 } 5208 } 5209 5210 bool VisitCastExpr(const CastExpr *E) { 5211 switch (E->getCastKind()) { 5212 default: 5213 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5214 5215 case CK_DerivedToBase: 5216 case CK_UncheckedDerivedToBase: 5217 if (!this->Visit(E->getSubExpr())) 5218 return false; 5219 5220 // Now figure out the necessary offset to add to the base LV to get from 5221 // the derived class to the base class. 5222 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 5223 Result); 5224 } 5225 } 5226 }; 5227 } 5228 5229 //===----------------------------------------------------------------------===// 5230 // LValue Evaluation 5231 // 5232 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 5233 // function designators (in C), decl references to void objects (in C), and 5234 // temporaries (if building with -Wno-address-of-temporary). 5235 // 5236 // LValue evaluation produces values comprising a base expression of one of the 5237 // following types: 5238 // - Declarations 5239 // * VarDecl 5240 // * FunctionDecl 5241 // - Literals 5242 // * CompoundLiteralExpr in C (and in global scope in C++) 5243 // * StringLiteral 5244 // * CXXTypeidExpr 5245 // * PredefinedExpr 5246 // * ObjCStringLiteralExpr 5247 // * ObjCEncodeExpr 5248 // * AddrLabelExpr 5249 // * BlockExpr 5250 // * CallExpr for a MakeStringConstant builtin 5251 // - Locals and temporaries 5252 // * MaterializeTemporaryExpr 5253 // * Any Expr, with a CallIndex indicating the function in which the temporary 5254 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 5255 // from the AST (FIXME). 5256 // * A MaterializeTemporaryExpr that has static storage duration, with no 5257 // CallIndex, for a lifetime-extended temporary. 5258 // plus an offset in bytes. 5259 //===----------------------------------------------------------------------===// 5260 namespace { 5261 class LValueExprEvaluator 5262 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 5263 public: 5264 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 5265 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 5266 5267 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 5268 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 5269 5270 bool VisitDeclRefExpr(const DeclRefExpr *E); 5271 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 5272 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 5273 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 5274 bool VisitMemberExpr(const MemberExpr *E); 5275 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 5276 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 5277 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 5278 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 5279 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 5280 bool VisitUnaryDeref(const UnaryOperator *E); 5281 bool VisitUnaryReal(const UnaryOperator *E); 5282 bool VisitUnaryImag(const UnaryOperator *E); 5283 bool VisitUnaryPreInc(const UnaryOperator *UO) { 5284 return VisitUnaryPreIncDec(UO); 5285 } 5286 bool VisitUnaryPreDec(const UnaryOperator *UO) { 5287 return VisitUnaryPreIncDec(UO); 5288 } 5289 bool VisitBinAssign(const BinaryOperator *BO); 5290 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 5291 5292 bool VisitCastExpr(const CastExpr *E) { 5293 switch (E->getCastKind()) { 5294 default: 5295 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 5296 5297 case CK_LValueBitCast: 5298 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5299 if (!Visit(E->getSubExpr())) 5300 return false; 5301 Result.Designator.setInvalid(); 5302 return true; 5303 5304 case CK_BaseToDerived: 5305 if (!Visit(E->getSubExpr())) 5306 return false; 5307 return HandleBaseToDerivedCast(Info, E, Result); 5308 } 5309 } 5310 }; 5311 } // end anonymous namespace 5312 5313 /// Evaluate an expression as an lvalue. This can be legitimately called on 5314 /// expressions which are not glvalues, in three cases: 5315 /// * function designators in C, and 5316 /// * "extern void" objects 5317 /// * @selector() expressions in Objective-C 5318 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 5319 bool InvalidBaseOK) { 5320 assert(E->isGLValue() || E->getType()->isFunctionType() || 5321 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 5322 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5323 } 5324 5325 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 5326 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 5327 return Success(FD); 5328 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 5329 return VisitVarDecl(E, VD); 5330 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 5331 return Visit(BD->getBinding()); 5332 return Error(E); 5333 } 5334 5335 5336 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 5337 5338 // If we are within a lambda's call operator, check whether the 'VD' referred 5339 // to within 'E' actually represents a lambda-capture that maps to a 5340 // data-member/field within the closure object, and if so, evaluate to the 5341 // field or what the field refers to. 5342 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 5343 isa<DeclRefExpr>(E) && 5344 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 5345 // We don't always have a complete capture-map when checking or inferring if 5346 // the function call operator meets the requirements of a constexpr function 5347 // - but we don't need to evaluate the captures to determine constexprness 5348 // (dcl.constexpr C++17). 5349 if (Info.checkingPotentialConstantExpression()) 5350 return false; 5351 5352 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 5353 // Start with 'Result' referring to the complete closure object... 5354 Result = *Info.CurrentCall->This; 5355 // ... then update it to refer to the field of the closure object 5356 // that represents the capture. 5357 if (!HandleLValueMember(Info, E, Result, FD)) 5358 return false; 5359 // And if the field is of reference type, update 'Result' to refer to what 5360 // the field refers to. 5361 if (FD->getType()->isReferenceType()) { 5362 APValue RVal; 5363 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 5364 RVal)) 5365 return false; 5366 Result.setFrom(Info.Ctx, RVal); 5367 } 5368 return true; 5369 } 5370 } 5371 CallStackFrame *Frame = nullptr; 5372 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 5373 // Only if a local variable was declared in the function currently being 5374 // evaluated, do we expect to be able to find its value in the current 5375 // frame. (Otherwise it was likely declared in an enclosing context and 5376 // could either have a valid evaluatable value (for e.g. a constexpr 5377 // variable) or be ill-formed (and trigger an appropriate evaluation 5378 // diagnostic)). 5379 if (Info.CurrentCall->Callee && 5380 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 5381 Frame = Info.CurrentCall; 5382 } 5383 } 5384 5385 if (!VD->getType()->isReferenceType()) { 5386 if (Frame) { 5387 Result.set({VD, Frame->Index, 5388 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 5389 return true; 5390 } 5391 return Success(VD); 5392 } 5393 5394 APValue *V; 5395 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 5396 return false; 5397 if (V->isUninit()) { 5398 if (!Info.checkingPotentialConstantExpression()) 5399 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 5400 return false; 5401 } 5402 return Success(*V, E); 5403 } 5404 5405 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 5406 const MaterializeTemporaryExpr *E) { 5407 // Walk through the expression to find the materialized temporary itself. 5408 SmallVector<const Expr *, 2> CommaLHSs; 5409 SmallVector<SubobjectAdjustment, 2> Adjustments; 5410 const Expr *Inner = E->GetTemporaryExpr()-> 5411 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 5412 5413 // If we passed any comma operators, evaluate their LHSs. 5414 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 5415 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 5416 return false; 5417 5418 // A materialized temporary with static storage duration can appear within the 5419 // result of a constant expression evaluation, so we need to preserve its 5420 // value for use outside this evaluation. 5421 APValue *Value; 5422 if (E->getStorageDuration() == SD_Static) { 5423 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 5424 *Value = APValue(); 5425 Result.set(E); 5426 } else { 5427 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result, 5428 *Info.CurrentCall); 5429 } 5430 5431 QualType Type = Inner->getType(); 5432 5433 // Materialize the temporary itself. 5434 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 5435 (E->getStorageDuration() == SD_Static && 5436 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 5437 *Value = APValue(); 5438 return false; 5439 } 5440 5441 // Adjust our lvalue to refer to the desired subobject. 5442 for (unsigned I = Adjustments.size(); I != 0; /**/) { 5443 --I; 5444 switch (Adjustments[I].Kind) { 5445 case SubobjectAdjustment::DerivedToBaseAdjustment: 5446 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 5447 Type, Result)) 5448 return false; 5449 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 5450 break; 5451 5452 case SubobjectAdjustment::FieldAdjustment: 5453 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 5454 return false; 5455 Type = Adjustments[I].Field->getType(); 5456 break; 5457 5458 case SubobjectAdjustment::MemberPointerAdjustment: 5459 if (!HandleMemberPointerAccess(this->Info, Type, Result, 5460 Adjustments[I].Ptr.RHS)) 5461 return false; 5462 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 5463 break; 5464 } 5465 } 5466 5467 return true; 5468 } 5469 5470 bool 5471 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 5472 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 5473 "lvalue compound literal in c++?"); 5474 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 5475 // only see this when folding in C, so there's no standard to follow here. 5476 return Success(E); 5477 } 5478 5479 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 5480 if (!E->isPotentiallyEvaluated()) 5481 return Success(E); 5482 5483 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic) 5484 << E->getExprOperand()->getType() 5485 << E->getExprOperand()->getSourceRange(); 5486 return false; 5487 } 5488 5489 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 5490 return Success(E); 5491 } 5492 5493 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 5494 // Handle static data members. 5495 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 5496 VisitIgnoredBaseExpression(E->getBase()); 5497 return VisitVarDecl(E, VD); 5498 } 5499 5500 // Handle static member functions. 5501 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 5502 if (MD->isStatic()) { 5503 VisitIgnoredBaseExpression(E->getBase()); 5504 return Success(MD); 5505 } 5506 } 5507 5508 // Handle non-static data members. 5509 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 5510 } 5511 5512 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 5513 // FIXME: Deal with vectors as array subscript bases. 5514 if (E->getBase()->getType()->isVectorType()) 5515 return Error(E); 5516 5517 bool Success = true; 5518 if (!evaluatePointer(E->getBase(), Result)) { 5519 if (!Info.noteFailure()) 5520 return false; 5521 Success = false; 5522 } 5523 5524 APSInt Index; 5525 if (!EvaluateInteger(E->getIdx(), Index, Info)) 5526 return false; 5527 5528 return Success && 5529 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 5530 } 5531 5532 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 5533 return evaluatePointer(E->getSubExpr(), Result); 5534 } 5535 5536 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 5537 if (!Visit(E->getSubExpr())) 5538 return false; 5539 // __real is a no-op on scalar lvalues. 5540 if (E->getSubExpr()->getType()->isAnyComplexType()) 5541 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 5542 return true; 5543 } 5544 5545 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 5546 assert(E->getSubExpr()->getType()->isAnyComplexType() && 5547 "lvalue __imag__ on scalar?"); 5548 if (!Visit(E->getSubExpr())) 5549 return false; 5550 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 5551 return true; 5552 } 5553 5554 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 5555 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5556 return Error(UO); 5557 5558 if (!this->Visit(UO->getSubExpr())) 5559 return false; 5560 5561 return handleIncDec( 5562 this->Info, UO, Result, UO->getSubExpr()->getType(), 5563 UO->isIncrementOp(), nullptr); 5564 } 5565 5566 bool LValueExprEvaluator::VisitCompoundAssignOperator( 5567 const CompoundAssignOperator *CAO) { 5568 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5569 return Error(CAO); 5570 5571 APValue RHS; 5572 5573 // The overall lvalue result is the result of evaluating the LHS. 5574 if (!this->Visit(CAO->getLHS())) { 5575 if (Info.noteFailure()) 5576 Evaluate(RHS, this->Info, CAO->getRHS()); 5577 return false; 5578 } 5579 5580 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 5581 return false; 5582 5583 return handleCompoundAssignment( 5584 this->Info, CAO, 5585 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 5586 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 5587 } 5588 5589 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 5590 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5591 return Error(E); 5592 5593 APValue NewVal; 5594 5595 if (!this->Visit(E->getLHS())) { 5596 if (Info.noteFailure()) 5597 Evaluate(NewVal, this->Info, E->getRHS()); 5598 return false; 5599 } 5600 5601 if (!Evaluate(NewVal, this->Info, E->getRHS())) 5602 return false; 5603 5604 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 5605 NewVal); 5606 } 5607 5608 //===----------------------------------------------------------------------===// 5609 // Pointer Evaluation 5610 //===----------------------------------------------------------------------===// 5611 5612 /// Attempts to compute the number of bytes available at the pointer 5613 /// returned by a function with the alloc_size attribute. Returns true if we 5614 /// were successful. Places an unsigned number into `Result`. 5615 /// 5616 /// This expects the given CallExpr to be a call to a function with an 5617 /// alloc_size attribute. 5618 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5619 const CallExpr *Call, 5620 llvm::APInt &Result) { 5621 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 5622 5623 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 5624 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 5625 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 5626 if (Call->getNumArgs() <= SizeArgNo) 5627 return false; 5628 5629 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 5630 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects)) 5631 return false; 5632 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 5633 return false; 5634 Into = Into.zextOrSelf(BitsInSizeT); 5635 return true; 5636 }; 5637 5638 APSInt SizeOfElem; 5639 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 5640 return false; 5641 5642 if (!AllocSize->getNumElemsParam().isValid()) { 5643 Result = std::move(SizeOfElem); 5644 return true; 5645 } 5646 5647 APSInt NumberOfElems; 5648 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 5649 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 5650 return false; 5651 5652 bool Overflow; 5653 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 5654 if (Overflow) 5655 return false; 5656 5657 Result = std::move(BytesAvailable); 5658 return true; 5659 } 5660 5661 /// Convenience function. LVal's base must be a call to an alloc_size 5662 /// function. 5663 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5664 const LValue &LVal, 5665 llvm::APInt &Result) { 5666 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 5667 "Can't get the size of a non alloc_size function"); 5668 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 5669 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 5670 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 5671 } 5672 5673 /// Attempts to evaluate the given LValueBase as the result of a call to 5674 /// a function with the alloc_size attribute. If it was possible to do so, this 5675 /// function will return true, make Result's Base point to said function call, 5676 /// and mark Result's Base as invalid. 5677 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 5678 LValue &Result) { 5679 if (Base.isNull()) 5680 return false; 5681 5682 // Because we do no form of static analysis, we only support const variables. 5683 // 5684 // Additionally, we can't support parameters, nor can we support static 5685 // variables (in the latter case, use-before-assign isn't UB; in the former, 5686 // we have no clue what they'll be assigned to). 5687 const auto *VD = 5688 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 5689 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 5690 return false; 5691 5692 const Expr *Init = VD->getAnyInitializer(); 5693 if (!Init) 5694 return false; 5695 5696 const Expr *E = Init->IgnoreParens(); 5697 if (!tryUnwrapAllocSizeCall(E)) 5698 return false; 5699 5700 // Store E instead of E unwrapped so that the type of the LValue's base is 5701 // what the user wanted. 5702 Result.setInvalid(E); 5703 5704 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 5705 Result.addUnsizedArray(Info, E, Pointee); 5706 return true; 5707 } 5708 5709 namespace { 5710 class PointerExprEvaluator 5711 : public ExprEvaluatorBase<PointerExprEvaluator> { 5712 LValue &Result; 5713 bool InvalidBaseOK; 5714 5715 bool Success(const Expr *E) { 5716 Result.set(E); 5717 return true; 5718 } 5719 5720 bool evaluateLValue(const Expr *E, LValue &Result) { 5721 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 5722 } 5723 5724 bool evaluatePointer(const Expr *E, LValue &Result) { 5725 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 5726 } 5727 5728 bool visitNonBuiltinCallExpr(const CallExpr *E); 5729 public: 5730 5731 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 5732 : ExprEvaluatorBaseTy(info), Result(Result), 5733 InvalidBaseOK(InvalidBaseOK) {} 5734 5735 bool Success(const APValue &V, const Expr *E) { 5736 Result.setFrom(Info.Ctx, V); 5737 return true; 5738 } 5739 bool ZeroInitialization(const Expr *E) { 5740 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 5741 Result.setNull(E->getType(), TargetVal); 5742 return true; 5743 } 5744 5745 bool VisitBinaryOperator(const BinaryOperator *E); 5746 bool VisitCastExpr(const CastExpr* E); 5747 bool VisitUnaryAddrOf(const UnaryOperator *E); 5748 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 5749 { return Success(E); } 5750 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 5751 if (Info.noteFailure()) 5752 EvaluateIgnoredValue(Info, E->getSubExpr()); 5753 return Error(E); 5754 } 5755 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 5756 { return Success(E); } 5757 bool VisitCallExpr(const CallExpr *E); 5758 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 5759 bool VisitBlockExpr(const BlockExpr *E) { 5760 if (!E->getBlockDecl()->hasCaptures()) 5761 return Success(E); 5762 return Error(E); 5763 } 5764 bool VisitCXXThisExpr(const CXXThisExpr *E) { 5765 // Can't look at 'this' when checking a potential constant expression. 5766 if (Info.checkingPotentialConstantExpression()) 5767 return false; 5768 if (!Info.CurrentCall->This) { 5769 if (Info.getLangOpts().CPlusPlus11) 5770 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 5771 else 5772 Info.FFDiag(E); 5773 return false; 5774 } 5775 Result = *Info.CurrentCall->This; 5776 // If we are inside a lambda's call operator, the 'this' expression refers 5777 // to the enclosing '*this' object (either by value or reference) which is 5778 // either copied into the closure object's field that represents the '*this' 5779 // or refers to '*this'. 5780 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 5781 // Update 'Result' to refer to the data member/field of the closure object 5782 // that represents the '*this' capture. 5783 if (!HandleLValueMember(Info, E, Result, 5784 Info.CurrentCall->LambdaThisCaptureField)) 5785 return false; 5786 // If we captured '*this' by reference, replace the field with its referent. 5787 if (Info.CurrentCall->LambdaThisCaptureField->getType() 5788 ->isPointerType()) { 5789 APValue RVal; 5790 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 5791 RVal)) 5792 return false; 5793 5794 Result.setFrom(Info.Ctx, RVal); 5795 } 5796 } 5797 return true; 5798 } 5799 5800 // FIXME: Missing: @protocol, @selector 5801 }; 5802 } // end anonymous namespace 5803 5804 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 5805 bool InvalidBaseOK) { 5806 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 5807 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5808 } 5809 5810 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 5811 if (E->getOpcode() != BO_Add && 5812 E->getOpcode() != BO_Sub) 5813 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5814 5815 const Expr *PExp = E->getLHS(); 5816 const Expr *IExp = E->getRHS(); 5817 if (IExp->getType()->isPointerType()) 5818 std::swap(PExp, IExp); 5819 5820 bool EvalPtrOK = evaluatePointer(PExp, Result); 5821 if (!EvalPtrOK && !Info.noteFailure()) 5822 return false; 5823 5824 llvm::APSInt Offset; 5825 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 5826 return false; 5827 5828 if (E->getOpcode() == BO_Sub) 5829 negateAsSigned(Offset); 5830 5831 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 5832 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 5833 } 5834 5835 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 5836 return evaluateLValue(E->getSubExpr(), Result); 5837 } 5838 5839 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 5840 const Expr *SubExpr = E->getSubExpr(); 5841 5842 switch (E->getCastKind()) { 5843 default: 5844 break; 5845 5846 case CK_BitCast: 5847 case CK_CPointerToObjCPointerCast: 5848 case CK_BlockPointerToObjCPointerCast: 5849 case CK_AnyPointerToBlockPointerCast: 5850 case CK_AddressSpaceConversion: 5851 if (!Visit(SubExpr)) 5852 return false; 5853 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 5854 // permitted in constant expressions in C++11. Bitcasts from cv void* are 5855 // also static_casts, but we disallow them as a resolution to DR1312. 5856 if (!E->getType()->isVoidPointerType()) { 5857 // If we changed anything other than cvr-qualifiers, we can't use this 5858 // value for constant folding. FIXME: Qualification conversions should 5859 // always be CK_NoOp, but we get this wrong in C. 5860 if (!Info.Ctx.hasCvrSimilarType(E->getType(), E->getSubExpr()->getType())) 5861 Result.Designator.setInvalid(); 5862 if (SubExpr->getType()->isVoidPointerType()) 5863 CCEDiag(E, diag::note_constexpr_invalid_cast) 5864 << 3 << SubExpr->getType(); 5865 else 5866 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5867 } 5868 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 5869 ZeroInitialization(E); 5870 return true; 5871 5872 case CK_DerivedToBase: 5873 case CK_UncheckedDerivedToBase: 5874 if (!evaluatePointer(E->getSubExpr(), Result)) 5875 return false; 5876 if (!Result.Base && Result.Offset.isZero()) 5877 return true; 5878 5879 // Now figure out the necessary offset to add to the base LV to get from 5880 // the derived class to the base class. 5881 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 5882 castAs<PointerType>()->getPointeeType(), 5883 Result); 5884 5885 case CK_BaseToDerived: 5886 if (!Visit(E->getSubExpr())) 5887 return false; 5888 if (!Result.Base && Result.Offset.isZero()) 5889 return true; 5890 return HandleBaseToDerivedCast(Info, E, Result); 5891 5892 case CK_NullToPointer: 5893 VisitIgnoredValue(E->getSubExpr()); 5894 return ZeroInitialization(E); 5895 5896 case CK_IntegralToPointer: { 5897 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5898 5899 APValue Value; 5900 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 5901 break; 5902 5903 if (Value.isInt()) { 5904 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 5905 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 5906 Result.Base = (Expr*)nullptr; 5907 Result.InvalidBase = false; 5908 Result.Offset = CharUnits::fromQuantity(N); 5909 Result.Designator.setInvalid(); 5910 Result.IsNullPtr = false; 5911 return true; 5912 } else { 5913 // Cast is of an lvalue, no need to change value. 5914 Result.setFrom(Info.Ctx, Value); 5915 return true; 5916 } 5917 } 5918 5919 case CK_ArrayToPointerDecay: { 5920 if (SubExpr->isGLValue()) { 5921 if (!evaluateLValue(SubExpr, Result)) 5922 return false; 5923 } else { 5924 APValue &Value = createTemporary(SubExpr, false, Result, 5925 *Info.CurrentCall); 5926 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 5927 return false; 5928 } 5929 // The result is a pointer to the first element of the array. 5930 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 5931 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 5932 Result.addArray(Info, E, CAT); 5933 else 5934 Result.addUnsizedArray(Info, E, AT->getElementType()); 5935 return true; 5936 } 5937 5938 case CK_FunctionToPointerDecay: 5939 return evaluateLValue(SubExpr, Result); 5940 5941 case CK_LValueToRValue: { 5942 LValue LVal; 5943 if (!evaluateLValue(E->getSubExpr(), LVal)) 5944 return false; 5945 5946 APValue RVal; 5947 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5948 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5949 LVal, RVal)) 5950 return InvalidBaseOK && 5951 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 5952 return Success(RVal, E); 5953 } 5954 } 5955 5956 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5957 } 5958 5959 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) { 5960 // C++ [expr.alignof]p3: 5961 // When alignof is applied to a reference type, the result is the 5962 // alignment of the referenced type. 5963 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 5964 T = Ref->getPointeeType(); 5965 5966 // __alignof is defined to return the preferred alignment. 5967 if (T.getQualifiers().hasUnaligned()) 5968 return CharUnits::One(); 5969 return Info.Ctx.toCharUnitsFromBits( 5970 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 5971 } 5972 5973 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) { 5974 E = E->IgnoreParens(); 5975 5976 // The kinds of expressions that we have special-case logic here for 5977 // should be kept up to date with the special checks for those 5978 // expressions in Sema. 5979 5980 // alignof decl is always accepted, even if it doesn't make sense: we default 5981 // to 1 in those cases. 5982 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5983 return Info.Ctx.getDeclAlign(DRE->getDecl(), 5984 /*RefAsPointee*/true); 5985 5986 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 5987 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 5988 /*RefAsPointee*/true); 5989 5990 return GetAlignOfType(Info, E->getType()); 5991 } 5992 5993 // To be clear: this happily visits unsupported builtins. Better name welcomed. 5994 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 5995 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 5996 return true; 5997 5998 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 5999 return false; 6000 6001 Result.setInvalid(E); 6002 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 6003 Result.addUnsizedArray(Info, E, PointeeTy); 6004 return true; 6005 } 6006 6007 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 6008 if (IsStringLiteralCall(E)) 6009 return Success(E); 6010 6011 if (unsigned BuiltinOp = E->getBuiltinCallee()) 6012 return VisitBuiltinCallExpr(E, BuiltinOp); 6013 6014 return visitNonBuiltinCallExpr(E); 6015 } 6016 6017 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 6018 unsigned BuiltinOp) { 6019 switch (BuiltinOp) { 6020 case Builtin::BI__builtin_addressof: 6021 return evaluateLValue(E->getArg(0), Result); 6022 case Builtin::BI__builtin_assume_aligned: { 6023 // We need to be very careful here because: if the pointer does not have the 6024 // asserted alignment, then the behavior is undefined, and undefined 6025 // behavior is non-constant. 6026 if (!evaluatePointer(E->getArg(0), Result)) 6027 return false; 6028 6029 LValue OffsetResult(Result); 6030 APSInt Alignment; 6031 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 6032 return false; 6033 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 6034 6035 if (E->getNumArgs() > 2) { 6036 APSInt Offset; 6037 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 6038 return false; 6039 6040 int64_t AdditionalOffset = -Offset.getZExtValue(); 6041 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 6042 } 6043 6044 // If there is a base object, then it must have the correct alignment. 6045 if (OffsetResult.Base) { 6046 CharUnits BaseAlignment; 6047 if (const ValueDecl *VD = 6048 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 6049 BaseAlignment = Info.Ctx.getDeclAlign(VD); 6050 } else { 6051 BaseAlignment = 6052 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>()); 6053 } 6054 6055 if (BaseAlignment < Align) { 6056 Result.Designator.setInvalid(); 6057 // FIXME: Add support to Diagnostic for long / long long. 6058 CCEDiag(E->getArg(0), 6059 diag::note_constexpr_baa_insufficient_alignment) << 0 6060 << (unsigned)BaseAlignment.getQuantity() 6061 << (unsigned)Align.getQuantity(); 6062 return false; 6063 } 6064 } 6065 6066 // The offset must also have the correct alignment. 6067 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 6068 Result.Designator.setInvalid(); 6069 6070 (OffsetResult.Base 6071 ? CCEDiag(E->getArg(0), 6072 diag::note_constexpr_baa_insufficient_alignment) << 1 6073 : CCEDiag(E->getArg(0), 6074 diag::note_constexpr_baa_value_insufficient_alignment)) 6075 << (int)OffsetResult.Offset.getQuantity() 6076 << (unsigned)Align.getQuantity(); 6077 return false; 6078 } 6079 6080 return true; 6081 } 6082 6083 case Builtin::BIstrchr: 6084 case Builtin::BIwcschr: 6085 case Builtin::BImemchr: 6086 case Builtin::BIwmemchr: 6087 if (Info.getLangOpts().CPlusPlus11) 6088 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6089 << /*isConstexpr*/0 << /*isConstructor*/0 6090 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 6091 else 6092 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6093 LLVM_FALLTHROUGH; 6094 case Builtin::BI__builtin_strchr: 6095 case Builtin::BI__builtin_wcschr: 6096 case Builtin::BI__builtin_memchr: 6097 case Builtin::BI__builtin_char_memchr: 6098 case Builtin::BI__builtin_wmemchr: { 6099 if (!Visit(E->getArg(0))) 6100 return false; 6101 APSInt Desired; 6102 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 6103 return false; 6104 uint64_t MaxLength = uint64_t(-1); 6105 if (BuiltinOp != Builtin::BIstrchr && 6106 BuiltinOp != Builtin::BIwcschr && 6107 BuiltinOp != Builtin::BI__builtin_strchr && 6108 BuiltinOp != Builtin::BI__builtin_wcschr) { 6109 APSInt N; 6110 if (!EvaluateInteger(E->getArg(2), N, Info)) 6111 return false; 6112 MaxLength = N.getExtValue(); 6113 } 6114 6115 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 6116 6117 // Figure out what value we're actually looking for (after converting to 6118 // the corresponding unsigned type if necessary). 6119 uint64_t DesiredVal; 6120 bool StopAtNull = false; 6121 switch (BuiltinOp) { 6122 case Builtin::BIstrchr: 6123 case Builtin::BI__builtin_strchr: 6124 // strchr compares directly to the passed integer, and therefore 6125 // always fails if given an int that is not a char. 6126 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 6127 E->getArg(1)->getType(), 6128 Desired), 6129 Desired)) 6130 return ZeroInitialization(E); 6131 StopAtNull = true; 6132 LLVM_FALLTHROUGH; 6133 case Builtin::BImemchr: 6134 case Builtin::BI__builtin_memchr: 6135 case Builtin::BI__builtin_char_memchr: 6136 // memchr compares by converting both sides to unsigned char. That's also 6137 // correct for strchr if we get this far (to cope with plain char being 6138 // unsigned in the strchr case). 6139 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 6140 break; 6141 6142 case Builtin::BIwcschr: 6143 case Builtin::BI__builtin_wcschr: 6144 StopAtNull = true; 6145 LLVM_FALLTHROUGH; 6146 case Builtin::BIwmemchr: 6147 case Builtin::BI__builtin_wmemchr: 6148 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 6149 DesiredVal = Desired.getZExtValue(); 6150 break; 6151 } 6152 6153 for (; MaxLength; --MaxLength) { 6154 APValue Char; 6155 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 6156 !Char.isInt()) 6157 return false; 6158 if (Char.getInt().getZExtValue() == DesiredVal) 6159 return true; 6160 if (StopAtNull && !Char.getInt()) 6161 break; 6162 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 6163 return false; 6164 } 6165 // Not found: return nullptr. 6166 return ZeroInitialization(E); 6167 } 6168 6169 case Builtin::BImemcpy: 6170 case Builtin::BImemmove: 6171 case Builtin::BIwmemcpy: 6172 case Builtin::BIwmemmove: 6173 if (Info.getLangOpts().CPlusPlus11) 6174 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6175 << /*isConstexpr*/0 << /*isConstructor*/0 6176 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 6177 else 6178 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6179 LLVM_FALLTHROUGH; 6180 case Builtin::BI__builtin_memcpy: 6181 case Builtin::BI__builtin_memmove: 6182 case Builtin::BI__builtin_wmemcpy: 6183 case Builtin::BI__builtin_wmemmove: { 6184 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 6185 BuiltinOp == Builtin::BIwmemmove || 6186 BuiltinOp == Builtin::BI__builtin_wmemcpy || 6187 BuiltinOp == Builtin::BI__builtin_wmemmove; 6188 bool Move = BuiltinOp == Builtin::BImemmove || 6189 BuiltinOp == Builtin::BIwmemmove || 6190 BuiltinOp == Builtin::BI__builtin_memmove || 6191 BuiltinOp == Builtin::BI__builtin_wmemmove; 6192 6193 // The result of mem* is the first argument. 6194 if (!Visit(E->getArg(0)) || Result.Designator.Invalid) 6195 return false; 6196 LValue Dest = Result; 6197 6198 LValue Src; 6199 if (!EvaluatePointer(E->getArg(1), Src, Info) || Src.Designator.Invalid) 6200 return false; 6201 6202 APSInt N; 6203 if (!EvaluateInteger(E->getArg(2), N, Info)) 6204 return false; 6205 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 6206 6207 // If the size is zero, we treat this as always being a valid no-op. 6208 // (Even if one of the src and dest pointers is null.) 6209 if (!N) 6210 return true; 6211 6212 // We require that Src and Dest are both pointers to arrays of 6213 // trivially-copyable type. (For the wide version, the designator will be 6214 // invalid if the designated object is not a wchar_t.) 6215 QualType T = Dest.Designator.getType(Info.Ctx); 6216 QualType SrcT = Src.Designator.getType(Info.Ctx); 6217 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 6218 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 6219 return false; 6220 } 6221 if (!T.isTriviallyCopyableType(Info.Ctx)) { 6222 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 6223 return false; 6224 } 6225 6226 // Figure out how many T's we're copying. 6227 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 6228 if (!WChar) { 6229 uint64_t Remainder; 6230 llvm::APInt OrigN = N; 6231 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 6232 if (Remainder) { 6233 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 6234 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 6235 << (unsigned)TSize; 6236 return false; 6237 } 6238 } 6239 6240 // Check that the copying will remain within the arrays, just so that we 6241 // can give a more meaningful diagnostic. This implicitly also checks that 6242 // N fits into 64 bits. 6243 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 6244 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 6245 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 6246 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 6247 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 6248 << N.toString(10, /*Signed*/false); 6249 return false; 6250 } 6251 uint64_t NElems = N.getZExtValue(); 6252 uint64_t NBytes = NElems * TSize; 6253 6254 // Check for overlap. 6255 int Direction = 1; 6256 if (HasSameBase(Src, Dest)) { 6257 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 6258 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 6259 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 6260 // Dest is inside the source region. 6261 if (!Move) { 6262 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 6263 return false; 6264 } 6265 // For memmove and friends, copy backwards. 6266 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 6267 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 6268 return false; 6269 Direction = -1; 6270 } else if (!Move && SrcOffset >= DestOffset && 6271 SrcOffset - DestOffset < NBytes) { 6272 // Src is inside the destination region for memcpy: invalid. 6273 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 6274 return false; 6275 } 6276 } 6277 6278 while (true) { 6279 APValue Val; 6280 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 6281 !handleAssignment(Info, E, Dest, T, Val)) 6282 return false; 6283 // Do not iterate past the last element; if we're copying backwards, that 6284 // might take us off the start of the array. 6285 if (--NElems == 0) 6286 return true; 6287 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 6288 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 6289 return false; 6290 } 6291 } 6292 6293 default: 6294 return visitNonBuiltinCallExpr(E); 6295 } 6296 } 6297 6298 //===----------------------------------------------------------------------===// 6299 // Member Pointer Evaluation 6300 //===----------------------------------------------------------------------===// 6301 6302 namespace { 6303 class MemberPointerExprEvaluator 6304 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 6305 MemberPtr &Result; 6306 6307 bool Success(const ValueDecl *D) { 6308 Result = MemberPtr(D); 6309 return true; 6310 } 6311 public: 6312 6313 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 6314 : ExprEvaluatorBaseTy(Info), Result(Result) {} 6315 6316 bool Success(const APValue &V, const Expr *E) { 6317 Result.setFrom(V); 6318 return true; 6319 } 6320 bool ZeroInitialization(const Expr *E) { 6321 return Success((const ValueDecl*)nullptr); 6322 } 6323 6324 bool VisitCastExpr(const CastExpr *E); 6325 bool VisitUnaryAddrOf(const UnaryOperator *E); 6326 }; 6327 } // end anonymous namespace 6328 6329 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 6330 EvalInfo &Info) { 6331 assert(E->isRValue() && E->getType()->isMemberPointerType()); 6332 return MemberPointerExprEvaluator(Info, Result).Visit(E); 6333 } 6334 6335 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 6336 switch (E->getCastKind()) { 6337 default: 6338 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6339 6340 case CK_NullToMemberPointer: 6341 VisitIgnoredValue(E->getSubExpr()); 6342 return ZeroInitialization(E); 6343 6344 case CK_BaseToDerivedMemberPointer: { 6345 if (!Visit(E->getSubExpr())) 6346 return false; 6347 if (E->path_empty()) 6348 return true; 6349 // Base-to-derived member pointer casts store the path in derived-to-base 6350 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 6351 // the wrong end of the derived->base arc, so stagger the path by one class. 6352 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 6353 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 6354 PathI != PathE; ++PathI) { 6355 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6356 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 6357 if (!Result.castToDerived(Derived)) 6358 return Error(E); 6359 } 6360 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 6361 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 6362 return Error(E); 6363 return true; 6364 } 6365 6366 case CK_DerivedToBaseMemberPointer: 6367 if (!Visit(E->getSubExpr())) 6368 return false; 6369 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6370 PathE = E->path_end(); PathI != PathE; ++PathI) { 6371 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6372 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6373 if (!Result.castToBase(Base)) 6374 return Error(E); 6375 } 6376 return true; 6377 } 6378 } 6379 6380 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 6381 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 6382 // member can be formed. 6383 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 6384 } 6385 6386 //===----------------------------------------------------------------------===// 6387 // Record Evaluation 6388 //===----------------------------------------------------------------------===// 6389 6390 namespace { 6391 class RecordExprEvaluator 6392 : public ExprEvaluatorBase<RecordExprEvaluator> { 6393 const LValue &This; 6394 APValue &Result; 6395 public: 6396 6397 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 6398 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 6399 6400 bool Success(const APValue &V, const Expr *E) { 6401 Result = V; 6402 return true; 6403 } 6404 bool ZeroInitialization(const Expr *E) { 6405 return ZeroInitialization(E, E->getType()); 6406 } 6407 bool ZeroInitialization(const Expr *E, QualType T); 6408 6409 bool VisitCallExpr(const CallExpr *E) { 6410 return handleCallExpr(E, Result, &This); 6411 } 6412 bool VisitCastExpr(const CastExpr *E); 6413 bool VisitInitListExpr(const InitListExpr *E); 6414 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6415 return VisitCXXConstructExpr(E, E->getType()); 6416 } 6417 bool VisitLambdaExpr(const LambdaExpr *E); 6418 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 6419 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 6420 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 6421 6422 bool VisitBinCmp(const BinaryOperator *E); 6423 }; 6424 } 6425 6426 /// Perform zero-initialization on an object of non-union class type. 6427 /// C++11 [dcl.init]p5: 6428 /// To zero-initialize an object or reference of type T means: 6429 /// [...] 6430 /// -- if T is a (possibly cv-qualified) non-union class type, 6431 /// each non-static data member and each base-class subobject is 6432 /// zero-initialized 6433 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 6434 const RecordDecl *RD, 6435 const LValue &This, APValue &Result) { 6436 assert(!RD->isUnion() && "Expected non-union class type"); 6437 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 6438 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 6439 std::distance(RD->field_begin(), RD->field_end())); 6440 6441 if (RD->isInvalidDecl()) return false; 6442 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6443 6444 if (CD) { 6445 unsigned Index = 0; 6446 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 6447 End = CD->bases_end(); I != End; ++I, ++Index) { 6448 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 6449 LValue Subobject = This; 6450 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 6451 return false; 6452 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 6453 Result.getStructBase(Index))) 6454 return false; 6455 } 6456 } 6457 6458 for (const auto *I : RD->fields()) { 6459 // -- if T is a reference type, no initialization is performed. 6460 if (I->getType()->isReferenceType()) 6461 continue; 6462 6463 LValue Subobject = This; 6464 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 6465 return false; 6466 6467 ImplicitValueInitExpr VIE(I->getType()); 6468 if (!EvaluateInPlace( 6469 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 6470 return false; 6471 } 6472 6473 return true; 6474 } 6475 6476 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 6477 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 6478 if (RD->isInvalidDecl()) return false; 6479 if (RD->isUnion()) { 6480 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 6481 // object's first non-static named data member is zero-initialized 6482 RecordDecl::field_iterator I = RD->field_begin(); 6483 if (I == RD->field_end()) { 6484 Result = APValue((const FieldDecl*)nullptr); 6485 return true; 6486 } 6487 6488 LValue Subobject = This; 6489 if (!HandleLValueMember(Info, E, Subobject, *I)) 6490 return false; 6491 Result = APValue(*I); 6492 ImplicitValueInitExpr VIE(I->getType()); 6493 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 6494 } 6495 6496 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 6497 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 6498 return false; 6499 } 6500 6501 return HandleClassZeroInitialization(Info, E, RD, This, Result); 6502 } 6503 6504 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 6505 switch (E->getCastKind()) { 6506 default: 6507 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6508 6509 case CK_ConstructorConversion: 6510 return Visit(E->getSubExpr()); 6511 6512 case CK_DerivedToBase: 6513 case CK_UncheckedDerivedToBase: { 6514 APValue DerivedObject; 6515 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 6516 return false; 6517 if (!DerivedObject.isStruct()) 6518 return Error(E->getSubExpr()); 6519 6520 // Derived-to-base rvalue conversion: just slice off the derived part. 6521 APValue *Value = &DerivedObject; 6522 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 6523 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6524 PathE = E->path_end(); PathI != PathE; ++PathI) { 6525 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 6526 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6527 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 6528 RD = Base; 6529 } 6530 Result = *Value; 6531 return true; 6532 } 6533 } 6534 } 6535 6536 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6537 if (E->isTransparent()) 6538 return Visit(E->getInit(0)); 6539 6540 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 6541 if (RD->isInvalidDecl()) return false; 6542 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6543 6544 if (RD->isUnion()) { 6545 const FieldDecl *Field = E->getInitializedFieldInUnion(); 6546 Result = APValue(Field); 6547 if (!Field) 6548 return true; 6549 6550 // If the initializer list for a union does not contain any elements, the 6551 // first element of the union is value-initialized. 6552 // FIXME: The element should be initialized from an initializer list. 6553 // Is this difference ever observable for initializer lists which 6554 // we don't build? 6555 ImplicitValueInitExpr VIE(Field->getType()); 6556 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 6557 6558 LValue Subobject = This; 6559 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 6560 return false; 6561 6562 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6563 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6564 isa<CXXDefaultInitExpr>(InitExpr)); 6565 6566 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 6567 } 6568 6569 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 6570 if (Result.isUninit()) 6571 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 6572 std::distance(RD->field_begin(), RD->field_end())); 6573 unsigned ElementNo = 0; 6574 bool Success = true; 6575 6576 // Initialize base classes. 6577 if (CXXRD) { 6578 for (const auto &Base : CXXRD->bases()) { 6579 assert(ElementNo < E->getNumInits() && "missing init for base class"); 6580 const Expr *Init = E->getInit(ElementNo); 6581 6582 LValue Subobject = This; 6583 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 6584 return false; 6585 6586 APValue &FieldVal = Result.getStructBase(ElementNo); 6587 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 6588 if (!Info.noteFailure()) 6589 return false; 6590 Success = false; 6591 } 6592 ++ElementNo; 6593 } 6594 } 6595 6596 // Initialize members. 6597 for (const auto *Field : RD->fields()) { 6598 // Anonymous bit-fields are not considered members of the class for 6599 // purposes of aggregate initialization. 6600 if (Field->isUnnamedBitfield()) 6601 continue; 6602 6603 LValue Subobject = This; 6604 6605 bool HaveInit = ElementNo < E->getNumInits(); 6606 6607 // FIXME: Diagnostics here should point to the end of the initializer 6608 // list, not the start. 6609 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 6610 Subobject, Field, &Layout)) 6611 return false; 6612 6613 // Perform an implicit value-initialization for members beyond the end of 6614 // the initializer list. 6615 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 6616 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 6617 6618 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6619 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6620 isa<CXXDefaultInitExpr>(Init)); 6621 6622 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6623 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 6624 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 6625 FieldVal, Field))) { 6626 if (!Info.noteFailure()) 6627 return false; 6628 Success = false; 6629 } 6630 } 6631 6632 return Success; 6633 } 6634 6635 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 6636 QualType T) { 6637 // Note that E's type is not necessarily the type of our class here; we might 6638 // be initializing an array element instead. 6639 const CXXConstructorDecl *FD = E->getConstructor(); 6640 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 6641 6642 bool ZeroInit = E->requiresZeroInitialization(); 6643 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 6644 // If we've already performed zero-initialization, we're already done. 6645 if (!Result.isUninit()) 6646 return true; 6647 6648 // We can get here in two different ways: 6649 // 1) We're performing value-initialization, and should zero-initialize 6650 // the object, or 6651 // 2) We're performing default-initialization of an object with a trivial 6652 // constexpr default constructor, in which case we should start the 6653 // lifetimes of all the base subobjects (there can be no data member 6654 // subobjects in this case) per [basic.life]p1. 6655 // Either way, ZeroInitialization is appropriate. 6656 return ZeroInitialization(E, T); 6657 } 6658 6659 const FunctionDecl *Definition = nullptr; 6660 auto Body = FD->getBody(Definition); 6661 6662 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6663 return false; 6664 6665 // Avoid materializing a temporary for an elidable copy/move constructor. 6666 if (E->isElidable() && !ZeroInit) 6667 if (const MaterializeTemporaryExpr *ME 6668 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 6669 return Visit(ME->GetTemporaryExpr()); 6670 6671 if (ZeroInit && !ZeroInitialization(E, T)) 6672 return false; 6673 6674 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 6675 return HandleConstructorCall(E, This, Args, 6676 cast<CXXConstructorDecl>(Definition), Info, 6677 Result); 6678 } 6679 6680 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 6681 const CXXInheritedCtorInitExpr *E) { 6682 if (!Info.CurrentCall) { 6683 assert(Info.checkingPotentialConstantExpression()); 6684 return false; 6685 } 6686 6687 const CXXConstructorDecl *FD = E->getConstructor(); 6688 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 6689 return false; 6690 6691 const FunctionDecl *Definition = nullptr; 6692 auto Body = FD->getBody(Definition); 6693 6694 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6695 return false; 6696 6697 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 6698 cast<CXXConstructorDecl>(Definition), Info, 6699 Result); 6700 } 6701 6702 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 6703 const CXXStdInitializerListExpr *E) { 6704 const ConstantArrayType *ArrayType = 6705 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 6706 6707 LValue Array; 6708 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 6709 return false; 6710 6711 // Get a pointer to the first element of the array. 6712 Array.addArray(Info, E, ArrayType); 6713 6714 // FIXME: Perform the checks on the field types in SemaInit. 6715 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 6716 RecordDecl::field_iterator Field = Record->field_begin(); 6717 if (Field == Record->field_end()) 6718 return Error(E); 6719 6720 // Start pointer. 6721 if (!Field->getType()->isPointerType() || 6722 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6723 ArrayType->getElementType())) 6724 return Error(E); 6725 6726 // FIXME: What if the initializer_list type has base classes, etc? 6727 Result = APValue(APValue::UninitStruct(), 0, 2); 6728 Array.moveInto(Result.getStructField(0)); 6729 6730 if (++Field == Record->field_end()) 6731 return Error(E); 6732 6733 if (Field->getType()->isPointerType() && 6734 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6735 ArrayType->getElementType())) { 6736 // End pointer. 6737 if (!HandleLValueArrayAdjustment(Info, E, Array, 6738 ArrayType->getElementType(), 6739 ArrayType->getSize().getZExtValue())) 6740 return false; 6741 Array.moveInto(Result.getStructField(1)); 6742 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 6743 // Length. 6744 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 6745 else 6746 return Error(E); 6747 6748 if (++Field != Record->field_end()) 6749 return Error(E); 6750 6751 return true; 6752 } 6753 6754 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 6755 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 6756 if (ClosureClass->isInvalidDecl()) return false; 6757 6758 if (Info.checkingPotentialConstantExpression()) return true; 6759 6760 const size_t NumFields = 6761 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 6762 6763 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 6764 E->capture_init_end()) && 6765 "The number of lambda capture initializers should equal the number of " 6766 "fields within the closure type"); 6767 6768 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 6769 // Iterate through all the lambda's closure object's fields and initialize 6770 // them. 6771 auto *CaptureInitIt = E->capture_init_begin(); 6772 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 6773 bool Success = true; 6774 for (const auto *Field : ClosureClass->fields()) { 6775 assert(CaptureInitIt != E->capture_init_end()); 6776 // Get the initializer for this field 6777 Expr *const CurFieldInit = *CaptureInitIt++; 6778 6779 // If there is no initializer, either this is a VLA or an error has 6780 // occurred. 6781 if (!CurFieldInit) 6782 return Error(E); 6783 6784 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6785 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 6786 if (!Info.keepEvaluatingAfterFailure()) 6787 return false; 6788 Success = false; 6789 } 6790 ++CaptureIt; 6791 } 6792 return Success; 6793 } 6794 6795 static bool EvaluateRecord(const Expr *E, const LValue &This, 6796 APValue &Result, EvalInfo &Info) { 6797 assert(E->isRValue() && E->getType()->isRecordType() && 6798 "can't evaluate expression as a record rvalue"); 6799 return RecordExprEvaluator(Info, This, Result).Visit(E); 6800 } 6801 6802 //===----------------------------------------------------------------------===// 6803 // Temporary Evaluation 6804 // 6805 // Temporaries are represented in the AST as rvalues, but generally behave like 6806 // lvalues. The full-object of which the temporary is a subobject is implicitly 6807 // materialized so that a reference can bind to it. 6808 //===----------------------------------------------------------------------===// 6809 namespace { 6810 class TemporaryExprEvaluator 6811 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 6812 public: 6813 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 6814 LValueExprEvaluatorBaseTy(Info, Result, false) {} 6815 6816 /// Visit an expression which constructs the value of this temporary. 6817 bool VisitConstructExpr(const Expr *E) { 6818 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall); 6819 return EvaluateInPlace(Value, Info, Result, E); 6820 } 6821 6822 bool VisitCastExpr(const CastExpr *E) { 6823 switch (E->getCastKind()) { 6824 default: 6825 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 6826 6827 case CK_ConstructorConversion: 6828 return VisitConstructExpr(E->getSubExpr()); 6829 } 6830 } 6831 bool VisitInitListExpr(const InitListExpr *E) { 6832 return VisitConstructExpr(E); 6833 } 6834 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6835 return VisitConstructExpr(E); 6836 } 6837 bool VisitCallExpr(const CallExpr *E) { 6838 return VisitConstructExpr(E); 6839 } 6840 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 6841 return VisitConstructExpr(E); 6842 } 6843 bool VisitLambdaExpr(const LambdaExpr *E) { 6844 return VisitConstructExpr(E); 6845 } 6846 }; 6847 } // end anonymous namespace 6848 6849 /// Evaluate an expression of record type as a temporary. 6850 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 6851 assert(E->isRValue() && E->getType()->isRecordType()); 6852 return TemporaryExprEvaluator(Info, Result).Visit(E); 6853 } 6854 6855 //===----------------------------------------------------------------------===// 6856 // Vector Evaluation 6857 //===----------------------------------------------------------------------===// 6858 6859 namespace { 6860 class VectorExprEvaluator 6861 : public ExprEvaluatorBase<VectorExprEvaluator> { 6862 APValue &Result; 6863 public: 6864 6865 VectorExprEvaluator(EvalInfo &info, APValue &Result) 6866 : ExprEvaluatorBaseTy(info), Result(Result) {} 6867 6868 bool Success(ArrayRef<APValue> V, const Expr *E) { 6869 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 6870 // FIXME: remove this APValue copy. 6871 Result = APValue(V.data(), V.size()); 6872 return true; 6873 } 6874 bool Success(const APValue &V, const Expr *E) { 6875 assert(V.isVector()); 6876 Result = V; 6877 return true; 6878 } 6879 bool ZeroInitialization(const Expr *E); 6880 6881 bool VisitUnaryReal(const UnaryOperator *E) 6882 { return Visit(E->getSubExpr()); } 6883 bool VisitCastExpr(const CastExpr* E); 6884 bool VisitInitListExpr(const InitListExpr *E); 6885 bool VisitUnaryImag(const UnaryOperator *E); 6886 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 6887 // binary comparisons, binary and/or/xor, 6888 // shufflevector, ExtVectorElementExpr 6889 }; 6890 } // end anonymous namespace 6891 6892 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 6893 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 6894 return VectorExprEvaluator(Info, Result).Visit(E); 6895 } 6896 6897 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 6898 const VectorType *VTy = E->getType()->castAs<VectorType>(); 6899 unsigned NElts = VTy->getNumElements(); 6900 6901 const Expr *SE = E->getSubExpr(); 6902 QualType SETy = SE->getType(); 6903 6904 switch (E->getCastKind()) { 6905 case CK_VectorSplat: { 6906 APValue Val = APValue(); 6907 if (SETy->isIntegerType()) { 6908 APSInt IntResult; 6909 if (!EvaluateInteger(SE, IntResult, Info)) 6910 return false; 6911 Val = APValue(std::move(IntResult)); 6912 } else if (SETy->isRealFloatingType()) { 6913 APFloat FloatResult(0.0); 6914 if (!EvaluateFloat(SE, FloatResult, Info)) 6915 return false; 6916 Val = APValue(std::move(FloatResult)); 6917 } else { 6918 return Error(E); 6919 } 6920 6921 // Splat and create vector APValue. 6922 SmallVector<APValue, 4> Elts(NElts, Val); 6923 return Success(Elts, E); 6924 } 6925 case CK_BitCast: { 6926 // Evaluate the operand into an APInt we can extract from. 6927 llvm::APInt SValInt; 6928 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 6929 return false; 6930 // Extract the elements 6931 QualType EltTy = VTy->getElementType(); 6932 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 6933 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 6934 SmallVector<APValue, 4> Elts; 6935 if (EltTy->isRealFloatingType()) { 6936 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 6937 unsigned FloatEltSize = EltSize; 6938 if (&Sem == &APFloat::x87DoubleExtended()) 6939 FloatEltSize = 80; 6940 for (unsigned i = 0; i < NElts; i++) { 6941 llvm::APInt Elt; 6942 if (BigEndian) 6943 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 6944 else 6945 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 6946 Elts.push_back(APValue(APFloat(Sem, Elt))); 6947 } 6948 } else if (EltTy->isIntegerType()) { 6949 for (unsigned i = 0; i < NElts; i++) { 6950 llvm::APInt Elt; 6951 if (BigEndian) 6952 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 6953 else 6954 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 6955 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 6956 } 6957 } else { 6958 return Error(E); 6959 } 6960 return Success(Elts, E); 6961 } 6962 default: 6963 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6964 } 6965 } 6966 6967 bool 6968 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6969 const VectorType *VT = E->getType()->castAs<VectorType>(); 6970 unsigned NumInits = E->getNumInits(); 6971 unsigned NumElements = VT->getNumElements(); 6972 6973 QualType EltTy = VT->getElementType(); 6974 SmallVector<APValue, 4> Elements; 6975 6976 // The number of initializers can be less than the number of 6977 // vector elements. For OpenCL, this can be due to nested vector 6978 // initialization. For GCC compatibility, missing trailing elements 6979 // should be initialized with zeroes. 6980 unsigned CountInits = 0, CountElts = 0; 6981 while (CountElts < NumElements) { 6982 // Handle nested vector initialization. 6983 if (CountInits < NumInits 6984 && E->getInit(CountInits)->getType()->isVectorType()) { 6985 APValue v; 6986 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 6987 return Error(E); 6988 unsigned vlen = v.getVectorLength(); 6989 for (unsigned j = 0; j < vlen; j++) 6990 Elements.push_back(v.getVectorElt(j)); 6991 CountElts += vlen; 6992 } else if (EltTy->isIntegerType()) { 6993 llvm::APSInt sInt(32); 6994 if (CountInits < NumInits) { 6995 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 6996 return false; 6997 } else // trailing integer zero. 6998 sInt = Info.Ctx.MakeIntValue(0, EltTy); 6999 Elements.push_back(APValue(sInt)); 7000 CountElts++; 7001 } else { 7002 llvm::APFloat f(0.0); 7003 if (CountInits < NumInits) { 7004 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 7005 return false; 7006 } else // trailing float zero. 7007 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 7008 Elements.push_back(APValue(f)); 7009 CountElts++; 7010 } 7011 CountInits++; 7012 } 7013 return Success(Elements, E); 7014 } 7015 7016 bool 7017 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 7018 const VectorType *VT = E->getType()->getAs<VectorType>(); 7019 QualType EltTy = VT->getElementType(); 7020 APValue ZeroElement; 7021 if (EltTy->isIntegerType()) 7022 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 7023 else 7024 ZeroElement = 7025 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 7026 7027 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 7028 return Success(Elements, E); 7029 } 7030 7031 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 7032 VisitIgnoredValue(E->getSubExpr()); 7033 return ZeroInitialization(E); 7034 } 7035 7036 //===----------------------------------------------------------------------===// 7037 // Array Evaluation 7038 //===----------------------------------------------------------------------===// 7039 7040 namespace { 7041 class ArrayExprEvaluator 7042 : public ExprEvaluatorBase<ArrayExprEvaluator> { 7043 const LValue &This; 7044 APValue &Result; 7045 public: 7046 7047 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 7048 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 7049 7050 bool Success(const APValue &V, const Expr *E) { 7051 assert((V.isArray() || V.isLValue()) && 7052 "expected array or string literal"); 7053 Result = V; 7054 return true; 7055 } 7056 7057 bool ZeroInitialization(const Expr *E) { 7058 const ConstantArrayType *CAT = 7059 Info.Ctx.getAsConstantArrayType(E->getType()); 7060 if (!CAT) 7061 return Error(E); 7062 7063 Result = APValue(APValue::UninitArray(), 0, 7064 CAT->getSize().getZExtValue()); 7065 if (!Result.hasArrayFiller()) return true; 7066 7067 // Zero-initialize all elements. 7068 LValue Subobject = This; 7069 Subobject.addArray(Info, E, CAT); 7070 ImplicitValueInitExpr VIE(CAT->getElementType()); 7071 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 7072 } 7073 7074 bool VisitCallExpr(const CallExpr *E) { 7075 return handleCallExpr(E, Result, &This); 7076 } 7077 bool VisitInitListExpr(const InitListExpr *E); 7078 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 7079 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 7080 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 7081 const LValue &Subobject, 7082 APValue *Value, QualType Type); 7083 }; 7084 } // end anonymous namespace 7085 7086 static bool EvaluateArray(const Expr *E, const LValue &This, 7087 APValue &Result, EvalInfo &Info) { 7088 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 7089 return ArrayExprEvaluator(Info, This, Result).Visit(E); 7090 } 7091 7092 // Return true iff the given array filler may depend on the element index. 7093 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 7094 // For now, just whitelist non-class value-initialization and initialization 7095 // lists comprised of them. 7096 if (isa<ImplicitValueInitExpr>(FillerExpr)) 7097 return false; 7098 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 7099 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 7100 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 7101 return true; 7102 } 7103 return false; 7104 } 7105 return true; 7106 } 7107 7108 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7109 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 7110 if (!CAT) 7111 return Error(E); 7112 7113 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 7114 // an appropriately-typed string literal enclosed in braces. 7115 if (E->isStringLiteralInit()) { 7116 LValue LV; 7117 if (!EvaluateLValue(E->getInit(0), LV, Info)) 7118 return false; 7119 APValue Val; 7120 LV.moveInto(Val); 7121 return Success(Val, E); 7122 } 7123 7124 bool Success = true; 7125 7126 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 7127 "zero-initialized array shouldn't have any initialized elts"); 7128 APValue Filler; 7129 if (Result.isArray() && Result.hasArrayFiller()) 7130 Filler = Result.getArrayFiller(); 7131 7132 unsigned NumEltsToInit = E->getNumInits(); 7133 unsigned NumElts = CAT->getSize().getZExtValue(); 7134 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 7135 7136 // If the initializer might depend on the array index, run it for each 7137 // array element. 7138 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 7139 NumEltsToInit = NumElts; 7140 7141 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 7142 << NumEltsToInit << ".\n"); 7143 7144 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 7145 7146 // If the array was previously zero-initialized, preserve the 7147 // zero-initialized values. 7148 if (!Filler.isUninit()) { 7149 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 7150 Result.getArrayInitializedElt(I) = Filler; 7151 if (Result.hasArrayFiller()) 7152 Result.getArrayFiller() = Filler; 7153 } 7154 7155 LValue Subobject = This; 7156 Subobject.addArray(Info, E, CAT); 7157 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 7158 const Expr *Init = 7159 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 7160 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 7161 Info, Subobject, Init) || 7162 !HandleLValueArrayAdjustment(Info, Init, Subobject, 7163 CAT->getElementType(), 1)) { 7164 if (!Info.noteFailure()) 7165 return false; 7166 Success = false; 7167 } 7168 } 7169 7170 if (!Result.hasArrayFiller()) 7171 return Success; 7172 7173 // If we get here, we have a trivial filler, which we can just evaluate 7174 // once and splat over the rest of the array elements. 7175 assert(FillerExpr && "no array filler for incomplete init list"); 7176 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 7177 FillerExpr) && Success; 7178 } 7179 7180 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 7181 if (E->getCommonExpr() && 7182 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false), 7183 Info, E->getCommonExpr()->getSourceExpr())) 7184 return false; 7185 7186 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 7187 7188 uint64_t Elements = CAT->getSize().getZExtValue(); 7189 Result = APValue(APValue::UninitArray(), Elements, Elements); 7190 7191 LValue Subobject = This; 7192 Subobject.addArray(Info, E, CAT); 7193 7194 bool Success = true; 7195 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 7196 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 7197 Info, Subobject, E->getSubExpr()) || 7198 !HandleLValueArrayAdjustment(Info, E, Subobject, 7199 CAT->getElementType(), 1)) { 7200 if (!Info.noteFailure()) 7201 return false; 7202 Success = false; 7203 } 7204 } 7205 7206 return Success; 7207 } 7208 7209 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 7210 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 7211 } 7212 7213 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 7214 const LValue &Subobject, 7215 APValue *Value, 7216 QualType Type) { 7217 bool HadZeroInit = !Value->isUninit(); 7218 7219 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 7220 unsigned N = CAT->getSize().getZExtValue(); 7221 7222 // Preserve the array filler if we had prior zero-initialization. 7223 APValue Filler = 7224 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 7225 : APValue(); 7226 7227 *Value = APValue(APValue::UninitArray(), N, N); 7228 7229 if (HadZeroInit) 7230 for (unsigned I = 0; I != N; ++I) 7231 Value->getArrayInitializedElt(I) = Filler; 7232 7233 // Initialize the elements. 7234 LValue ArrayElt = Subobject; 7235 ArrayElt.addArray(Info, E, CAT); 7236 for (unsigned I = 0; I != N; ++I) 7237 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 7238 CAT->getElementType()) || 7239 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 7240 CAT->getElementType(), 1)) 7241 return false; 7242 7243 return true; 7244 } 7245 7246 if (!Type->isRecordType()) 7247 return Error(E); 7248 7249 return RecordExprEvaluator(Info, Subobject, *Value) 7250 .VisitCXXConstructExpr(E, Type); 7251 } 7252 7253 //===----------------------------------------------------------------------===// 7254 // Integer Evaluation 7255 // 7256 // As a GNU extension, we support casting pointers to sufficiently-wide integer 7257 // types and back in constant folding. Integer values are thus represented 7258 // either as an integer-valued APValue, or as an lvalue-valued APValue. 7259 //===----------------------------------------------------------------------===// 7260 7261 namespace { 7262 class IntExprEvaluator 7263 : public ExprEvaluatorBase<IntExprEvaluator> { 7264 APValue &Result; 7265 public: 7266 IntExprEvaluator(EvalInfo &info, APValue &result) 7267 : ExprEvaluatorBaseTy(info), Result(result) {} 7268 7269 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 7270 assert(E->getType()->isIntegralOrEnumerationType() && 7271 "Invalid evaluation result."); 7272 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 7273 "Invalid evaluation result."); 7274 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7275 "Invalid evaluation result."); 7276 Result = APValue(SI); 7277 return true; 7278 } 7279 bool Success(const llvm::APSInt &SI, const Expr *E) { 7280 return Success(SI, E, Result); 7281 } 7282 7283 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 7284 assert(E->getType()->isIntegralOrEnumerationType() && 7285 "Invalid evaluation result."); 7286 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7287 "Invalid evaluation result."); 7288 Result = APValue(APSInt(I)); 7289 Result.getInt().setIsUnsigned( 7290 E->getType()->isUnsignedIntegerOrEnumerationType()); 7291 return true; 7292 } 7293 bool Success(const llvm::APInt &I, const Expr *E) { 7294 return Success(I, E, Result); 7295 } 7296 7297 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 7298 assert(E->getType()->isIntegralOrEnumerationType() && 7299 "Invalid evaluation result."); 7300 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 7301 return true; 7302 } 7303 bool Success(uint64_t Value, const Expr *E) { 7304 return Success(Value, E, Result); 7305 } 7306 7307 bool Success(CharUnits Size, const Expr *E) { 7308 return Success(Size.getQuantity(), E); 7309 } 7310 7311 bool Success(const APValue &V, const Expr *E) { 7312 if (V.isLValue() || V.isAddrLabelDiff()) { 7313 Result = V; 7314 return true; 7315 } 7316 return Success(V.getInt(), E); 7317 } 7318 7319 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 7320 7321 //===--------------------------------------------------------------------===// 7322 // Visitor Methods 7323 //===--------------------------------------------------------------------===// 7324 7325 bool VisitIntegerLiteral(const IntegerLiteral *E) { 7326 return Success(E->getValue(), E); 7327 } 7328 bool VisitCharacterLiteral(const CharacterLiteral *E) { 7329 return Success(E->getValue(), E); 7330 } 7331 7332 bool CheckReferencedDecl(const Expr *E, const Decl *D); 7333 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7334 if (CheckReferencedDecl(E, E->getDecl())) 7335 return true; 7336 7337 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 7338 } 7339 bool VisitMemberExpr(const MemberExpr *E) { 7340 if (CheckReferencedDecl(E, E->getMemberDecl())) { 7341 VisitIgnoredBaseExpression(E->getBase()); 7342 return true; 7343 } 7344 7345 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 7346 } 7347 7348 bool VisitCallExpr(const CallExpr *E); 7349 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 7350 bool VisitBinaryOperator(const BinaryOperator *E); 7351 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 7352 bool VisitUnaryOperator(const UnaryOperator *E); 7353 7354 bool VisitCastExpr(const CastExpr* E); 7355 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 7356 7357 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 7358 return Success(E->getValue(), E); 7359 } 7360 7361 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 7362 return Success(E->getValue(), E); 7363 } 7364 7365 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 7366 if (Info.ArrayInitIndex == uint64_t(-1)) { 7367 // We were asked to evaluate this subexpression independent of the 7368 // enclosing ArrayInitLoopExpr. We can't do that. 7369 Info.FFDiag(E); 7370 return false; 7371 } 7372 return Success(Info.ArrayInitIndex, E); 7373 } 7374 7375 // Note, GNU defines __null as an integer, not a pointer. 7376 bool VisitGNUNullExpr(const GNUNullExpr *E) { 7377 return ZeroInitialization(E); 7378 } 7379 7380 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 7381 return Success(E->getValue(), E); 7382 } 7383 7384 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 7385 return Success(E->getValue(), E); 7386 } 7387 7388 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 7389 return Success(E->getValue(), E); 7390 } 7391 7392 bool VisitUnaryReal(const UnaryOperator *E); 7393 bool VisitUnaryImag(const UnaryOperator *E); 7394 7395 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 7396 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 7397 7398 // FIXME: Missing: array subscript of vector, member of vector 7399 }; 7400 7401 class FixedPointExprEvaluator 7402 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 7403 APValue &Result; 7404 7405 public: 7406 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 7407 : ExprEvaluatorBaseTy(info), Result(result) {} 7408 7409 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 7410 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7411 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() && 7412 "Invalid evaluation result."); 7413 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7414 "Invalid evaluation result."); 7415 Result = APValue(SI); 7416 return true; 7417 } 7418 bool Success(const llvm::APSInt &SI, const Expr *E) { 7419 return Success(SI, E, Result); 7420 } 7421 7422 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 7423 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7424 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7425 "Invalid evaluation result."); 7426 Result = APValue(APSInt(I)); 7427 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType()); 7428 return true; 7429 } 7430 bool Success(const llvm::APInt &I, const Expr *E) { 7431 return Success(I, E, Result); 7432 } 7433 7434 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 7435 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7436 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 7437 return true; 7438 } 7439 bool Success(uint64_t Value, const Expr *E) { 7440 return Success(Value, E, Result); 7441 } 7442 7443 bool Success(CharUnits Size, const Expr *E) { 7444 return Success(Size.getQuantity(), E); 7445 } 7446 7447 bool Success(const APValue &V, const Expr *E) { 7448 if (V.isLValue() || V.isAddrLabelDiff()) { 7449 Result = V; 7450 return true; 7451 } 7452 return Success(V.getInt(), E); 7453 } 7454 7455 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 7456 7457 //===--------------------------------------------------------------------===// 7458 // Visitor Methods 7459 //===--------------------------------------------------------------------===// 7460 7461 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 7462 return Success(E->getValue(), E); 7463 } 7464 7465 bool VisitUnaryOperator(const UnaryOperator *E); 7466 }; 7467 } // end anonymous namespace 7468 7469 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 7470 /// produce either the integer value or a pointer. 7471 /// 7472 /// GCC has a heinous extension which folds casts between pointer types and 7473 /// pointer-sized integral types. We support this by allowing the evaluation of 7474 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 7475 /// Some simple arithmetic on such values is supported (they are treated much 7476 /// like char*). 7477 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 7478 EvalInfo &Info) { 7479 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 7480 return IntExprEvaluator(Info, Result).Visit(E); 7481 } 7482 7483 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 7484 APValue Val; 7485 if (!EvaluateIntegerOrLValue(E, Val, Info)) 7486 return false; 7487 if (!Val.isInt()) { 7488 // FIXME: It would be better to produce the diagnostic for casting 7489 // a pointer to an integer. 7490 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 7491 return false; 7492 } 7493 Result = Val.getInt(); 7494 return true; 7495 } 7496 7497 /// Check whether the given declaration can be directly converted to an integral 7498 /// rvalue. If not, no diagnostic is produced; there are other things we can 7499 /// try. 7500 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 7501 // Enums are integer constant exprs. 7502 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 7503 // Check for signedness/width mismatches between E type and ECD value. 7504 bool SameSign = (ECD->getInitVal().isSigned() 7505 == E->getType()->isSignedIntegerOrEnumerationType()); 7506 bool SameWidth = (ECD->getInitVal().getBitWidth() 7507 == Info.Ctx.getIntWidth(E->getType())); 7508 if (SameSign && SameWidth) 7509 return Success(ECD->getInitVal(), E); 7510 else { 7511 // Get rid of mismatch (otherwise Success assertions will fail) 7512 // by computing a new value matching the type of E. 7513 llvm::APSInt Val = ECD->getInitVal(); 7514 if (!SameSign) 7515 Val.setIsSigned(!ECD->getInitVal().isSigned()); 7516 if (!SameWidth) 7517 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 7518 return Success(Val, E); 7519 } 7520 } 7521 return false; 7522 } 7523 7524 /// Values returned by __builtin_classify_type, chosen to match the values 7525 /// produced by GCC's builtin. 7526 enum class GCCTypeClass { 7527 None = -1, 7528 Void = 0, 7529 Integer = 1, 7530 // GCC reserves 2 for character types, but instead classifies them as 7531 // integers. 7532 Enum = 3, 7533 Bool = 4, 7534 Pointer = 5, 7535 // GCC reserves 6 for references, but appears to never use it (because 7536 // expressions never have reference type, presumably). 7537 PointerToDataMember = 7, 7538 RealFloat = 8, 7539 Complex = 9, 7540 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 7541 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 7542 // GCC claims to reserve 11 for pointers to member functions, but *actually* 7543 // uses 12 for that purpose, same as for a class or struct. Maybe it 7544 // internally implements a pointer to member as a struct? Who knows. 7545 PointerToMemberFunction = 12, // Not a bug, see above. 7546 ClassOrStruct = 12, 7547 Union = 13, 7548 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 7549 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 7550 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 7551 // literals. 7552 }; 7553 7554 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 7555 /// as GCC. 7556 static GCCTypeClass 7557 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 7558 assert(!T->isDependentType() && "unexpected dependent type"); 7559 7560 QualType CanTy = T.getCanonicalType(); 7561 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 7562 7563 switch (CanTy->getTypeClass()) { 7564 #define TYPE(ID, BASE) 7565 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 7566 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 7567 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 7568 #include "clang/AST/TypeNodes.def" 7569 case Type::Auto: 7570 case Type::DeducedTemplateSpecialization: 7571 llvm_unreachable("unexpected non-canonical or dependent type"); 7572 7573 case Type::Builtin: 7574 switch (BT->getKind()) { 7575 #define BUILTIN_TYPE(ID, SINGLETON_ID) 7576 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 7577 case BuiltinType::ID: return GCCTypeClass::Integer; 7578 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 7579 case BuiltinType::ID: return GCCTypeClass::RealFloat; 7580 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 7581 case BuiltinType::ID: break; 7582 #include "clang/AST/BuiltinTypes.def" 7583 case BuiltinType::Void: 7584 return GCCTypeClass::Void; 7585 7586 case BuiltinType::Bool: 7587 return GCCTypeClass::Bool; 7588 7589 case BuiltinType::Char_U: 7590 case BuiltinType::UChar: 7591 case BuiltinType::WChar_U: 7592 case BuiltinType::Char8: 7593 case BuiltinType::Char16: 7594 case BuiltinType::Char32: 7595 case BuiltinType::UShort: 7596 case BuiltinType::UInt: 7597 case BuiltinType::ULong: 7598 case BuiltinType::ULongLong: 7599 case BuiltinType::UInt128: 7600 return GCCTypeClass::Integer; 7601 7602 case BuiltinType::UShortAccum: 7603 case BuiltinType::UAccum: 7604 case BuiltinType::ULongAccum: 7605 case BuiltinType::UShortFract: 7606 case BuiltinType::UFract: 7607 case BuiltinType::ULongFract: 7608 case BuiltinType::SatUShortAccum: 7609 case BuiltinType::SatUAccum: 7610 case BuiltinType::SatULongAccum: 7611 case BuiltinType::SatUShortFract: 7612 case BuiltinType::SatUFract: 7613 case BuiltinType::SatULongFract: 7614 return GCCTypeClass::None; 7615 7616 case BuiltinType::NullPtr: 7617 7618 case BuiltinType::ObjCId: 7619 case BuiltinType::ObjCClass: 7620 case BuiltinType::ObjCSel: 7621 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7622 case BuiltinType::Id: 7623 #include "clang/Basic/OpenCLImageTypes.def" 7624 case BuiltinType::OCLSampler: 7625 case BuiltinType::OCLEvent: 7626 case BuiltinType::OCLClkEvent: 7627 case BuiltinType::OCLQueue: 7628 case BuiltinType::OCLReserveID: 7629 return GCCTypeClass::None; 7630 7631 case BuiltinType::Dependent: 7632 llvm_unreachable("unexpected dependent type"); 7633 }; 7634 llvm_unreachable("unexpected placeholder type"); 7635 7636 case Type::Enum: 7637 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 7638 7639 case Type::Pointer: 7640 case Type::ConstantArray: 7641 case Type::VariableArray: 7642 case Type::IncompleteArray: 7643 case Type::FunctionNoProto: 7644 case Type::FunctionProto: 7645 return GCCTypeClass::Pointer; 7646 7647 case Type::MemberPointer: 7648 return CanTy->isMemberDataPointerType() 7649 ? GCCTypeClass::PointerToDataMember 7650 : GCCTypeClass::PointerToMemberFunction; 7651 7652 case Type::Complex: 7653 return GCCTypeClass::Complex; 7654 7655 case Type::Record: 7656 return CanTy->isUnionType() ? GCCTypeClass::Union 7657 : GCCTypeClass::ClassOrStruct; 7658 7659 case Type::Atomic: 7660 // GCC classifies _Atomic T the same as T. 7661 return EvaluateBuiltinClassifyType( 7662 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 7663 7664 case Type::BlockPointer: 7665 case Type::Vector: 7666 case Type::ExtVector: 7667 case Type::ObjCObject: 7668 case Type::ObjCInterface: 7669 case Type::ObjCObjectPointer: 7670 case Type::Pipe: 7671 // GCC classifies vectors as None. We follow its lead and classify all 7672 // other types that don't fit into the regular classification the same way. 7673 return GCCTypeClass::None; 7674 7675 case Type::LValueReference: 7676 case Type::RValueReference: 7677 llvm_unreachable("invalid type for expression"); 7678 } 7679 7680 llvm_unreachable("unexpected type class"); 7681 } 7682 7683 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 7684 /// as GCC. 7685 static GCCTypeClass 7686 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 7687 // If no argument was supplied, default to None. This isn't 7688 // ideal, however it is what gcc does. 7689 if (E->getNumArgs() == 0) 7690 return GCCTypeClass::None; 7691 7692 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 7693 // being an ICE, but still folds it to a constant using the type of the first 7694 // argument. 7695 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 7696 } 7697 7698 /// EvaluateBuiltinConstantPForLValue - Determine the result of 7699 /// __builtin_constant_p when applied to the given lvalue. 7700 /// 7701 /// An lvalue is only "constant" if it is a pointer or reference to the first 7702 /// character of a string literal. 7703 template<typename LValue> 7704 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) { 7705 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>(); 7706 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero(); 7707 } 7708 7709 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 7710 /// GCC as we can manage. 7711 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) { 7712 QualType ArgType = Arg->getType(); 7713 7714 // __builtin_constant_p always has one operand. The rules which gcc follows 7715 // are not precisely documented, but are as follows: 7716 // 7717 // - If the operand is of integral, floating, complex or enumeration type, 7718 // and can be folded to a known value of that type, it returns 1. 7719 // - If the operand and can be folded to a pointer to the first character 7720 // of a string literal (or such a pointer cast to an integral type), it 7721 // returns 1. 7722 // 7723 // Otherwise, it returns 0. 7724 // 7725 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 7726 // its support for this does not currently work. 7727 if (ArgType->isIntegralOrEnumerationType()) { 7728 Expr::EvalResult Result; 7729 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects) 7730 return false; 7731 7732 APValue &V = Result.Val; 7733 if (V.getKind() == APValue::Int) 7734 return true; 7735 if (V.getKind() == APValue::LValue) 7736 return EvaluateBuiltinConstantPForLValue(V); 7737 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) { 7738 return Arg->isEvaluatable(Ctx); 7739 } else if (ArgType->isPointerType() || Arg->isGLValue()) { 7740 LValue LV; 7741 Expr::EvalStatus Status; 7742 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 7743 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info) 7744 : EvaluatePointer(Arg, LV, Info)) && 7745 !Status.HasSideEffects) 7746 return EvaluateBuiltinConstantPForLValue(LV); 7747 } 7748 7749 // Anything else isn't considered to be sufficiently constant. 7750 return false; 7751 } 7752 7753 /// Retrieves the "underlying object type" of the given expression, 7754 /// as used by __builtin_object_size. 7755 static QualType getObjectType(APValue::LValueBase B) { 7756 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 7757 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 7758 return VD->getType(); 7759 } else if (const Expr *E = B.get<const Expr*>()) { 7760 if (isa<CompoundLiteralExpr>(E)) 7761 return E->getType(); 7762 } 7763 7764 return QualType(); 7765 } 7766 7767 /// A more selective version of E->IgnoreParenCasts for 7768 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 7769 /// to change the type of E. 7770 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 7771 /// 7772 /// Always returns an RValue with a pointer representation. 7773 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 7774 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 7775 7776 auto *NoParens = E->IgnoreParens(); 7777 auto *Cast = dyn_cast<CastExpr>(NoParens); 7778 if (Cast == nullptr) 7779 return NoParens; 7780 7781 // We only conservatively allow a few kinds of casts, because this code is 7782 // inherently a simple solution that seeks to support the common case. 7783 auto CastKind = Cast->getCastKind(); 7784 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 7785 CastKind != CK_AddressSpaceConversion) 7786 return NoParens; 7787 7788 auto *SubExpr = Cast->getSubExpr(); 7789 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 7790 return NoParens; 7791 return ignorePointerCastsAndParens(SubExpr); 7792 } 7793 7794 /// Checks to see if the given LValue's Designator is at the end of the LValue's 7795 /// record layout. e.g. 7796 /// struct { struct { int a, b; } fst, snd; } obj; 7797 /// obj.fst // no 7798 /// obj.snd // yes 7799 /// obj.fst.a // no 7800 /// obj.fst.b // no 7801 /// obj.snd.a // no 7802 /// obj.snd.b // yes 7803 /// 7804 /// Please note: this function is specialized for how __builtin_object_size 7805 /// views "objects". 7806 /// 7807 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 7808 /// correct result, it will always return true. 7809 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 7810 assert(!LVal.Designator.Invalid); 7811 7812 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 7813 const RecordDecl *Parent = FD->getParent(); 7814 Invalid = Parent->isInvalidDecl(); 7815 if (Invalid || Parent->isUnion()) 7816 return true; 7817 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 7818 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 7819 }; 7820 7821 auto &Base = LVal.getLValueBase(); 7822 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 7823 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 7824 bool Invalid; 7825 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7826 return Invalid; 7827 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 7828 for (auto *FD : IFD->chain()) { 7829 bool Invalid; 7830 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 7831 return Invalid; 7832 } 7833 } 7834 } 7835 7836 unsigned I = 0; 7837 QualType BaseType = getType(Base); 7838 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 7839 // If we don't know the array bound, conservatively assume we're looking at 7840 // the final array element. 7841 ++I; 7842 if (BaseType->isIncompleteArrayType()) 7843 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 7844 else 7845 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 7846 } 7847 7848 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 7849 const auto &Entry = LVal.Designator.Entries[I]; 7850 if (BaseType->isArrayType()) { 7851 // Because __builtin_object_size treats arrays as objects, we can ignore 7852 // the index iff this is the last array in the Designator. 7853 if (I + 1 == E) 7854 return true; 7855 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 7856 uint64_t Index = Entry.ArrayIndex; 7857 if (Index + 1 != CAT->getSize()) 7858 return false; 7859 BaseType = CAT->getElementType(); 7860 } else if (BaseType->isAnyComplexType()) { 7861 const auto *CT = BaseType->castAs<ComplexType>(); 7862 uint64_t Index = Entry.ArrayIndex; 7863 if (Index != 1) 7864 return false; 7865 BaseType = CT->getElementType(); 7866 } else if (auto *FD = getAsField(Entry)) { 7867 bool Invalid; 7868 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7869 return Invalid; 7870 BaseType = FD->getType(); 7871 } else { 7872 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 7873 return false; 7874 } 7875 } 7876 return true; 7877 } 7878 7879 /// Tests to see if the LValue has a user-specified designator (that isn't 7880 /// necessarily valid). Note that this always returns 'true' if the LValue has 7881 /// an unsized array as its first designator entry, because there's currently no 7882 /// way to tell if the user typed *foo or foo[0]. 7883 static bool refersToCompleteObject(const LValue &LVal) { 7884 if (LVal.Designator.Invalid) 7885 return false; 7886 7887 if (!LVal.Designator.Entries.empty()) 7888 return LVal.Designator.isMostDerivedAnUnsizedArray(); 7889 7890 if (!LVal.InvalidBase) 7891 return true; 7892 7893 // If `E` is a MemberExpr, then the first part of the designator is hiding in 7894 // the LValueBase. 7895 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 7896 return !E || !isa<MemberExpr>(E); 7897 } 7898 7899 /// Attempts to detect a user writing into a piece of memory that's impossible 7900 /// to figure out the size of by just using types. 7901 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 7902 const SubobjectDesignator &Designator = LVal.Designator; 7903 // Notes: 7904 // - Users can only write off of the end when we have an invalid base. Invalid 7905 // bases imply we don't know where the memory came from. 7906 // - We used to be a bit more aggressive here; we'd only be conservative if 7907 // the array at the end was flexible, or if it had 0 or 1 elements. This 7908 // broke some common standard library extensions (PR30346), but was 7909 // otherwise seemingly fine. It may be useful to reintroduce this behavior 7910 // with some sort of whitelist. OTOH, it seems that GCC is always 7911 // conservative with the last element in structs (if it's an array), so our 7912 // current behavior is more compatible than a whitelisting approach would 7913 // be. 7914 return LVal.InvalidBase && 7915 Designator.Entries.size() == Designator.MostDerivedPathLength && 7916 Designator.MostDerivedIsArrayElement && 7917 isDesignatorAtObjectEnd(Ctx, LVal); 7918 } 7919 7920 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 7921 /// Fails if the conversion would cause loss of precision. 7922 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 7923 CharUnits &Result) { 7924 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 7925 if (Int.ugt(CharUnitsMax)) 7926 return false; 7927 Result = CharUnits::fromQuantity(Int.getZExtValue()); 7928 return true; 7929 } 7930 7931 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 7932 /// determine how many bytes exist from the beginning of the object to either 7933 /// the end of the current subobject, or the end of the object itself, depending 7934 /// on what the LValue looks like + the value of Type. 7935 /// 7936 /// If this returns false, the value of Result is undefined. 7937 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 7938 unsigned Type, const LValue &LVal, 7939 CharUnits &EndOffset) { 7940 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 7941 7942 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 7943 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 7944 return false; 7945 return HandleSizeof(Info, ExprLoc, Ty, Result); 7946 }; 7947 7948 // We want to evaluate the size of the entire object. This is a valid fallback 7949 // for when Type=1 and the designator is invalid, because we're asked for an 7950 // upper-bound. 7951 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 7952 // Type=3 wants a lower bound, so we can't fall back to this. 7953 if (Type == 3 && !DetermineForCompleteObject) 7954 return false; 7955 7956 llvm::APInt APEndOffset; 7957 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7958 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 7959 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 7960 7961 if (LVal.InvalidBase) 7962 return false; 7963 7964 QualType BaseTy = getObjectType(LVal.getLValueBase()); 7965 return CheckedHandleSizeof(BaseTy, EndOffset); 7966 } 7967 7968 // We want to evaluate the size of a subobject. 7969 const SubobjectDesignator &Designator = LVal.Designator; 7970 7971 // The following is a moderately common idiom in C: 7972 // 7973 // struct Foo { int a; char c[1]; }; 7974 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 7975 // strcpy(&F->c[0], Bar); 7976 // 7977 // In order to not break too much legacy code, we need to support it. 7978 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 7979 // If we can resolve this to an alloc_size call, we can hand that back, 7980 // because we know for certain how many bytes there are to write to. 7981 llvm::APInt APEndOffset; 7982 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7983 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 7984 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 7985 7986 // If we cannot determine the size of the initial allocation, then we can't 7987 // given an accurate upper-bound. However, we are still able to give 7988 // conservative lower-bounds for Type=3. 7989 if (Type == 1) 7990 return false; 7991 } 7992 7993 CharUnits BytesPerElem; 7994 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 7995 return false; 7996 7997 // According to the GCC documentation, we want the size of the subobject 7998 // denoted by the pointer. But that's not quite right -- what we actually 7999 // want is the size of the immediately-enclosing array, if there is one. 8000 int64_t ElemsRemaining; 8001 if (Designator.MostDerivedIsArrayElement && 8002 Designator.Entries.size() == Designator.MostDerivedPathLength) { 8003 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 8004 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex; 8005 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 8006 } else { 8007 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 8008 } 8009 8010 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 8011 return true; 8012 } 8013 8014 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 8015 /// returns true and stores the result in @p Size. 8016 /// 8017 /// If @p WasError is non-null, this will report whether the failure to evaluate 8018 /// is to be treated as an Error in IntExprEvaluator. 8019 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 8020 EvalInfo &Info, uint64_t &Size) { 8021 // Determine the denoted object. 8022 LValue LVal; 8023 { 8024 // The operand of __builtin_object_size is never evaluated for side-effects. 8025 // If there are any, but we can determine the pointed-to object anyway, then 8026 // ignore the side-effects. 8027 SpeculativeEvaluationRAII SpeculativeEval(Info); 8028 FoldOffsetRAII Fold(Info); 8029 8030 if (E->isGLValue()) { 8031 // It's possible for us to be given GLValues if we're called via 8032 // Expr::tryEvaluateObjectSize. 8033 APValue RVal; 8034 if (!EvaluateAsRValue(Info, E, RVal)) 8035 return false; 8036 LVal.setFrom(Info.Ctx, RVal); 8037 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 8038 /*InvalidBaseOK=*/true)) 8039 return false; 8040 } 8041 8042 // If we point to before the start of the object, there are no accessible 8043 // bytes. 8044 if (LVal.getLValueOffset().isNegative()) { 8045 Size = 0; 8046 return true; 8047 } 8048 8049 CharUnits EndOffset; 8050 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 8051 return false; 8052 8053 // If we've fallen outside of the end offset, just pretend there's nothing to 8054 // write to/read from. 8055 if (EndOffset <= LVal.getLValueOffset()) 8056 Size = 0; 8057 else 8058 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 8059 return true; 8060 } 8061 8062 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 8063 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8064 return VisitBuiltinCallExpr(E, BuiltinOp); 8065 8066 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8067 } 8068 8069 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8070 unsigned BuiltinOp) { 8071 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 8072 default: 8073 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8074 8075 case Builtin::BI__builtin_object_size: { 8076 // The type was checked when we built the expression. 8077 unsigned Type = 8078 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 8079 assert(Type <= 3 && "unexpected type"); 8080 8081 uint64_t Size; 8082 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 8083 return Success(Size, E); 8084 8085 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 8086 return Success((Type & 2) ? 0 : -1, E); 8087 8088 // Expression had no side effects, but we couldn't statically determine the 8089 // size of the referenced object. 8090 switch (Info.EvalMode) { 8091 case EvalInfo::EM_ConstantExpression: 8092 case EvalInfo::EM_PotentialConstantExpression: 8093 case EvalInfo::EM_ConstantFold: 8094 case EvalInfo::EM_EvaluateForOverflow: 8095 case EvalInfo::EM_IgnoreSideEffects: 8096 case EvalInfo::EM_OffsetFold: 8097 // Leave it to IR generation. 8098 return Error(E); 8099 case EvalInfo::EM_ConstantExpressionUnevaluated: 8100 case EvalInfo::EM_PotentialConstantExpressionUnevaluated: 8101 // Reduce it to a constant now. 8102 return Success((Type & 2) ? 0 : -1, E); 8103 } 8104 8105 llvm_unreachable("unexpected EvalMode"); 8106 } 8107 8108 case Builtin::BI__builtin_bswap16: 8109 case Builtin::BI__builtin_bswap32: 8110 case Builtin::BI__builtin_bswap64: { 8111 APSInt Val; 8112 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8113 return false; 8114 8115 return Success(Val.byteSwap(), E); 8116 } 8117 8118 case Builtin::BI__builtin_classify_type: 8119 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 8120 8121 case Builtin::BI__builtin_clrsb: 8122 case Builtin::BI__builtin_clrsbl: 8123 case Builtin::BI__builtin_clrsbll: { 8124 APSInt Val; 8125 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8126 return false; 8127 8128 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 8129 } 8130 8131 case Builtin::BI__builtin_clz: 8132 case Builtin::BI__builtin_clzl: 8133 case Builtin::BI__builtin_clzll: 8134 case Builtin::BI__builtin_clzs: { 8135 APSInt Val; 8136 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8137 return false; 8138 if (!Val) 8139 return Error(E); 8140 8141 return Success(Val.countLeadingZeros(), E); 8142 } 8143 8144 case Builtin::BI__builtin_constant_p: 8145 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E); 8146 8147 case Builtin::BI__builtin_ctz: 8148 case Builtin::BI__builtin_ctzl: 8149 case Builtin::BI__builtin_ctzll: 8150 case Builtin::BI__builtin_ctzs: { 8151 APSInt Val; 8152 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8153 return false; 8154 if (!Val) 8155 return Error(E); 8156 8157 return Success(Val.countTrailingZeros(), E); 8158 } 8159 8160 case Builtin::BI__builtin_eh_return_data_regno: { 8161 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 8162 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 8163 return Success(Operand, E); 8164 } 8165 8166 case Builtin::BI__builtin_expect: 8167 return Visit(E->getArg(0)); 8168 8169 case Builtin::BI__builtin_ffs: 8170 case Builtin::BI__builtin_ffsl: 8171 case Builtin::BI__builtin_ffsll: { 8172 APSInt Val; 8173 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8174 return false; 8175 8176 unsigned N = Val.countTrailingZeros(); 8177 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 8178 } 8179 8180 case Builtin::BI__builtin_fpclassify: { 8181 APFloat Val(0.0); 8182 if (!EvaluateFloat(E->getArg(5), Val, Info)) 8183 return false; 8184 unsigned Arg; 8185 switch (Val.getCategory()) { 8186 case APFloat::fcNaN: Arg = 0; break; 8187 case APFloat::fcInfinity: Arg = 1; break; 8188 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 8189 case APFloat::fcZero: Arg = 4; break; 8190 } 8191 return Visit(E->getArg(Arg)); 8192 } 8193 8194 case Builtin::BI__builtin_isinf_sign: { 8195 APFloat Val(0.0); 8196 return EvaluateFloat(E->getArg(0), Val, Info) && 8197 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 8198 } 8199 8200 case Builtin::BI__builtin_isinf: { 8201 APFloat Val(0.0); 8202 return EvaluateFloat(E->getArg(0), Val, Info) && 8203 Success(Val.isInfinity() ? 1 : 0, E); 8204 } 8205 8206 case Builtin::BI__builtin_isfinite: { 8207 APFloat Val(0.0); 8208 return EvaluateFloat(E->getArg(0), Val, Info) && 8209 Success(Val.isFinite() ? 1 : 0, E); 8210 } 8211 8212 case Builtin::BI__builtin_isnan: { 8213 APFloat Val(0.0); 8214 return EvaluateFloat(E->getArg(0), Val, Info) && 8215 Success(Val.isNaN() ? 1 : 0, E); 8216 } 8217 8218 case Builtin::BI__builtin_isnormal: { 8219 APFloat Val(0.0); 8220 return EvaluateFloat(E->getArg(0), Val, Info) && 8221 Success(Val.isNormal() ? 1 : 0, E); 8222 } 8223 8224 case Builtin::BI__builtin_parity: 8225 case Builtin::BI__builtin_parityl: 8226 case Builtin::BI__builtin_parityll: { 8227 APSInt Val; 8228 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8229 return false; 8230 8231 return Success(Val.countPopulation() % 2, E); 8232 } 8233 8234 case Builtin::BI__builtin_popcount: 8235 case Builtin::BI__builtin_popcountl: 8236 case Builtin::BI__builtin_popcountll: { 8237 APSInt Val; 8238 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8239 return false; 8240 8241 return Success(Val.countPopulation(), E); 8242 } 8243 8244 case Builtin::BIstrlen: 8245 case Builtin::BIwcslen: 8246 // A call to strlen is not a constant expression. 8247 if (Info.getLangOpts().CPlusPlus11) 8248 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8249 << /*isConstexpr*/0 << /*isConstructor*/0 8250 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8251 else 8252 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8253 LLVM_FALLTHROUGH; 8254 case Builtin::BI__builtin_strlen: 8255 case Builtin::BI__builtin_wcslen: { 8256 // As an extension, we support __builtin_strlen() as a constant expression, 8257 // and support folding strlen() to a constant. 8258 LValue String; 8259 if (!EvaluatePointer(E->getArg(0), String, Info)) 8260 return false; 8261 8262 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 8263 8264 // Fast path: if it's a string literal, search the string value. 8265 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 8266 String.getLValueBase().dyn_cast<const Expr *>())) { 8267 // The string literal may have embedded null characters. Find the first 8268 // one and truncate there. 8269 StringRef Str = S->getBytes(); 8270 int64_t Off = String.Offset.getQuantity(); 8271 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 8272 S->getCharByteWidth() == 1 && 8273 // FIXME: Add fast-path for wchar_t too. 8274 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 8275 Str = Str.substr(Off); 8276 8277 StringRef::size_type Pos = Str.find(0); 8278 if (Pos != StringRef::npos) 8279 Str = Str.substr(0, Pos); 8280 8281 return Success(Str.size(), E); 8282 } 8283 8284 // Fall through to slow path to issue appropriate diagnostic. 8285 } 8286 8287 // Slow path: scan the bytes of the string looking for the terminating 0. 8288 for (uint64_t Strlen = 0; /**/; ++Strlen) { 8289 APValue Char; 8290 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 8291 !Char.isInt()) 8292 return false; 8293 if (!Char.getInt()) 8294 return Success(Strlen, E); 8295 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 8296 return false; 8297 } 8298 } 8299 8300 case Builtin::BIstrcmp: 8301 case Builtin::BIwcscmp: 8302 case Builtin::BIstrncmp: 8303 case Builtin::BIwcsncmp: 8304 case Builtin::BImemcmp: 8305 case Builtin::BIwmemcmp: 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_strcmp: 8315 case Builtin::BI__builtin_wcscmp: 8316 case Builtin::BI__builtin_strncmp: 8317 case Builtin::BI__builtin_wcsncmp: 8318 case Builtin::BI__builtin_memcmp: 8319 case Builtin::BI__builtin_wmemcmp: { 8320 LValue String1, String2; 8321 if (!EvaluatePointer(E->getArg(0), String1, Info) || 8322 !EvaluatePointer(E->getArg(1), String2, Info)) 8323 return false; 8324 8325 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 8326 8327 uint64_t MaxLength = uint64_t(-1); 8328 if (BuiltinOp != Builtin::BIstrcmp && 8329 BuiltinOp != Builtin::BIwcscmp && 8330 BuiltinOp != Builtin::BI__builtin_strcmp && 8331 BuiltinOp != Builtin::BI__builtin_wcscmp) { 8332 APSInt N; 8333 if (!EvaluateInteger(E->getArg(2), N, Info)) 8334 return false; 8335 MaxLength = N.getExtValue(); 8336 } 8337 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp && 8338 BuiltinOp != Builtin::BIwmemcmp && 8339 BuiltinOp != Builtin::BI__builtin_memcmp && 8340 BuiltinOp != Builtin::BI__builtin_wmemcmp); 8341 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 8342 BuiltinOp == Builtin::BIwcsncmp || 8343 BuiltinOp == Builtin::BIwmemcmp || 8344 BuiltinOp == Builtin::BI__builtin_wcscmp || 8345 BuiltinOp == Builtin::BI__builtin_wcsncmp || 8346 BuiltinOp == Builtin::BI__builtin_wmemcmp; 8347 for (; MaxLength; --MaxLength) { 8348 APValue Char1, Char2; 8349 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) || 8350 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) || 8351 !Char1.isInt() || !Char2.isInt()) 8352 return false; 8353 if (Char1.getInt() != Char2.getInt()) { 8354 if (IsWide) // wmemcmp compares with wchar_t signedness. 8355 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 8356 // memcmp always compares unsigned chars. 8357 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 8358 } 8359 if (StopAtNull && !Char1.getInt()) 8360 return Success(0, E); 8361 assert(!(StopAtNull && !Char2.getInt())); 8362 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) || 8363 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1)) 8364 return false; 8365 } 8366 // We hit the strncmp / memcmp limit. 8367 return Success(0, E); 8368 } 8369 8370 case Builtin::BI__atomic_always_lock_free: 8371 case Builtin::BI__atomic_is_lock_free: 8372 case Builtin::BI__c11_atomic_is_lock_free: { 8373 APSInt SizeVal; 8374 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 8375 return false; 8376 8377 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 8378 // of two less than the maximum inline atomic width, we know it is 8379 // lock-free. If the size isn't a power of two, or greater than the 8380 // maximum alignment where we promote atomics, we know it is not lock-free 8381 // (at least not in the sense of atomic_is_lock_free). Otherwise, 8382 // the answer can only be determined at runtime; for example, 16-byte 8383 // atomics have lock-free implementations on some, but not all, 8384 // x86-64 processors. 8385 8386 // Check power-of-two. 8387 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 8388 if (Size.isPowerOfTwo()) { 8389 // Check against inlining width. 8390 unsigned InlineWidthBits = 8391 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 8392 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 8393 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 8394 Size == CharUnits::One() || 8395 E->getArg(1)->isNullPointerConstant(Info.Ctx, 8396 Expr::NPC_NeverValueDependent)) 8397 // OK, we will inline appropriately-aligned operations of this size, 8398 // and _Atomic(T) is appropriately-aligned. 8399 return Success(1, E); 8400 8401 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 8402 castAs<PointerType>()->getPointeeType(); 8403 if (!PointeeType->isIncompleteType() && 8404 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 8405 // OK, we will inline operations on this object. 8406 return Success(1, E); 8407 } 8408 } 8409 } 8410 8411 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 8412 Success(0, E) : Error(E); 8413 } 8414 case Builtin::BIomp_is_initial_device: 8415 // We can decide statically which value the runtime would return if called. 8416 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 8417 case Builtin::BI__builtin_add_overflow: 8418 case Builtin::BI__builtin_sub_overflow: 8419 case Builtin::BI__builtin_mul_overflow: 8420 case Builtin::BI__builtin_sadd_overflow: 8421 case Builtin::BI__builtin_uadd_overflow: 8422 case Builtin::BI__builtin_uaddl_overflow: 8423 case Builtin::BI__builtin_uaddll_overflow: 8424 case Builtin::BI__builtin_usub_overflow: 8425 case Builtin::BI__builtin_usubl_overflow: 8426 case Builtin::BI__builtin_usubll_overflow: 8427 case Builtin::BI__builtin_umul_overflow: 8428 case Builtin::BI__builtin_umull_overflow: 8429 case Builtin::BI__builtin_umulll_overflow: 8430 case Builtin::BI__builtin_saddl_overflow: 8431 case Builtin::BI__builtin_saddll_overflow: 8432 case Builtin::BI__builtin_ssub_overflow: 8433 case Builtin::BI__builtin_ssubl_overflow: 8434 case Builtin::BI__builtin_ssubll_overflow: 8435 case Builtin::BI__builtin_smul_overflow: 8436 case Builtin::BI__builtin_smull_overflow: 8437 case Builtin::BI__builtin_smulll_overflow: { 8438 LValue ResultLValue; 8439 APSInt LHS, RHS; 8440 8441 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 8442 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 8443 !EvaluateInteger(E->getArg(1), RHS, Info) || 8444 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 8445 return false; 8446 8447 APSInt Result; 8448 bool DidOverflow = false; 8449 8450 // If the types don't have to match, enlarge all 3 to the largest of them. 8451 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 8452 BuiltinOp == Builtin::BI__builtin_sub_overflow || 8453 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 8454 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 8455 ResultType->isSignedIntegerOrEnumerationType(); 8456 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 8457 ResultType->isSignedIntegerOrEnumerationType(); 8458 uint64_t LHSSize = LHS.getBitWidth(); 8459 uint64_t RHSSize = RHS.getBitWidth(); 8460 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 8461 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 8462 8463 // Add an additional bit if the signedness isn't uniformly agreed to. We 8464 // could do this ONLY if there is a signed and an unsigned that both have 8465 // MaxBits, but the code to check that is pretty nasty. The issue will be 8466 // caught in the shrink-to-result later anyway. 8467 if (IsSigned && !AllSigned) 8468 ++MaxBits; 8469 8470 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits), 8471 !IsSigned); 8472 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits), 8473 !IsSigned); 8474 Result = APSInt(MaxBits, !IsSigned); 8475 } 8476 8477 // Find largest int. 8478 switch (BuiltinOp) { 8479 default: 8480 llvm_unreachable("Invalid value for BuiltinOp"); 8481 case Builtin::BI__builtin_add_overflow: 8482 case Builtin::BI__builtin_sadd_overflow: 8483 case Builtin::BI__builtin_saddl_overflow: 8484 case Builtin::BI__builtin_saddll_overflow: 8485 case Builtin::BI__builtin_uadd_overflow: 8486 case Builtin::BI__builtin_uaddl_overflow: 8487 case Builtin::BI__builtin_uaddll_overflow: 8488 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 8489 : LHS.uadd_ov(RHS, DidOverflow); 8490 break; 8491 case Builtin::BI__builtin_sub_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_usub_overflow: 8496 case Builtin::BI__builtin_usubl_overflow: 8497 case Builtin::BI__builtin_usubll_overflow: 8498 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 8499 : LHS.usub_ov(RHS, DidOverflow); 8500 break; 8501 case Builtin::BI__builtin_mul_overflow: 8502 case Builtin::BI__builtin_smul_overflow: 8503 case Builtin::BI__builtin_smull_overflow: 8504 case Builtin::BI__builtin_smulll_overflow: 8505 case Builtin::BI__builtin_umul_overflow: 8506 case Builtin::BI__builtin_umull_overflow: 8507 case Builtin::BI__builtin_umulll_overflow: 8508 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 8509 : LHS.umul_ov(RHS, DidOverflow); 8510 break; 8511 } 8512 8513 // In the case where multiple sizes are allowed, truncate and see if 8514 // the values are the same. 8515 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 8516 BuiltinOp == Builtin::BI__builtin_sub_overflow || 8517 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 8518 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 8519 // since it will give us the behavior of a TruncOrSelf in the case where 8520 // its parameter <= its size. We previously set Result to be at least the 8521 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 8522 // will work exactly like TruncOrSelf. 8523 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 8524 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 8525 8526 if (!APSInt::isSameValue(Temp, Result)) 8527 DidOverflow = true; 8528 Result = Temp; 8529 } 8530 8531 APValue APV{Result}; 8532 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 8533 return false; 8534 return Success(DidOverflow, E); 8535 } 8536 } 8537 } 8538 8539 /// Determine whether this is a pointer past the end of the complete 8540 /// object referred to by the lvalue. 8541 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 8542 const LValue &LV) { 8543 // A null pointer can be viewed as being "past the end" but we don't 8544 // choose to look at it that way here. 8545 if (!LV.getLValueBase()) 8546 return false; 8547 8548 // If the designator is valid and refers to a subobject, we're not pointing 8549 // past the end. 8550 if (!LV.getLValueDesignator().Invalid && 8551 !LV.getLValueDesignator().isOnePastTheEnd()) 8552 return false; 8553 8554 // A pointer to an incomplete type might be past-the-end if the type's size is 8555 // zero. We cannot tell because the type is incomplete. 8556 QualType Ty = getType(LV.getLValueBase()); 8557 if (Ty->isIncompleteType()) 8558 return true; 8559 8560 // We're a past-the-end pointer if we point to the byte after the object, 8561 // no matter what our type or path is. 8562 auto Size = Ctx.getTypeSizeInChars(Ty); 8563 return LV.getLValueOffset() == Size; 8564 } 8565 8566 namespace { 8567 8568 /// Data recursive integer evaluator of certain binary operators. 8569 /// 8570 /// We use a data recursive algorithm for binary operators so that we are able 8571 /// to handle extreme cases of chained binary operators without causing stack 8572 /// overflow. 8573 class DataRecursiveIntBinOpEvaluator { 8574 struct EvalResult { 8575 APValue Val; 8576 bool Failed; 8577 8578 EvalResult() : Failed(false) { } 8579 8580 void swap(EvalResult &RHS) { 8581 Val.swap(RHS.Val); 8582 Failed = RHS.Failed; 8583 RHS.Failed = false; 8584 } 8585 }; 8586 8587 struct Job { 8588 const Expr *E; 8589 EvalResult LHSResult; // meaningful only for binary operator expression. 8590 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 8591 8592 Job() = default; 8593 Job(Job &&) = default; 8594 8595 void startSpeculativeEval(EvalInfo &Info) { 8596 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 8597 } 8598 8599 private: 8600 SpeculativeEvaluationRAII SpecEvalRAII; 8601 }; 8602 8603 SmallVector<Job, 16> Queue; 8604 8605 IntExprEvaluator &IntEval; 8606 EvalInfo &Info; 8607 APValue &FinalResult; 8608 8609 public: 8610 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 8611 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 8612 8613 /// True if \param E is a binary operator that we are going to handle 8614 /// data recursively. 8615 /// We handle binary operators that are comma, logical, or that have operands 8616 /// with integral or enumeration type. 8617 static bool shouldEnqueue(const BinaryOperator *E) { 8618 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 8619 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 8620 E->getLHS()->getType()->isIntegralOrEnumerationType() && 8621 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8622 } 8623 8624 bool Traverse(const BinaryOperator *E) { 8625 enqueue(E); 8626 EvalResult PrevResult; 8627 while (!Queue.empty()) 8628 process(PrevResult); 8629 8630 if (PrevResult.Failed) return false; 8631 8632 FinalResult.swap(PrevResult.Val); 8633 return true; 8634 } 8635 8636 private: 8637 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 8638 return IntEval.Success(Value, E, Result); 8639 } 8640 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 8641 return IntEval.Success(Value, E, Result); 8642 } 8643 bool Error(const Expr *E) { 8644 return IntEval.Error(E); 8645 } 8646 bool Error(const Expr *E, diag::kind D) { 8647 return IntEval.Error(E, D); 8648 } 8649 8650 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 8651 return Info.CCEDiag(E, D); 8652 } 8653 8654 // Returns true if visiting the RHS is necessary, false otherwise. 8655 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8656 bool &SuppressRHSDiags); 8657 8658 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8659 const BinaryOperator *E, APValue &Result); 8660 8661 void EvaluateExpr(const Expr *E, EvalResult &Result) { 8662 Result.Failed = !Evaluate(Result.Val, Info, E); 8663 if (Result.Failed) 8664 Result.Val = APValue(); 8665 } 8666 8667 void process(EvalResult &Result); 8668 8669 void enqueue(const Expr *E) { 8670 E = E->IgnoreParens(); 8671 Queue.resize(Queue.size()+1); 8672 Queue.back().E = E; 8673 Queue.back().Kind = Job::AnyExprKind; 8674 } 8675 }; 8676 8677 } 8678 8679 bool DataRecursiveIntBinOpEvaluator:: 8680 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8681 bool &SuppressRHSDiags) { 8682 if (E->getOpcode() == BO_Comma) { 8683 // Ignore LHS but note if we could not evaluate it. 8684 if (LHSResult.Failed) 8685 return Info.noteSideEffect(); 8686 return true; 8687 } 8688 8689 if (E->isLogicalOp()) { 8690 bool LHSAsBool; 8691 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 8692 // We were able to evaluate the LHS, see if we can get away with not 8693 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 8694 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 8695 Success(LHSAsBool, E, LHSResult.Val); 8696 return false; // Ignore RHS 8697 } 8698 } else { 8699 LHSResult.Failed = true; 8700 8701 // Since we weren't able to evaluate the left hand side, it 8702 // might have had side effects. 8703 if (!Info.noteSideEffect()) 8704 return false; 8705 8706 // We can't evaluate the LHS; however, sometimes the result 8707 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8708 // Don't ignore RHS and suppress diagnostics from this arm. 8709 SuppressRHSDiags = true; 8710 } 8711 8712 return true; 8713 } 8714 8715 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8716 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8717 8718 if (LHSResult.Failed && !Info.noteFailure()) 8719 return false; // Ignore RHS; 8720 8721 return true; 8722 } 8723 8724 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 8725 bool IsSub) { 8726 // Compute the new offset in the appropriate width, wrapping at 64 bits. 8727 // FIXME: When compiling for a 32-bit target, we should use 32-bit 8728 // offsets. 8729 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 8730 CharUnits &Offset = LVal.getLValueOffset(); 8731 uint64_t Offset64 = Offset.getQuantity(); 8732 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 8733 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 8734 : Offset64 + Index64); 8735 } 8736 8737 bool DataRecursiveIntBinOpEvaluator:: 8738 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8739 const BinaryOperator *E, APValue &Result) { 8740 if (E->getOpcode() == BO_Comma) { 8741 if (RHSResult.Failed) 8742 return false; 8743 Result = RHSResult.Val; 8744 return true; 8745 } 8746 8747 if (E->isLogicalOp()) { 8748 bool lhsResult, rhsResult; 8749 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 8750 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 8751 8752 if (LHSIsOK) { 8753 if (RHSIsOK) { 8754 if (E->getOpcode() == BO_LOr) 8755 return Success(lhsResult || rhsResult, E, Result); 8756 else 8757 return Success(lhsResult && rhsResult, E, Result); 8758 } 8759 } else { 8760 if (RHSIsOK) { 8761 // We can't evaluate the LHS; however, sometimes the result 8762 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8763 if (rhsResult == (E->getOpcode() == BO_LOr)) 8764 return Success(rhsResult, E, Result); 8765 } 8766 } 8767 8768 return false; 8769 } 8770 8771 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8772 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8773 8774 if (LHSResult.Failed || RHSResult.Failed) 8775 return false; 8776 8777 const APValue &LHSVal = LHSResult.Val; 8778 const APValue &RHSVal = RHSResult.Val; 8779 8780 // Handle cases like (unsigned long)&a + 4. 8781 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 8782 Result = LHSVal; 8783 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 8784 return true; 8785 } 8786 8787 // Handle cases like 4 + (unsigned long)&a 8788 if (E->getOpcode() == BO_Add && 8789 RHSVal.isLValue() && LHSVal.isInt()) { 8790 Result = RHSVal; 8791 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 8792 return true; 8793 } 8794 8795 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 8796 // Handle (intptr_t)&&A - (intptr_t)&&B. 8797 if (!LHSVal.getLValueOffset().isZero() || 8798 !RHSVal.getLValueOffset().isZero()) 8799 return false; 8800 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 8801 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 8802 if (!LHSExpr || !RHSExpr) 8803 return false; 8804 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 8805 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 8806 if (!LHSAddrExpr || !RHSAddrExpr) 8807 return false; 8808 // Make sure both labels come from the same function. 8809 if (LHSAddrExpr->getLabel()->getDeclContext() != 8810 RHSAddrExpr->getLabel()->getDeclContext()) 8811 return false; 8812 Result = APValue(LHSAddrExpr, RHSAddrExpr); 8813 return true; 8814 } 8815 8816 // All the remaining cases expect both operands to be an integer 8817 if (!LHSVal.isInt() || !RHSVal.isInt()) 8818 return Error(E); 8819 8820 // Set up the width and signedness manually, in case it can't be deduced 8821 // from the operation we're performing. 8822 // FIXME: Don't do this in the cases where we can deduce it. 8823 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 8824 E->getType()->isUnsignedIntegerOrEnumerationType()); 8825 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 8826 RHSVal.getInt(), Value)) 8827 return false; 8828 return Success(Value, E, Result); 8829 } 8830 8831 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 8832 Job &job = Queue.back(); 8833 8834 switch (job.Kind) { 8835 case Job::AnyExprKind: { 8836 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 8837 if (shouldEnqueue(Bop)) { 8838 job.Kind = Job::BinOpKind; 8839 enqueue(Bop->getLHS()); 8840 return; 8841 } 8842 } 8843 8844 EvaluateExpr(job.E, Result); 8845 Queue.pop_back(); 8846 return; 8847 } 8848 8849 case Job::BinOpKind: { 8850 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8851 bool SuppressRHSDiags = false; 8852 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 8853 Queue.pop_back(); 8854 return; 8855 } 8856 if (SuppressRHSDiags) 8857 job.startSpeculativeEval(Info); 8858 job.LHSResult.swap(Result); 8859 job.Kind = Job::BinOpVisitedLHSKind; 8860 enqueue(Bop->getRHS()); 8861 return; 8862 } 8863 8864 case Job::BinOpVisitedLHSKind: { 8865 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8866 EvalResult RHS; 8867 RHS.swap(Result); 8868 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 8869 Queue.pop_back(); 8870 return; 8871 } 8872 } 8873 8874 llvm_unreachable("Invalid Job::Kind!"); 8875 } 8876 8877 namespace { 8878 /// Used when we determine that we should fail, but can keep evaluating prior to 8879 /// noting that we had a failure. 8880 class DelayedNoteFailureRAII { 8881 EvalInfo &Info; 8882 bool NoteFailure; 8883 8884 public: 8885 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 8886 : Info(Info), NoteFailure(NoteFailure) {} 8887 ~DelayedNoteFailureRAII() { 8888 if (NoteFailure) { 8889 bool ContinueAfterFailure = Info.noteFailure(); 8890 (void)ContinueAfterFailure; 8891 assert(ContinueAfterFailure && 8892 "Shouldn't have kept evaluating on failure."); 8893 } 8894 } 8895 }; 8896 } 8897 8898 template <class SuccessCB, class AfterCB> 8899 static bool 8900 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 8901 SuccessCB &&Success, AfterCB &&DoAfter) { 8902 assert(E->isComparisonOp() && "expected comparison operator"); 8903 assert((E->getOpcode() == BO_Cmp || 8904 E->getType()->isIntegralOrEnumerationType()) && 8905 "unsupported binary expression evaluation"); 8906 auto Error = [&](const Expr *E) { 8907 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 8908 return false; 8909 }; 8910 8911 using CCR = ComparisonCategoryResult; 8912 bool IsRelational = E->isRelationalOp(); 8913 bool IsEquality = E->isEqualityOp(); 8914 if (E->getOpcode() == BO_Cmp) { 8915 const ComparisonCategoryInfo &CmpInfo = 8916 Info.Ctx.CompCategories.getInfoForType(E->getType()); 8917 IsRelational = CmpInfo.isOrdered(); 8918 IsEquality = CmpInfo.isEquality(); 8919 } 8920 8921 QualType LHSTy = E->getLHS()->getType(); 8922 QualType RHSTy = E->getRHS()->getType(); 8923 8924 if (LHSTy->isIntegralOrEnumerationType() && 8925 RHSTy->isIntegralOrEnumerationType()) { 8926 APSInt LHS, RHS; 8927 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 8928 if (!LHSOK && !Info.noteFailure()) 8929 return false; 8930 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 8931 return false; 8932 if (LHS < RHS) 8933 return Success(CCR::Less, E); 8934 if (LHS > RHS) 8935 return Success(CCR::Greater, E); 8936 return Success(CCR::Equal, E); 8937 } 8938 8939 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 8940 ComplexValue LHS, RHS; 8941 bool LHSOK; 8942 if (E->isAssignmentOp()) { 8943 LValue LV; 8944 EvaluateLValue(E->getLHS(), LV, Info); 8945 LHSOK = false; 8946 } else if (LHSTy->isRealFloatingType()) { 8947 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 8948 if (LHSOK) { 8949 LHS.makeComplexFloat(); 8950 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 8951 } 8952 } else { 8953 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 8954 } 8955 if (!LHSOK && !Info.noteFailure()) 8956 return false; 8957 8958 if (E->getRHS()->getType()->isRealFloatingType()) { 8959 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 8960 return false; 8961 RHS.makeComplexFloat(); 8962 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 8963 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 8964 return false; 8965 8966 if (LHS.isComplexFloat()) { 8967 APFloat::cmpResult CR_r = 8968 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 8969 APFloat::cmpResult CR_i = 8970 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 8971 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 8972 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 8973 } else { 8974 assert(IsEquality && "invalid complex comparison"); 8975 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 8976 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 8977 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 8978 } 8979 } 8980 8981 if (LHSTy->isRealFloatingType() && 8982 RHSTy->isRealFloatingType()) { 8983 APFloat RHS(0.0), LHS(0.0); 8984 8985 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 8986 if (!LHSOK && !Info.noteFailure()) 8987 return false; 8988 8989 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 8990 return false; 8991 8992 assert(E->isComparisonOp() && "Invalid binary operator!"); 8993 auto GetCmpRes = [&]() { 8994 switch (LHS.compare(RHS)) { 8995 case APFloat::cmpEqual: 8996 return CCR::Equal; 8997 case APFloat::cmpLessThan: 8998 return CCR::Less; 8999 case APFloat::cmpGreaterThan: 9000 return CCR::Greater; 9001 case APFloat::cmpUnordered: 9002 return CCR::Unordered; 9003 } 9004 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 9005 }; 9006 return Success(GetCmpRes(), E); 9007 } 9008 9009 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 9010 LValue LHSValue, RHSValue; 9011 9012 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 9013 if (!LHSOK && !Info.noteFailure()) 9014 return false; 9015 9016 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9017 return false; 9018 9019 // Reject differing bases from the normal codepath; we special-case 9020 // comparisons to null. 9021 if (!HasSameBase(LHSValue, RHSValue)) { 9022 // Inequalities and subtractions between unrelated pointers have 9023 // unspecified or undefined behavior. 9024 if (!IsEquality) 9025 return Error(E); 9026 // A constant address may compare equal to the address of a symbol. 9027 // The one exception is that address of an object cannot compare equal 9028 // to a null pointer constant. 9029 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 9030 (!RHSValue.Base && !RHSValue.Offset.isZero())) 9031 return Error(E); 9032 // It's implementation-defined whether distinct literals will have 9033 // distinct addresses. In clang, the result of such a comparison is 9034 // unspecified, so it is not a constant expression. However, we do know 9035 // that the address of a literal will be non-null. 9036 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 9037 LHSValue.Base && RHSValue.Base) 9038 return Error(E); 9039 // We can't tell whether weak symbols will end up pointing to the same 9040 // object. 9041 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 9042 return Error(E); 9043 // We can't compare the address of the start of one object with the 9044 // past-the-end address of another object, per C++ DR1652. 9045 if ((LHSValue.Base && LHSValue.Offset.isZero() && 9046 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 9047 (RHSValue.Base && RHSValue.Offset.isZero() && 9048 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 9049 return Error(E); 9050 // We can't tell whether an object is at the same address as another 9051 // zero sized object. 9052 if ((RHSValue.Base && isZeroSized(LHSValue)) || 9053 (LHSValue.Base && isZeroSized(RHSValue))) 9054 return Error(E); 9055 return Success(CCR::Nonequal, E); 9056 } 9057 9058 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 9059 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 9060 9061 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 9062 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 9063 9064 // C++11 [expr.rel]p3: 9065 // Pointers to void (after pointer conversions) can be compared, with a 9066 // result defined as follows: If both pointers represent the same 9067 // address or are both the null pointer value, the result is true if the 9068 // operator is <= or >= and false otherwise; otherwise the result is 9069 // unspecified. 9070 // We interpret this as applying to pointers to *cv* void. 9071 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 9072 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 9073 9074 // C++11 [expr.rel]p2: 9075 // - If two pointers point to non-static data members of the same object, 9076 // or to subobjects or array elements fo such members, recursively, the 9077 // pointer to the later declared member compares greater provided the 9078 // two members have the same access control and provided their class is 9079 // not a union. 9080 // [...] 9081 // - Otherwise pointer comparisons are unspecified. 9082 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 9083 bool WasArrayIndex; 9084 unsigned Mismatch = FindDesignatorMismatch( 9085 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 9086 // At the point where the designators diverge, the comparison has a 9087 // specified value if: 9088 // - we are comparing array indices 9089 // - we are comparing fields of a union, or fields with the same access 9090 // Otherwise, the result is unspecified and thus the comparison is not a 9091 // constant expression. 9092 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 9093 Mismatch < RHSDesignator.Entries.size()) { 9094 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 9095 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 9096 if (!LF && !RF) 9097 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 9098 else if (!LF) 9099 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 9100 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 9101 << RF->getParent() << RF; 9102 else if (!RF) 9103 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 9104 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 9105 << LF->getParent() << LF; 9106 else if (!LF->getParent()->isUnion() && 9107 LF->getAccess() != RF->getAccess()) 9108 Info.CCEDiag(E, 9109 diag::note_constexpr_pointer_comparison_differing_access) 9110 << LF << LF->getAccess() << RF << RF->getAccess() 9111 << LF->getParent(); 9112 } 9113 } 9114 9115 // The comparison here must be unsigned, and performed with the same 9116 // width as the pointer. 9117 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 9118 uint64_t CompareLHS = LHSOffset.getQuantity(); 9119 uint64_t CompareRHS = RHSOffset.getQuantity(); 9120 assert(PtrSize <= 64 && "Unexpected pointer width"); 9121 uint64_t Mask = ~0ULL >> (64 - PtrSize); 9122 CompareLHS &= Mask; 9123 CompareRHS &= Mask; 9124 9125 // If there is a base and this is a relational operator, we can only 9126 // compare pointers within the object in question; otherwise, the result 9127 // depends on where the object is located in memory. 9128 if (!LHSValue.Base.isNull() && IsRelational) { 9129 QualType BaseTy = getType(LHSValue.Base); 9130 if (BaseTy->isIncompleteType()) 9131 return Error(E); 9132 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 9133 uint64_t OffsetLimit = Size.getQuantity(); 9134 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 9135 return Error(E); 9136 } 9137 9138 if (CompareLHS < CompareRHS) 9139 return Success(CCR::Less, E); 9140 if (CompareLHS > CompareRHS) 9141 return Success(CCR::Greater, E); 9142 return Success(CCR::Equal, E); 9143 } 9144 9145 if (LHSTy->isMemberPointerType()) { 9146 assert(IsEquality && "unexpected member pointer operation"); 9147 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 9148 9149 MemberPtr LHSValue, RHSValue; 9150 9151 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 9152 if (!LHSOK && !Info.noteFailure()) 9153 return false; 9154 9155 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9156 return false; 9157 9158 // C++11 [expr.eq]p2: 9159 // If both operands are null, they compare equal. Otherwise if only one is 9160 // null, they compare unequal. 9161 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 9162 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 9163 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 9164 } 9165 9166 // Otherwise if either is a pointer to a virtual member function, the 9167 // result is unspecified. 9168 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 9169 if (MD->isVirtual()) 9170 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 9171 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 9172 if (MD->isVirtual()) 9173 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 9174 9175 // Otherwise they compare equal if and only if they would refer to the 9176 // same member of the same most derived object or the same subobject if 9177 // they were dereferenced with a hypothetical object of the associated 9178 // class type. 9179 bool Equal = LHSValue == RHSValue; 9180 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 9181 } 9182 9183 if (LHSTy->isNullPtrType()) { 9184 assert(E->isComparisonOp() && "unexpected nullptr operation"); 9185 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 9186 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 9187 // are compared, the result is true of the operator is <=, >= or ==, and 9188 // false otherwise. 9189 return Success(CCR::Equal, E); 9190 } 9191 9192 return DoAfter(); 9193 } 9194 9195 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 9196 if (!CheckLiteralType(Info, E)) 9197 return false; 9198 9199 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 9200 const BinaryOperator *E) { 9201 // Evaluation succeeded. Lookup the information for the comparison category 9202 // type and fetch the VarDecl for the result. 9203 const ComparisonCategoryInfo &CmpInfo = 9204 Info.Ctx.CompCategories.getInfoForType(E->getType()); 9205 const VarDecl *VD = 9206 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; 9207 // Check and evaluate the result as a constant expression. 9208 LValue LV; 9209 LV.set(VD); 9210 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 9211 return false; 9212 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 9213 }; 9214 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 9215 return ExprEvaluatorBaseTy::VisitBinCmp(E); 9216 }); 9217 } 9218 9219 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9220 // We don't call noteFailure immediately because the assignment happens after 9221 // we evaluate LHS and RHS. 9222 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 9223 return Error(E); 9224 9225 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 9226 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 9227 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 9228 9229 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 9230 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 9231 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 9232 9233 if (E->isComparisonOp()) { 9234 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way 9235 // comparisons and then translating the result. 9236 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 9237 const BinaryOperator *E) { 9238 using CCR = ComparisonCategoryResult; 9239 bool IsEqual = ResKind == CCR::Equal, 9240 IsLess = ResKind == CCR::Less, 9241 IsGreater = ResKind == CCR::Greater; 9242 auto Op = E->getOpcode(); 9243 switch (Op) { 9244 default: 9245 llvm_unreachable("unsupported binary operator"); 9246 case BO_EQ: 9247 case BO_NE: 9248 return Success(IsEqual == (Op == BO_EQ), E); 9249 case BO_LT: return Success(IsLess, E); 9250 case BO_GT: return Success(IsGreater, E); 9251 case BO_LE: return Success(IsEqual || IsLess, E); 9252 case BO_GE: return Success(IsEqual || IsGreater, E); 9253 } 9254 }; 9255 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 9256 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9257 }); 9258 } 9259 9260 QualType LHSTy = E->getLHS()->getType(); 9261 QualType RHSTy = E->getRHS()->getType(); 9262 9263 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 9264 E->getOpcode() == BO_Sub) { 9265 LValue LHSValue, RHSValue; 9266 9267 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 9268 if (!LHSOK && !Info.noteFailure()) 9269 return false; 9270 9271 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9272 return false; 9273 9274 // Reject differing bases from the normal codepath; we special-case 9275 // comparisons to null. 9276 if (!HasSameBase(LHSValue, RHSValue)) { 9277 // Handle &&A - &&B. 9278 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 9279 return Error(E); 9280 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 9281 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 9282 if (!LHSExpr || !RHSExpr) 9283 return Error(E); 9284 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 9285 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 9286 if (!LHSAddrExpr || !RHSAddrExpr) 9287 return Error(E); 9288 // Make sure both labels come from the same function. 9289 if (LHSAddrExpr->getLabel()->getDeclContext() != 9290 RHSAddrExpr->getLabel()->getDeclContext()) 9291 return Error(E); 9292 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 9293 } 9294 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 9295 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 9296 9297 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 9298 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 9299 9300 // C++11 [expr.add]p6: 9301 // Unless both pointers point to elements of the same array object, or 9302 // one past the last element of the array object, the behavior is 9303 // undefined. 9304 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 9305 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 9306 RHSDesignator)) 9307 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 9308 9309 QualType Type = E->getLHS()->getType(); 9310 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 9311 9312 CharUnits ElementSize; 9313 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 9314 return false; 9315 9316 // As an extension, a type may have zero size (empty struct or union in 9317 // C, array of zero length). Pointer subtraction in such cases has 9318 // undefined behavior, so is not constant. 9319 if (ElementSize.isZero()) { 9320 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 9321 << ElementType; 9322 return false; 9323 } 9324 9325 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 9326 // and produce incorrect results when it overflows. Such behavior 9327 // appears to be non-conforming, but is common, so perhaps we should 9328 // assume the standard intended for such cases to be undefined behavior 9329 // and check for them. 9330 9331 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 9332 // overflow in the final conversion to ptrdiff_t. 9333 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 9334 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 9335 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 9336 false); 9337 APSInt TrueResult = (LHS - RHS) / ElemSize; 9338 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 9339 9340 if (Result.extend(65) != TrueResult && 9341 !HandleOverflow(Info, E, TrueResult, E->getType())) 9342 return false; 9343 return Success(Result, E); 9344 } 9345 9346 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9347 } 9348 9349 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 9350 /// a result as the expression's type. 9351 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 9352 const UnaryExprOrTypeTraitExpr *E) { 9353 switch(E->getKind()) { 9354 case UETT_AlignOf: { 9355 if (E->isArgumentType()) 9356 return Success(GetAlignOfType(Info, E->getArgumentType()), E); 9357 else 9358 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E); 9359 } 9360 9361 case UETT_VecStep: { 9362 QualType Ty = E->getTypeOfArgument(); 9363 9364 if (Ty->isVectorType()) { 9365 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 9366 9367 // The vec_step built-in functions that take a 3-component 9368 // vector return 4. (OpenCL 1.1 spec 6.11.12) 9369 if (n == 3) 9370 n = 4; 9371 9372 return Success(n, E); 9373 } else 9374 return Success(1, E); 9375 } 9376 9377 case UETT_SizeOf: { 9378 QualType SrcTy = E->getTypeOfArgument(); 9379 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 9380 // the result is the size of the referenced type." 9381 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 9382 SrcTy = Ref->getPointeeType(); 9383 9384 CharUnits Sizeof; 9385 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 9386 return false; 9387 return Success(Sizeof, E); 9388 } 9389 case UETT_OpenMPRequiredSimdAlign: 9390 assert(E->isArgumentType()); 9391 return Success( 9392 Info.Ctx.toCharUnitsFromBits( 9393 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 9394 .getQuantity(), 9395 E); 9396 } 9397 9398 llvm_unreachable("unknown expr/type trait"); 9399 } 9400 9401 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 9402 CharUnits Result; 9403 unsigned n = OOE->getNumComponents(); 9404 if (n == 0) 9405 return Error(OOE); 9406 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 9407 for (unsigned i = 0; i != n; ++i) { 9408 OffsetOfNode ON = OOE->getComponent(i); 9409 switch (ON.getKind()) { 9410 case OffsetOfNode::Array: { 9411 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 9412 APSInt IdxResult; 9413 if (!EvaluateInteger(Idx, IdxResult, Info)) 9414 return false; 9415 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 9416 if (!AT) 9417 return Error(OOE); 9418 CurrentType = AT->getElementType(); 9419 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 9420 Result += IdxResult.getSExtValue() * ElementSize; 9421 break; 9422 } 9423 9424 case OffsetOfNode::Field: { 9425 FieldDecl *MemberDecl = ON.getField(); 9426 const RecordType *RT = CurrentType->getAs<RecordType>(); 9427 if (!RT) 9428 return Error(OOE); 9429 RecordDecl *RD = RT->getDecl(); 9430 if (RD->isInvalidDecl()) return false; 9431 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 9432 unsigned i = MemberDecl->getFieldIndex(); 9433 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 9434 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 9435 CurrentType = MemberDecl->getType().getNonReferenceType(); 9436 break; 9437 } 9438 9439 case OffsetOfNode::Identifier: 9440 llvm_unreachable("dependent __builtin_offsetof"); 9441 9442 case OffsetOfNode::Base: { 9443 CXXBaseSpecifier *BaseSpec = ON.getBase(); 9444 if (BaseSpec->isVirtual()) 9445 return Error(OOE); 9446 9447 // Find the layout of the class whose base we are looking into. 9448 const RecordType *RT = CurrentType->getAs<RecordType>(); 9449 if (!RT) 9450 return Error(OOE); 9451 RecordDecl *RD = RT->getDecl(); 9452 if (RD->isInvalidDecl()) return false; 9453 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 9454 9455 // Find the base class itself. 9456 CurrentType = BaseSpec->getType(); 9457 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 9458 if (!BaseRT) 9459 return Error(OOE); 9460 9461 // Add the offset to the base. 9462 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 9463 break; 9464 } 9465 } 9466 } 9467 return Success(Result, OOE); 9468 } 9469 9470 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9471 switch (E->getOpcode()) { 9472 default: 9473 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 9474 // See C99 6.6p3. 9475 return Error(E); 9476 case UO_Extension: 9477 // FIXME: Should extension allow i-c-e extension expressions in its scope? 9478 // If so, we could clear the diagnostic ID. 9479 return Visit(E->getSubExpr()); 9480 case UO_Plus: 9481 // The result is just the value. 9482 return Visit(E->getSubExpr()); 9483 case UO_Minus: { 9484 if (!Visit(E->getSubExpr())) 9485 return false; 9486 if (!Result.isInt()) return Error(E); 9487 const APSInt &Value = Result.getInt(); 9488 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 9489 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 9490 E->getType())) 9491 return false; 9492 return Success(-Value, E); 9493 } 9494 case UO_Not: { 9495 if (!Visit(E->getSubExpr())) 9496 return false; 9497 if (!Result.isInt()) return Error(E); 9498 return Success(~Result.getInt(), E); 9499 } 9500 case UO_LNot: { 9501 bool bres; 9502 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 9503 return false; 9504 return Success(!bres, E); 9505 } 9506 } 9507 } 9508 9509 /// HandleCast - This is used to evaluate implicit or explicit casts where the 9510 /// result type is integer. 9511 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 9512 const Expr *SubExpr = E->getSubExpr(); 9513 QualType DestType = E->getType(); 9514 QualType SrcType = SubExpr->getType(); 9515 9516 switch (E->getCastKind()) { 9517 case CK_BaseToDerived: 9518 case CK_DerivedToBase: 9519 case CK_UncheckedDerivedToBase: 9520 case CK_Dynamic: 9521 case CK_ToUnion: 9522 case CK_ArrayToPointerDecay: 9523 case CK_FunctionToPointerDecay: 9524 case CK_NullToPointer: 9525 case CK_NullToMemberPointer: 9526 case CK_BaseToDerivedMemberPointer: 9527 case CK_DerivedToBaseMemberPointer: 9528 case CK_ReinterpretMemberPointer: 9529 case CK_ConstructorConversion: 9530 case CK_IntegralToPointer: 9531 case CK_ToVoid: 9532 case CK_VectorSplat: 9533 case CK_IntegralToFloating: 9534 case CK_FloatingCast: 9535 case CK_CPointerToObjCPointerCast: 9536 case CK_BlockPointerToObjCPointerCast: 9537 case CK_AnyPointerToBlockPointerCast: 9538 case CK_ObjCObjectLValueCast: 9539 case CK_FloatingRealToComplex: 9540 case CK_FloatingComplexToReal: 9541 case CK_FloatingComplexCast: 9542 case CK_FloatingComplexToIntegralComplex: 9543 case CK_IntegralRealToComplex: 9544 case CK_IntegralComplexCast: 9545 case CK_IntegralComplexToFloatingComplex: 9546 case CK_BuiltinFnToFnPtr: 9547 case CK_ZeroToOCLEvent: 9548 case CK_ZeroToOCLQueue: 9549 case CK_NonAtomicToAtomic: 9550 case CK_AddressSpaceConversion: 9551 case CK_IntToOCLSampler: 9552 llvm_unreachable("invalid cast kind for integral value"); 9553 9554 case CK_BitCast: 9555 case CK_Dependent: 9556 case CK_LValueBitCast: 9557 case CK_ARCProduceObject: 9558 case CK_ARCConsumeObject: 9559 case CK_ARCReclaimReturnedObject: 9560 case CK_ARCExtendBlockObject: 9561 case CK_CopyAndAutoreleaseBlockObject: 9562 return Error(E); 9563 9564 case CK_UserDefinedConversion: 9565 case CK_LValueToRValue: 9566 case CK_AtomicToNonAtomic: 9567 case CK_NoOp: 9568 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9569 9570 case CK_MemberPointerToBoolean: 9571 case CK_PointerToBoolean: 9572 case CK_IntegralToBoolean: 9573 case CK_FloatingToBoolean: 9574 case CK_BooleanToSignedIntegral: 9575 case CK_FloatingComplexToBoolean: 9576 case CK_IntegralComplexToBoolean: { 9577 bool BoolResult; 9578 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 9579 return false; 9580 uint64_t IntResult = BoolResult; 9581 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 9582 IntResult = (uint64_t)-1; 9583 return Success(IntResult, E); 9584 } 9585 9586 case CK_IntegralCast: { 9587 if (!Visit(SubExpr)) 9588 return false; 9589 9590 if (!Result.isInt()) { 9591 // Allow casts of address-of-label differences if they are no-ops 9592 // or narrowing. (The narrowing case isn't actually guaranteed to 9593 // be constant-evaluatable except in some narrow cases which are hard 9594 // to detect here. We let it through on the assumption the user knows 9595 // what they are doing.) 9596 if (Result.isAddrLabelDiff()) 9597 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 9598 // Only allow casts of lvalues if they are lossless. 9599 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 9600 } 9601 9602 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 9603 Result.getInt()), E); 9604 } 9605 9606 case CK_PointerToIntegral: { 9607 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 9608 9609 LValue LV; 9610 if (!EvaluatePointer(SubExpr, LV, Info)) 9611 return false; 9612 9613 if (LV.getLValueBase()) { 9614 // Only allow based lvalue casts if they are lossless. 9615 // FIXME: Allow a larger integer size than the pointer size, and allow 9616 // narrowing back down to pointer width in subsequent integral casts. 9617 // FIXME: Check integer type's active bits, not its type size. 9618 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 9619 return Error(E); 9620 9621 LV.Designator.setInvalid(); 9622 LV.moveInto(Result); 9623 return true; 9624 } 9625 9626 uint64_t V; 9627 if (LV.isNullPointer()) 9628 V = Info.Ctx.getTargetNullPointerValue(SrcType); 9629 else 9630 V = LV.getLValueOffset().getQuantity(); 9631 9632 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType); 9633 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 9634 } 9635 9636 case CK_IntegralComplexToReal: { 9637 ComplexValue C; 9638 if (!EvaluateComplex(SubExpr, C, Info)) 9639 return false; 9640 return Success(C.getComplexIntReal(), E); 9641 } 9642 9643 case CK_FloatingToIntegral: { 9644 APFloat F(0.0); 9645 if (!EvaluateFloat(SubExpr, F, Info)) 9646 return false; 9647 9648 APSInt Value; 9649 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 9650 return false; 9651 return Success(Value, E); 9652 } 9653 } 9654 9655 llvm_unreachable("unknown cast resulting in integral value"); 9656 } 9657 9658 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9659 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9660 ComplexValue LV; 9661 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9662 return false; 9663 if (!LV.isComplexInt()) 9664 return Error(E); 9665 return Success(LV.getComplexIntReal(), E); 9666 } 9667 9668 return Visit(E->getSubExpr()); 9669 } 9670 9671 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9672 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 9673 ComplexValue LV; 9674 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9675 return false; 9676 if (!LV.isComplexInt()) 9677 return Error(E); 9678 return Success(LV.getComplexIntImag(), E); 9679 } 9680 9681 VisitIgnoredValue(E->getSubExpr()); 9682 return Success(0, E); 9683 } 9684 9685 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 9686 return Success(E->getPackLength(), E); 9687 } 9688 9689 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 9690 return Success(E->getValue(), E); 9691 } 9692 9693 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9694 switch (E->getOpcode()) { 9695 default: 9696 // Invalid unary operators 9697 return Error(E); 9698 case UO_Plus: 9699 // The result is just the value. 9700 return Visit(E->getSubExpr()); 9701 case UO_Minus: { 9702 if (!Visit(E->getSubExpr())) return false; 9703 if (!Result.isInt()) return Error(E); 9704 const APSInt &Value = Result.getInt(); 9705 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) { 9706 SmallString<64> S; 9707 FixedPointValueToString(S, Value, 9708 Info.Ctx.getTypeInfo(E->getType()).Width); 9709 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType(); 9710 if (Info.noteUndefinedBehavior()) return false; 9711 } 9712 return Success(-Value, E); 9713 } 9714 case UO_LNot: { 9715 bool bres; 9716 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 9717 return false; 9718 return Success(!bres, E); 9719 } 9720 } 9721 } 9722 9723 //===----------------------------------------------------------------------===// 9724 // Float Evaluation 9725 //===----------------------------------------------------------------------===// 9726 9727 namespace { 9728 class FloatExprEvaluator 9729 : public ExprEvaluatorBase<FloatExprEvaluator> { 9730 APFloat &Result; 9731 public: 9732 FloatExprEvaluator(EvalInfo &info, APFloat &result) 9733 : ExprEvaluatorBaseTy(info), Result(result) {} 9734 9735 bool Success(const APValue &V, const Expr *e) { 9736 Result = V.getFloat(); 9737 return true; 9738 } 9739 9740 bool ZeroInitialization(const Expr *E) { 9741 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 9742 return true; 9743 } 9744 9745 bool VisitCallExpr(const CallExpr *E); 9746 9747 bool VisitUnaryOperator(const UnaryOperator *E); 9748 bool VisitBinaryOperator(const BinaryOperator *E); 9749 bool VisitFloatingLiteral(const FloatingLiteral *E); 9750 bool VisitCastExpr(const CastExpr *E); 9751 9752 bool VisitUnaryReal(const UnaryOperator *E); 9753 bool VisitUnaryImag(const UnaryOperator *E); 9754 9755 // FIXME: Missing: array subscript of vector, member of vector 9756 }; 9757 } // end anonymous namespace 9758 9759 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 9760 assert(E->isRValue() && E->getType()->isRealFloatingType()); 9761 return FloatExprEvaluator(Info, Result).Visit(E); 9762 } 9763 9764 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 9765 QualType ResultTy, 9766 const Expr *Arg, 9767 bool SNaN, 9768 llvm::APFloat &Result) { 9769 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 9770 if (!S) return false; 9771 9772 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 9773 9774 llvm::APInt fill; 9775 9776 // Treat empty strings as if they were zero. 9777 if (S->getString().empty()) 9778 fill = llvm::APInt(32, 0); 9779 else if (S->getString().getAsInteger(0, fill)) 9780 return false; 9781 9782 if (Context.getTargetInfo().isNan2008()) { 9783 if (SNaN) 9784 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9785 else 9786 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9787 } else { 9788 // Prior to IEEE 754-2008, architectures were allowed to choose whether 9789 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 9790 // a different encoding to what became a standard in 2008, and for pre- 9791 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 9792 // sNaN. This is now known as "legacy NaN" encoding. 9793 if (SNaN) 9794 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9795 else 9796 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9797 } 9798 9799 return true; 9800 } 9801 9802 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 9803 switch (E->getBuiltinCallee()) { 9804 default: 9805 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9806 9807 case Builtin::BI__builtin_huge_val: 9808 case Builtin::BI__builtin_huge_valf: 9809 case Builtin::BI__builtin_huge_vall: 9810 case Builtin::BI__builtin_huge_valf128: 9811 case Builtin::BI__builtin_inf: 9812 case Builtin::BI__builtin_inff: 9813 case Builtin::BI__builtin_infl: 9814 case Builtin::BI__builtin_inff128: { 9815 const llvm::fltSemantics &Sem = 9816 Info.Ctx.getFloatTypeSemantics(E->getType()); 9817 Result = llvm::APFloat::getInf(Sem); 9818 return true; 9819 } 9820 9821 case Builtin::BI__builtin_nans: 9822 case Builtin::BI__builtin_nansf: 9823 case Builtin::BI__builtin_nansl: 9824 case Builtin::BI__builtin_nansf128: 9825 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9826 true, Result)) 9827 return Error(E); 9828 return true; 9829 9830 case Builtin::BI__builtin_nan: 9831 case Builtin::BI__builtin_nanf: 9832 case Builtin::BI__builtin_nanl: 9833 case Builtin::BI__builtin_nanf128: 9834 // If this is __builtin_nan() turn this into a nan, otherwise we 9835 // can't constant fold it. 9836 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9837 false, Result)) 9838 return Error(E); 9839 return true; 9840 9841 case Builtin::BI__builtin_fabs: 9842 case Builtin::BI__builtin_fabsf: 9843 case Builtin::BI__builtin_fabsl: 9844 case Builtin::BI__builtin_fabsf128: 9845 if (!EvaluateFloat(E->getArg(0), Result, Info)) 9846 return false; 9847 9848 if (Result.isNegative()) 9849 Result.changeSign(); 9850 return true; 9851 9852 // FIXME: Builtin::BI__builtin_powi 9853 // FIXME: Builtin::BI__builtin_powif 9854 // FIXME: Builtin::BI__builtin_powil 9855 9856 case Builtin::BI__builtin_copysign: 9857 case Builtin::BI__builtin_copysignf: 9858 case Builtin::BI__builtin_copysignl: 9859 case Builtin::BI__builtin_copysignf128: { 9860 APFloat RHS(0.); 9861 if (!EvaluateFloat(E->getArg(0), Result, Info) || 9862 !EvaluateFloat(E->getArg(1), RHS, Info)) 9863 return false; 9864 Result.copySign(RHS); 9865 return true; 9866 } 9867 } 9868 } 9869 9870 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9871 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9872 ComplexValue CV; 9873 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9874 return false; 9875 Result = CV.FloatReal; 9876 return true; 9877 } 9878 9879 return Visit(E->getSubExpr()); 9880 } 9881 9882 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9883 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9884 ComplexValue CV; 9885 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9886 return false; 9887 Result = CV.FloatImag; 9888 return true; 9889 } 9890 9891 VisitIgnoredValue(E->getSubExpr()); 9892 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 9893 Result = llvm::APFloat::getZero(Sem); 9894 return true; 9895 } 9896 9897 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9898 switch (E->getOpcode()) { 9899 default: return Error(E); 9900 case UO_Plus: 9901 return EvaluateFloat(E->getSubExpr(), Result, Info); 9902 case UO_Minus: 9903 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 9904 return false; 9905 Result.changeSign(); 9906 return true; 9907 } 9908 } 9909 9910 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9911 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 9912 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9913 9914 APFloat RHS(0.0); 9915 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 9916 if (!LHSOK && !Info.noteFailure()) 9917 return false; 9918 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 9919 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 9920 } 9921 9922 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 9923 Result = E->getValue(); 9924 return true; 9925 } 9926 9927 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 9928 const Expr* SubExpr = E->getSubExpr(); 9929 9930 switch (E->getCastKind()) { 9931 default: 9932 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9933 9934 case CK_IntegralToFloating: { 9935 APSInt IntResult; 9936 return EvaluateInteger(SubExpr, IntResult, Info) && 9937 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 9938 E->getType(), Result); 9939 } 9940 9941 case CK_FloatingCast: { 9942 if (!Visit(SubExpr)) 9943 return false; 9944 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 9945 Result); 9946 } 9947 9948 case CK_FloatingComplexToReal: { 9949 ComplexValue V; 9950 if (!EvaluateComplex(SubExpr, V, Info)) 9951 return false; 9952 Result = V.getComplexFloatReal(); 9953 return true; 9954 } 9955 } 9956 } 9957 9958 //===----------------------------------------------------------------------===// 9959 // Complex Evaluation (for float and integer) 9960 //===----------------------------------------------------------------------===// 9961 9962 namespace { 9963 class ComplexExprEvaluator 9964 : public ExprEvaluatorBase<ComplexExprEvaluator> { 9965 ComplexValue &Result; 9966 9967 public: 9968 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 9969 : ExprEvaluatorBaseTy(info), Result(Result) {} 9970 9971 bool Success(const APValue &V, const Expr *e) { 9972 Result.setFrom(V); 9973 return true; 9974 } 9975 9976 bool ZeroInitialization(const Expr *E); 9977 9978 //===--------------------------------------------------------------------===// 9979 // Visitor Methods 9980 //===--------------------------------------------------------------------===// 9981 9982 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 9983 bool VisitCastExpr(const CastExpr *E); 9984 bool VisitBinaryOperator(const BinaryOperator *E); 9985 bool VisitUnaryOperator(const UnaryOperator *E); 9986 bool VisitInitListExpr(const InitListExpr *E); 9987 }; 9988 } // end anonymous namespace 9989 9990 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 9991 EvalInfo &Info) { 9992 assert(E->isRValue() && E->getType()->isAnyComplexType()); 9993 return ComplexExprEvaluator(Info, Result).Visit(E); 9994 } 9995 9996 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 9997 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 9998 if (ElemTy->isRealFloatingType()) { 9999 Result.makeComplexFloat(); 10000 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 10001 Result.FloatReal = Zero; 10002 Result.FloatImag = Zero; 10003 } else { 10004 Result.makeComplexInt(); 10005 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 10006 Result.IntReal = Zero; 10007 Result.IntImag = Zero; 10008 } 10009 return true; 10010 } 10011 10012 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 10013 const Expr* SubExpr = E->getSubExpr(); 10014 10015 if (SubExpr->getType()->isRealFloatingType()) { 10016 Result.makeComplexFloat(); 10017 APFloat &Imag = Result.FloatImag; 10018 if (!EvaluateFloat(SubExpr, Imag, Info)) 10019 return false; 10020 10021 Result.FloatReal = APFloat(Imag.getSemantics()); 10022 return true; 10023 } else { 10024 assert(SubExpr->getType()->isIntegerType() && 10025 "Unexpected imaginary literal."); 10026 10027 Result.makeComplexInt(); 10028 APSInt &Imag = Result.IntImag; 10029 if (!EvaluateInteger(SubExpr, Imag, Info)) 10030 return false; 10031 10032 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 10033 return true; 10034 } 10035 } 10036 10037 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 10038 10039 switch (E->getCastKind()) { 10040 case CK_BitCast: 10041 case CK_BaseToDerived: 10042 case CK_DerivedToBase: 10043 case CK_UncheckedDerivedToBase: 10044 case CK_Dynamic: 10045 case CK_ToUnion: 10046 case CK_ArrayToPointerDecay: 10047 case CK_FunctionToPointerDecay: 10048 case CK_NullToPointer: 10049 case CK_NullToMemberPointer: 10050 case CK_BaseToDerivedMemberPointer: 10051 case CK_DerivedToBaseMemberPointer: 10052 case CK_MemberPointerToBoolean: 10053 case CK_ReinterpretMemberPointer: 10054 case CK_ConstructorConversion: 10055 case CK_IntegralToPointer: 10056 case CK_PointerToIntegral: 10057 case CK_PointerToBoolean: 10058 case CK_ToVoid: 10059 case CK_VectorSplat: 10060 case CK_IntegralCast: 10061 case CK_BooleanToSignedIntegral: 10062 case CK_IntegralToBoolean: 10063 case CK_IntegralToFloating: 10064 case CK_FloatingToIntegral: 10065 case CK_FloatingToBoolean: 10066 case CK_FloatingCast: 10067 case CK_CPointerToObjCPointerCast: 10068 case CK_BlockPointerToObjCPointerCast: 10069 case CK_AnyPointerToBlockPointerCast: 10070 case CK_ObjCObjectLValueCast: 10071 case CK_FloatingComplexToReal: 10072 case CK_FloatingComplexToBoolean: 10073 case CK_IntegralComplexToReal: 10074 case CK_IntegralComplexToBoolean: 10075 case CK_ARCProduceObject: 10076 case CK_ARCConsumeObject: 10077 case CK_ARCReclaimReturnedObject: 10078 case CK_ARCExtendBlockObject: 10079 case CK_CopyAndAutoreleaseBlockObject: 10080 case CK_BuiltinFnToFnPtr: 10081 case CK_ZeroToOCLEvent: 10082 case CK_ZeroToOCLQueue: 10083 case CK_NonAtomicToAtomic: 10084 case CK_AddressSpaceConversion: 10085 case CK_IntToOCLSampler: 10086 llvm_unreachable("invalid cast kind for complex value"); 10087 10088 case CK_LValueToRValue: 10089 case CK_AtomicToNonAtomic: 10090 case CK_NoOp: 10091 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10092 10093 case CK_Dependent: 10094 case CK_LValueBitCast: 10095 case CK_UserDefinedConversion: 10096 return Error(E); 10097 10098 case CK_FloatingRealToComplex: { 10099 APFloat &Real = Result.FloatReal; 10100 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 10101 return false; 10102 10103 Result.makeComplexFloat(); 10104 Result.FloatImag = APFloat(Real.getSemantics()); 10105 return true; 10106 } 10107 10108 case CK_FloatingComplexCast: { 10109 if (!Visit(E->getSubExpr())) 10110 return false; 10111 10112 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10113 QualType From 10114 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10115 10116 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 10117 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 10118 } 10119 10120 case CK_FloatingComplexToIntegralComplex: { 10121 if (!Visit(E->getSubExpr())) 10122 return false; 10123 10124 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10125 QualType From 10126 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10127 Result.makeComplexInt(); 10128 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 10129 To, Result.IntReal) && 10130 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 10131 To, Result.IntImag); 10132 } 10133 10134 case CK_IntegralRealToComplex: { 10135 APSInt &Real = Result.IntReal; 10136 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 10137 return false; 10138 10139 Result.makeComplexInt(); 10140 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 10141 return true; 10142 } 10143 10144 case CK_IntegralComplexCast: { 10145 if (!Visit(E->getSubExpr())) 10146 return false; 10147 10148 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10149 QualType From 10150 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10151 10152 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 10153 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 10154 return true; 10155 } 10156 10157 case CK_IntegralComplexToFloatingComplex: { 10158 if (!Visit(E->getSubExpr())) 10159 return false; 10160 10161 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 10162 QualType From 10163 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 10164 Result.makeComplexFloat(); 10165 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 10166 To, Result.FloatReal) && 10167 HandleIntToFloatCast(Info, E, From, Result.IntImag, 10168 To, Result.FloatImag); 10169 } 10170 } 10171 10172 llvm_unreachable("unknown cast resulting in complex value"); 10173 } 10174 10175 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10176 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 10177 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10178 10179 // Track whether the LHS or RHS is real at the type system level. When this is 10180 // the case we can simplify our evaluation strategy. 10181 bool LHSReal = false, RHSReal = false; 10182 10183 bool LHSOK; 10184 if (E->getLHS()->getType()->isRealFloatingType()) { 10185 LHSReal = true; 10186 APFloat &Real = Result.FloatReal; 10187 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 10188 if (LHSOK) { 10189 Result.makeComplexFloat(); 10190 Result.FloatImag = APFloat(Real.getSemantics()); 10191 } 10192 } else { 10193 LHSOK = Visit(E->getLHS()); 10194 } 10195 if (!LHSOK && !Info.noteFailure()) 10196 return false; 10197 10198 ComplexValue RHS; 10199 if (E->getRHS()->getType()->isRealFloatingType()) { 10200 RHSReal = true; 10201 APFloat &Real = RHS.FloatReal; 10202 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 10203 return false; 10204 RHS.makeComplexFloat(); 10205 RHS.FloatImag = APFloat(Real.getSemantics()); 10206 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 10207 return false; 10208 10209 assert(!(LHSReal && RHSReal) && 10210 "Cannot have both operands of a complex operation be real."); 10211 switch (E->getOpcode()) { 10212 default: return Error(E); 10213 case BO_Add: 10214 if (Result.isComplexFloat()) { 10215 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 10216 APFloat::rmNearestTiesToEven); 10217 if (LHSReal) 10218 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 10219 else if (!RHSReal) 10220 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 10221 APFloat::rmNearestTiesToEven); 10222 } else { 10223 Result.getComplexIntReal() += RHS.getComplexIntReal(); 10224 Result.getComplexIntImag() += RHS.getComplexIntImag(); 10225 } 10226 break; 10227 case BO_Sub: 10228 if (Result.isComplexFloat()) { 10229 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 10230 APFloat::rmNearestTiesToEven); 10231 if (LHSReal) { 10232 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 10233 Result.getComplexFloatImag().changeSign(); 10234 } else if (!RHSReal) { 10235 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 10236 APFloat::rmNearestTiesToEven); 10237 } 10238 } else { 10239 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 10240 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 10241 } 10242 break; 10243 case BO_Mul: 10244 if (Result.isComplexFloat()) { 10245 // This is an implementation of complex multiplication according to the 10246 // constraints laid out in C11 Annex G. The implemention uses the 10247 // following naming scheme: 10248 // (a + ib) * (c + id) 10249 ComplexValue LHS = Result; 10250 APFloat &A = LHS.getComplexFloatReal(); 10251 APFloat &B = LHS.getComplexFloatImag(); 10252 APFloat &C = RHS.getComplexFloatReal(); 10253 APFloat &D = RHS.getComplexFloatImag(); 10254 APFloat &ResR = Result.getComplexFloatReal(); 10255 APFloat &ResI = Result.getComplexFloatImag(); 10256 if (LHSReal) { 10257 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 10258 ResR = A * C; 10259 ResI = A * D; 10260 } else if (RHSReal) { 10261 ResR = C * A; 10262 ResI = C * B; 10263 } else { 10264 // In the fully general case, we need to handle NaNs and infinities 10265 // robustly. 10266 APFloat AC = A * C; 10267 APFloat BD = B * D; 10268 APFloat AD = A * D; 10269 APFloat BC = B * C; 10270 ResR = AC - BD; 10271 ResI = AD + BC; 10272 if (ResR.isNaN() && ResI.isNaN()) { 10273 bool Recalc = false; 10274 if (A.isInfinity() || B.isInfinity()) { 10275 A = APFloat::copySign( 10276 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 10277 B = APFloat::copySign( 10278 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 10279 if (C.isNaN()) 10280 C = APFloat::copySign(APFloat(C.getSemantics()), C); 10281 if (D.isNaN()) 10282 D = APFloat::copySign(APFloat(D.getSemantics()), D); 10283 Recalc = true; 10284 } 10285 if (C.isInfinity() || D.isInfinity()) { 10286 C = APFloat::copySign( 10287 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 10288 D = APFloat::copySign( 10289 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 10290 if (A.isNaN()) 10291 A = APFloat::copySign(APFloat(A.getSemantics()), A); 10292 if (B.isNaN()) 10293 B = APFloat::copySign(APFloat(B.getSemantics()), B); 10294 Recalc = true; 10295 } 10296 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 10297 AD.isInfinity() || BC.isInfinity())) { 10298 if (A.isNaN()) 10299 A = APFloat::copySign(APFloat(A.getSemantics()), A); 10300 if (B.isNaN()) 10301 B = APFloat::copySign(APFloat(B.getSemantics()), B); 10302 if (C.isNaN()) 10303 C = APFloat::copySign(APFloat(C.getSemantics()), C); 10304 if (D.isNaN()) 10305 D = APFloat::copySign(APFloat(D.getSemantics()), D); 10306 Recalc = true; 10307 } 10308 if (Recalc) { 10309 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 10310 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 10311 } 10312 } 10313 } 10314 } else { 10315 ComplexValue LHS = Result; 10316 Result.getComplexIntReal() = 10317 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 10318 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 10319 Result.getComplexIntImag() = 10320 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 10321 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 10322 } 10323 break; 10324 case BO_Div: 10325 if (Result.isComplexFloat()) { 10326 // This is an implementation of complex division according to the 10327 // constraints laid out in C11 Annex G. The implemention uses the 10328 // following naming scheme: 10329 // (a + ib) / (c + id) 10330 ComplexValue LHS = Result; 10331 APFloat &A = LHS.getComplexFloatReal(); 10332 APFloat &B = LHS.getComplexFloatImag(); 10333 APFloat &C = RHS.getComplexFloatReal(); 10334 APFloat &D = RHS.getComplexFloatImag(); 10335 APFloat &ResR = Result.getComplexFloatReal(); 10336 APFloat &ResI = Result.getComplexFloatImag(); 10337 if (RHSReal) { 10338 ResR = A / C; 10339 ResI = B / C; 10340 } else { 10341 if (LHSReal) { 10342 // No real optimizations we can do here, stub out with zero. 10343 B = APFloat::getZero(A.getSemantics()); 10344 } 10345 int DenomLogB = 0; 10346 APFloat MaxCD = maxnum(abs(C), abs(D)); 10347 if (MaxCD.isFinite()) { 10348 DenomLogB = ilogb(MaxCD); 10349 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 10350 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 10351 } 10352 APFloat Denom = C * C + D * D; 10353 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 10354 APFloat::rmNearestTiesToEven); 10355 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 10356 APFloat::rmNearestTiesToEven); 10357 if (ResR.isNaN() && ResI.isNaN()) { 10358 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 10359 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 10360 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 10361 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 10362 D.isFinite()) { 10363 A = APFloat::copySign( 10364 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 10365 B = APFloat::copySign( 10366 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 10367 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 10368 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 10369 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 10370 C = APFloat::copySign( 10371 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 10372 D = APFloat::copySign( 10373 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 10374 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 10375 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 10376 } 10377 } 10378 } 10379 } else { 10380 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 10381 return Error(E, diag::note_expr_divide_by_zero); 10382 10383 ComplexValue LHS = Result; 10384 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 10385 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 10386 Result.getComplexIntReal() = 10387 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 10388 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 10389 Result.getComplexIntImag() = 10390 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 10391 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 10392 } 10393 break; 10394 } 10395 10396 return true; 10397 } 10398 10399 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10400 // Get the operand value into 'Result'. 10401 if (!Visit(E->getSubExpr())) 10402 return false; 10403 10404 switch (E->getOpcode()) { 10405 default: 10406 return Error(E); 10407 case UO_Extension: 10408 return true; 10409 case UO_Plus: 10410 // The result is always just the subexpr. 10411 return true; 10412 case UO_Minus: 10413 if (Result.isComplexFloat()) { 10414 Result.getComplexFloatReal().changeSign(); 10415 Result.getComplexFloatImag().changeSign(); 10416 } 10417 else { 10418 Result.getComplexIntReal() = -Result.getComplexIntReal(); 10419 Result.getComplexIntImag() = -Result.getComplexIntImag(); 10420 } 10421 return true; 10422 case UO_Not: 10423 if (Result.isComplexFloat()) 10424 Result.getComplexFloatImag().changeSign(); 10425 else 10426 Result.getComplexIntImag() = -Result.getComplexIntImag(); 10427 return true; 10428 } 10429 } 10430 10431 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10432 if (E->getNumInits() == 2) { 10433 if (E->getType()->isComplexType()) { 10434 Result.makeComplexFloat(); 10435 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 10436 return false; 10437 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 10438 return false; 10439 } else { 10440 Result.makeComplexInt(); 10441 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 10442 return false; 10443 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 10444 return false; 10445 } 10446 return true; 10447 } 10448 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 10449 } 10450 10451 //===----------------------------------------------------------------------===// 10452 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 10453 // implicit conversion. 10454 //===----------------------------------------------------------------------===// 10455 10456 namespace { 10457 class AtomicExprEvaluator : 10458 public ExprEvaluatorBase<AtomicExprEvaluator> { 10459 const LValue *This; 10460 APValue &Result; 10461 public: 10462 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 10463 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10464 10465 bool Success(const APValue &V, const Expr *E) { 10466 Result = V; 10467 return true; 10468 } 10469 10470 bool ZeroInitialization(const Expr *E) { 10471 ImplicitValueInitExpr VIE( 10472 E->getType()->castAs<AtomicType>()->getValueType()); 10473 // For atomic-qualified class (and array) types in C++, initialize the 10474 // _Atomic-wrapped subobject directly, in-place. 10475 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 10476 : Evaluate(Result, Info, &VIE); 10477 } 10478 10479 bool VisitCastExpr(const CastExpr *E) { 10480 switch (E->getCastKind()) { 10481 default: 10482 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10483 case CK_NonAtomicToAtomic: 10484 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 10485 : Evaluate(Result, Info, E->getSubExpr()); 10486 } 10487 } 10488 }; 10489 } // end anonymous namespace 10490 10491 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 10492 EvalInfo &Info) { 10493 assert(E->isRValue() && E->getType()->isAtomicType()); 10494 return AtomicExprEvaluator(Info, This, Result).Visit(E); 10495 } 10496 10497 //===----------------------------------------------------------------------===// 10498 // Void expression evaluation, primarily for a cast to void on the LHS of a 10499 // comma operator 10500 //===----------------------------------------------------------------------===// 10501 10502 namespace { 10503 class VoidExprEvaluator 10504 : public ExprEvaluatorBase<VoidExprEvaluator> { 10505 public: 10506 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 10507 10508 bool Success(const APValue &V, const Expr *e) { return true; } 10509 10510 bool ZeroInitialization(const Expr *E) { return true; } 10511 10512 bool VisitCastExpr(const CastExpr *E) { 10513 switch (E->getCastKind()) { 10514 default: 10515 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10516 case CK_ToVoid: 10517 VisitIgnoredValue(E->getSubExpr()); 10518 return true; 10519 } 10520 } 10521 10522 bool VisitCallExpr(const CallExpr *E) { 10523 switch (E->getBuiltinCallee()) { 10524 default: 10525 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10526 case Builtin::BI__assume: 10527 case Builtin::BI__builtin_assume: 10528 // The argument is not evaluated! 10529 return true; 10530 } 10531 } 10532 }; 10533 } // end anonymous namespace 10534 10535 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 10536 assert(E->isRValue() && E->getType()->isVoidType()); 10537 return VoidExprEvaluator(Info).Visit(E); 10538 } 10539 10540 //===----------------------------------------------------------------------===// 10541 // Top level Expr::EvaluateAsRValue method. 10542 //===----------------------------------------------------------------------===// 10543 10544 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 10545 // In C, function designators are not lvalues, but we evaluate them as if they 10546 // are. 10547 QualType T = E->getType(); 10548 if (E->isGLValue() || T->isFunctionType()) { 10549 LValue LV; 10550 if (!EvaluateLValue(E, LV, Info)) 10551 return false; 10552 LV.moveInto(Result); 10553 } else if (T->isVectorType()) { 10554 if (!EvaluateVector(E, Result, Info)) 10555 return false; 10556 } else if (T->isIntegralOrEnumerationType()) { 10557 if (!IntExprEvaluator(Info, Result).Visit(E)) 10558 return false; 10559 } else if (T->hasPointerRepresentation()) { 10560 LValue LV; 10561 if (!EvaluatePointer(E, LV, Info)) 10562 return false; 10563 LV.moveInto(Result); 10564 } else if (T->isRealFloatingType()) { 10565 llvm::APFloat F(0.0); 10566 if (!EvaluateFloat(E, F, Info)) 10567 return false; 10568 Result = APValue(F); 10569 } else if (T->isAnyComplexType()) { 10570 ComplexValue C; 10571 if (!EvaluateComplex(E, C, Info)) 10572 return false; 10573 C.moveInto(Result); 10574 } else if (T->isFixedPointType()) { 10575 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 10576 } else if (T->isMemberPointerType()) { 10577 MemberPtr P; 10578 if (!EvaluateMemberPointer(E, P, Info)) 10579 return false; 10580 P.moveInto(Result); 10581 return true; 10582 } else if (T->isArrayType()) { 10583 LValue LV; 10584 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10585 if (!EvaluateArray(E, LV, Value, Info)) 10586 return false; 10587 Result = Value; 10588 } else if (T->isRecordType()) { 10589 LValue LV; 10590 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10591 if (!EvaluateRecord(E, LV, Value, Info)) 10592 return false; 10593 Result = Value; 10594 } else if (T->isVoidType()) { 10595 if (!Info.getLangOpts().CPlusPlus11) 10596 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 10597 << E->getType(); 10598 if (!EvaluateVoid(E, Info)) 10599 return false; 10600 } else if (T->isAtomicType()) { 10601 QualType Unqual = T.getAtomicUnqualifiedType(); 10602 if (Unqual->isArrayType() || Unqual->isRecordType()) { 10603 LValue LV; 10604 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10605 if (!EvaluateAtomic(E, &LV, Value, Info)) 10606 return false; 10607 } else { 10608 if (!EvaluateAtomic(E, nullptr, Result, Info)) 10609 return false; 10610 } 10611 } else if (Info.getLangOpts().CPlusPlus11) { 10612 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 10613 return false; 10614 } else { 10615 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10616 return false; 10617 } 10618 10619 return true; 10620 } 10621 10622 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 10623 /// cases, the in-place evaluation is essential, since later initializers for 10624 /// an object can indirectly refer to subobjects which were initialized earlier. 10625 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 10626 const Expr *E, bool AllowNonLiteralTypes) { 10627 assert(!E->isValueDependent()); 10628 10629 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 10630 return false; 10631 10632 if (E->isRValue()) { 10633 // Evaluate arrays and record types in-place, so that later initializers can 10634 // refer to earlier-initialized members of the object. 10635 QualType T = E->getType(); 10636 if (T->isArrayType()) 10637 return EvaluateArray(E, This, Result, Info); 10638 else if (T->isRecordType()) 10639 return EvaluateRecord(E, This, Result, Info); 10640 else if (T->isAtomicType()) { 10641 QualType Unqual = T.getAtomicUnqualifiedType(); 10642 if (Unqual->isArrayType() || Unqual->isRecordType()) 10643 return EvaluateAtomic(E, &This, Result, Info); 10644 } 10645 } 10646 10647 // For any other type, in-place evaluation is unimportant. 10648 return Evaluate(Result, Info, E); 10649 } 10650 10651 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 10652 /// lvalue-to-rvalue cast if it is an lvalue. 10653 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 10654 if (E->getType().isNull()) 10655 return false; 10656 10657 if (!CheckLiteralType(Info, E)) 10658 return false; 10659 10660 if (!::Evaluate(Result, Info, E)) 10661 return false; 10662 10663 if (E->isGLValue()) { 10664 LValue LV; 10665 LV.setFrom(Info.Ctx, Result); 10666 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 10667 return false; 10668 } 10669 10670 // Check this core constant expression is a constant expression. 10671 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 10672 } 10673 10674 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 10675 const ASTContext &Ctx, bool &IsConst) { 10676 // Fast-path evaluations of integer literals, since we sometimes see files 10677 // containing vast quantities of these. 10678 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 10679 Result.Val = APValue(APSInt(L->getValue(), 10680 L->getType()->isUnsignedIntegerType())); 10681 IsConst = true; 10682 return true; 10683 } 10684 10685 // This case should be rare, but we need to check it before we check on 10686 // the type below. 10687 if (Exp->getType().isNull()) { 10688 IsConst = false; 10689 return true; 10690 } 10691 10692 // FIXME: Evaluating values of large array and record types can cause 10693 // performance problems. Only do so in C++11 for now. 10694 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 10695 Exp->getType()->isRecordType()) && 10696 !Ctx.getLangOpts().CPlusPlus11) { 10697 IsConst = false; 10698 return true; 10699 } 10700 return false; 10701 } 10702 10703 10704 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 10705 /// any crazy technique (that has nothing to do with language standards) that 10706 /// we want to. If this function returns true, it returns the folded constant 10707 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 10708 /// will be applied to the result. 10709 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { 10710 bool IsConst; 10711 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst)) 10712 return IsConst; 10713 10714 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 10715 return ::EvaluateAsRValue(Info, this, Result.Val); 10716 } 10717 10718 bool Expr::EvaluateAsBooleanCondition(bool &Result, 10719 const ASTContext &Ctx) const { 10720 EvalResult Scratch; 10721 return EvaluateAsRValue(Scratch, Ctx) && 10722 HandleConversionToBool(Scratch.Val, Result); 10723 } 10724 10725 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 10726 Expr::SideEffectsKind SEK) { 10727 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 10728 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 10729 } 10730 10731 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx, 10732 SideEffectsKind AllowSideEffects) const { 10733 if (!getType()->isIntegralOrEnumerationType()) 10734 return false; 10735 10736 EvalResult ExprResult; 10737 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() || 10738 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10739 return false; 10740 10741 Result = ExprResult.Val.getInt(); 10742 return true; 10743 } 10744 10745 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 10746 SideEffectsKind AllowSideEffects) const { 10747 if (!getType()->isRealFloatingType()) 10748 return false; 10749 10750 EvalResult ExprResult; 10751 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() || 10752 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10753 return false; 10754 10755 Result = ExprResult.Val.getFloat(); 10756 return true; 10757 } 10758 10759 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 10760 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 10761 10762 LValue LV; 10763 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 10764 !CheckLValueConstantExpression(Info, getExprLoc(), 10765 Ctx.getLValueReferenceType(getType()), LV, 10766 Expr::EvaluateForCodeGen)) 10767 return false; 10768 10769 LV.moveInto(Result.Val); 10770 return true; 10771 } 10772 10773 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 10774 const ASTContext &Ctx) const { 10775 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 10776 EvalInfo Info(Ctx, Result, EM); 10777 if (!::Evaluate(Result.Val, Info, this)) 10778 return false; 10779 10780 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val, 10781 Usage); 10782 } 10783 10784 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 10785 const VarDecl *VD, 10786 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 10787 // FIXME: Evaluating initializers for large array and record types can cause 10788 // performance problems. Only do so in C++11 for now. 10789 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 10790 !Ctx.getLangOpts().CPlusPlus11) 10791 return false; 10792 10793 Expr::EvalStatus EStatus; 10794 EStatus.Diag = &Notes; 10795 10796 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr() 10797 ? EvalInfo::EM_ConstantExpression 10798 : EvalInfo::EM_ConstantFold); 10799 InitInfo.setEvaluatingDecl(VD, Value); 10800 10801 LValue LVal; 10802 LVal.set(VD); 10803 10804 // C++11 [basic.start.init]p2: 10805 // Variables with static storage duration or thread storage duration shall be 10806 // zero-initialized before any other initialization takes place. 10807 // This behavior is not present in C. 10808 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 10809 !VD->getType()->isReferenceType()) { 10810 ImplicitValueInitExpr VIE(VD->getType()); 10811 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, 10812 /*AllowNonLiteralTypes=*/true)) 10813 return false; 10814 } 10815 10816 if (!EvaluateInPlace(Value, InitInfo, LVal, this, 10817 /*AllowNonLiteralTypes=*/true) || 10818 EStatus.HasSideEffects) 10819 return false; 10820 10821 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 10822 Value); 10823 } 10824 10825 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 10826 /// constant folded, but discard the result. 10827 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 10828 EvalResult Result; 10829 return EvaluateAsRValue(Result, Ctx) && 10830 !hasUnacceptableSideEffect(Result, SEK); 10831 } 10832 10833 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 10834 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 10835 EvalResult EvalResult; 10836 EvalResult.Diag = Diag; 10837 bool Result = EvaluateAsRValue(EvalResult, Ctx); 10838 (void)Result; 10839 assert(Result && "Could not evaluate expression"); 10840 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 10841 10842 return EvalResult.Val.getInt(); 10843 } 10844 10845 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 10846 bool IsConst; 10847 EvalResult EvalResult; 10848 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) { 10849 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow); 10850 (void)::EvaluateAsRValue(Info, this, EvalResult.Val); 10851 } 10852 } 10853 10854 bool Expr::EvalResult::isGlobalLValue() const { 10855 assert(Val.isLValue()); 10856 return IsGlobalLValue(Val.getLValueBase()); 10857 } 10858 10859 10860 /// isIntegerConstantExpr - this recursive routine will test if an expression is 10861 /// an integer constant expression. 10862 10863 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 10864 /// comma, etc 10865 10866 // CheckICE - This function does the fundamental ICE checking: the returned 10867 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 10868 // and a (possibly null) SourceLocation indicating the location of the problem. 10869 // 10870 // Note that to reduce code duplication, this helper does no evaluation 10871 // itself; the caller checks whether the expression is evaluatable, and 10872 // in the rare cases where CheckICE actually cares about the evaluated 10873 // value, it calls into Evaluate. 10874 10875 namespace { 10876 10877 enum ICEKind { 10878 /// This expression is an ICE. 10879 IK_ICE, 10880 /// This expression is not an ICE, but if it isn't evaluated, it's 10881 /// a legal subexpression for an ICE. This return value is used to handle 10882 /// the comma operator in C99 mode, and non-constant subexpressions. 10883 IK_ICEIfUnevaluated, 10884 /// This expression is not an ICE, and is not a legal subexpression for one. 10885 IK_NotICE 10886 }; 10887 10888 struct ICEDiag { 10889 ICEKind Kind; 10890 SourceLocation Loc; 10891 10892 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 10893 }; 10894 10895 } 10896 10897 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 10898 10899 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 10900 10901 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 10902 Expr::EvalResult EVResult; 10903 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects || 10904 !EVResult.Val.isInt()) 10905 return ICEDiag(IK_NotICE, E->getBeginLoc()); 10906 10907 return NoDiag(); 10908 } 10909 10910 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 10911 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 10912 if (!E->getType()->isIntegralOrEnumerationType()) 10913 return ICEDiag(IK_NotICE, E->getBeginLoc()); 10914 10915 switch (E->getStmtClass()) { 10916 #define ABSTRACT_STMT(Node) 10917 #define STMT(Node, Base) case Expr::Node##Class: 10918 #define EXPR(Node, Base) 10919 #include "clang/AST/StmtNodes.inc" 10920 case Expr::PredefinedExprClass: 10921 case Expr::FloatingLiteralClass: 10922 case Expr::ImaginaryLiteralClass: 10923 case Expr::StringLiteralClass: 10924 case Expr::ArraySubscriptExprClass: 10925 case Expr::OMPArraySectionExprClass: 10926 case Expr::MemberExprClass: 10927 case Expr::CompoundAssignOperatorClass: 10928 case Expr::CompoundLiteralExprClass: 10929 case Expr::ExtVectorElementExprClass: 10930 case Expr::DesignatedInitExprClass: 10931 case Expr::ArrayInitLoopExprClass: 10932 case Expr::ArrayInitIndexExprClass: 10933 case Expr::NoInitExprClass: 10934 case Expr::DesignatedInitUpdateExprClass: 10935 case Expr::ImplicitValueInitExprClass: 10936 case Expr::ParenListExprClass: 10937 case Expr::VAArgExprClass: 10938 case Expr::AddrLabelExprClass: 10939 case Expr::StmtExprClass: 10940 case Expr::CXXMemberCallExprClass: 10941 case Expr::CUDAKernelCallExprClass: 10942 case Expr::CXXDynamicCastExprClass: 10943 case Expr::CXXTypeidExprClass: 10944 case Expr::CXXUuidofExprClass: 10945 case Expr::MSPropertyRefExprClass: 10946 case Expr::MSPropertySubscriptExprClass: 10947 case Expr::CXXNullPtrLiteralExprClass: 10948 case Expr::UserDefinedLiteralClass: 10949 case Expr::CXXThisExprClass: 10950 case Expr::CXXThrowExprClass: 10951 case Expr::CXXNewExprClass: 10952 case Expr::CXXDeleteExprClass: 10953 case Expr::CXXPseudoDestructorExprClass: 10954 case Expr::UnresolvedLookupExprClass: 10955 case Expr::TypoExprClass: 10956 case Expr::DependentScopeDeclRefExprClass: 10957 case Expr::CXXConstructExprClass: 10958 case Expr::CXXInheritedCtorInitExprClass: 10959 case Expr::CXXStdInitializerListExprClass: 10960 case Expr::CXXBindTemporaryExprClass: 10961 case Expr::ExprWithCleanupsClass: 10962 case Expr::CXXTemporaryObjectExprClass: 10963 case Expr::CXXUnresolvedConstructExprClass: 10964 case Expr::CXXDependentScopeMemberExprClass: 10965 case Expr::UnresolvedMemberExprClass: 10966 case Expr::ObjCStringLiteralClass: 10967 case Expr::ObjCBoxedExprClass: 10968 case Expr::ObjCArrayLiteralClass: 10969 case Expr::ObjCDictionaryLiteralClass: 10970 case Expr::ObjCEncodeExprClass: 10971 case Expr::ObjCMessageExprClass: 10972 case Expr::ObjCSelectorExprClass: 10973 case Expr::ObjCProtocolExprClass: 10974 case Expr::ObjCIvarRefExprClass: 10975 case Expr::ObjCPropertyRefExprClass: 10976 case Expr::ObjCSubscriptRefExprClass: 10977 case Expr::ObjCIsaExprClass: 10978 case Expr::ObjCAvailabilityCheckExprClass: 10979 case Expr::ShuffleVectorExprClass: 10980 case Expr::ConvertVectorExprClass: 10981 case Expr::BlockExprClass: 10982 case Expr::NoStmtClass: 10983 case Expr::OpaqueValueExprClass: 10984 case Expr::PackExpansionExprClass: 10985 case Expr::SubstNonTypeTemplateParmPackExprClass: 10986 case Expr::FunctionParmPackExprClass: 10987 case Expr::AsTypeExprClass: 10988 case Expr::ObjCIndirectCopyRestoreExprClass: 10989 case Expr::MaterializeTemporaryExprClass: 10990 case Expr::PseudoObjectExprClass: 10991 case Expr::AtomicExprClass: 10992 case Expr::LambdaExprClass: 10993 case Expr::CXXFoldExprClass: 10994 case Expr::CoawaitExprClass: 10995 case Expr::DependentCoawaitExprClass: 10996 case Expr::CoyieldExprClass: 10997 return ICEDiag(IK_NotICE, E->getBeginLoc()); 10998 10999 case Expr::InitListExprClass: { 11000 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 11001 // form "T x = { a };" is equivalent to "T x = a;". 11002 // Unless we're initializing a reference, T is a scalar as it is known to be 11003 // of integral or enumeration type. 11004 if (E->isRValue()) 11005 if (cast<InitListExpr>(E)->getNumInits() == 1) 11006 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 11007 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11008 } 11009 11010 case Expr::SizeOfPackExprClass: 11011 case Expr::GNUNullExprClass: 11012 // GCC considers the GNU __null value to be an integral constant expression. 11013 return NoDiag(); 11014 11015 case Expr::SubstNonTypeTemplateParmExprClass: 11016 return 11017 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 11018 11019 case Expr::ParenExprClass: 11020 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 11021 case Expr::GenericSelectionExprClass: 11022 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 11023 case Expr::IntegerLiteralClass: 11024 case Expr::FixedPointLiteralClass: 11025 case Expr::CharacterLiteralClass: 11026 case Expr::ObjCBoolLiteralExprClass: 11027 case Expr::CXXBoolLiteralExprClass: 11028 case Expr::CXXScalarValueInitExprClass: 11029 case Expr::TypeTraitExprClass: 11030 case Expr::ArrayTypeTraitExprClass: 11031 case Expr::ExpressionTraitExprClass: 11032 case Expr::CXXNoexceptExprClass: 11033 return NoDiag(); 11034 case Expr::CallExprClass: 11035 case Expr::CXXOperatorCallExprClass: { 11036 // C99 6.6/3 allows function calls within unevaluated subexpressions of 11037 // constant expressions, but they can never be ICEs because an ICE cannot 11038 // contain an operand of (pointer to) function type. 11039 const CallExpr *CE = cast<CallExpr>(E); 11040 if (CE->getBuiltinCallee()) 11041 return CheckEvalInICE(E, Ctx); 11042 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11043 } 11044 case Expr::DeclRefExprClass: { 11045 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 11046 return NoDiag(); 11047 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 11048 if (Ctx.getLangOpts().CPlusPlus && 11049 D && IsConstNonVolatile(D->getType())) { 11050 // Parameter variables are never constants. Without this check, 11051 // getAnyInitializer() can find a default argument, which leads 11052 // to chaos. 11053 if (isa<ParmVarDecl>(D)) 11054 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11055 11056 // C++ 7.1.5.1p2 11057 // A variable of non-volatile const-qualified integral or enumeration 11058 // type initialized by an ICE can be used in ICEs. 11059 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 11060 if (!Dcl->getType()->isIntegralOrEnumerationType()) 11061 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11062 11063 const VarDecl *VD; 11064 // Look for a declaration of this variable that has an initializer, and 11065 // check whether it is an ICE. 11066 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 11067 return NoDiag(); 11068 else 11069 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11070 } 11071 } 11072 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11073 } 11074 case Expr::UnaryOperatorClass: { 11075 const UnaryOperator *Exp = cast<UnaryOperator>(E); 11076 switch (Exp->getOpcode()) { 11077 case UO_PostInc: 11078 case UO_PostDec: 11079 case UO_PreInc: 11080 case UO_PreDec: 11081 case UO_AddrOf: 11082 case UO_Deref: 11083 case UO_Coawait: 11084 // C99 6.6/3 allows increment and decrement within unevaluated 11085 // subexpressions of constant expressions, but they can never be ICEs 11086 // because an ICE cannot contain an lvalue operand. 11087 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11088 case UO_Extension: 11089 case UO_LNot: 11090 case UO_Plus: 11091 case UO_Minus: 11092 case UO_Not: 11093 case UO_Real: 11094 case UO_Imag: 11095 return CheckICE(Exp->getSubExpr(), Ctx); 11096 } 11097 11098 // OffsetOf falls through here. 11099 LLVM_FALLTHROUGH; 11100 } 11101 case Expr::OffsetOfExprClass: { 11102 // Note that per C99, offsetof must be an ICE. And AFAIK, using 11103 // EvaluateAsRValue matches the proposed gcc behavior for cases like 11104 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 11105 // compliance: we should warn earlier for offsetof expressions with 11106 // array subscripts that aren't ICEs, and if the array subscripts 11107 // are ICEs, the value of the offsetof must be an integer constant. 11108 return CheckEvalInICE(E, Ctx); 11109 } 11110 case Expr::UnaryExprOrTypeTraitExprClass: { 11111 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 11112 if ((Exp->getKind() == UETT_SizeOf) && 11113 Exp->getTypeOfArgument()->isVariableArrayType()) 11114 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11115 return NoDiag(); 11116 } 11117 case Expr::BinaryOperatorClass: { 11118 const BinaryOperator *Exp = cast<BinaryOperator>(E); 11119 switch (Exp->getOpcode()) { 11120 case BO_PtrMemD: 11121 case BO_PtrMemI: 11122 case BO_Assign: 11123 case BO_MulAssign: 11124 case BO_DivAssign: 11125 case BO_RemAssign: 11126 case BO_AddAssign: 11127 case BO_SubAssign: 11128 case BO_ShlAssign: 11129 case BO_ShrAssign: 11130 case BO_AndAssign: 11131 case BO_XorAssign: 11132 case BO_OrAssign: 11133 // C99 6.6/3 allows assignments within unevaluated subexpressions of 11134 // constant expressions, but they can never be ICEs because an ICE cannot 11135 // contain an lvalue operand. 11136 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11137 11138 case BO_Mul: 11139 case BO_Div: 11140 case BO_Rem: 11141 case BO_Add: 11142 case BO_Sub: 11143 case BO_Shl: 11144 case BO_Shr: 11145 case BO_LT: 11146 case BO_GT: 11147 case BO_LE: 11148 case BO_GE: 11149 case BO_EQ: 11150 case BO_NE: 11151 case BO_And: 11152 case BO_Xor: 11153 case BO_Or: 11154 case BO_Comma: 11155 case BO_Cmp: { 11156 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 11157 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 11158 if (Exp->getOpcode() == BO_Div || 11159 Exp->getOpcode() == BO_Rem) { 11160 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 11161 // we don't evaluate one. 11162 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 11163 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 11164 if (REval == 0) 11165 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11166 if (REval.isSigned() && REval.isAllOnesValue()) { 11167 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 11168 if (LEval.isMinSignedValue()) 11169 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11170 } 11171 } 11172 } 11173 if (Exp->getOpcode() == BO_Comma) { 11174 if (Ctx.getLangOpts().C99) { 11175 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 11176 // if it isn't evaluated. 11177 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 11178 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11179 } else { 11180 // In both C89 and C++, commas in ICEs are illegal. 11181 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11182 } 11183 } 11184 return Worst(LHSResult, RHSResult); 11185 } 11186 case BO_LAnd: 11187 case BO_LOr: { 11188 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 11189 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 11190 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 11191 // Rare case where the RHS has a comma "side-effect"; we need 11192 // to actually check the condition to see whether the side 11193 // with the comma is evaluated. 11194 if ((Exp->getOpcode() == BO_LAnd) != 11195 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 11196 return RHSResult; 11197 return NoDiag(); 11198 } 11199 11200 return Worst(LHSResult, RHSResult); 11201 } 11202 } 11203 LLVM_FALLTHROUGH; 11204 } 11205 case Expr::ImplicitCastExprClass: 11206 case Expr::CStyleCastExprClass: 11207 case Expr::CXXFunctionalCastExprClass: 11208 case Expr::CXXStaticCastExprClass: 11209 case Expr::CXXReinterpretCastExprClass: 11210 case Expr::CXXConstCastExprClass: 11211 case Expr::ObjCBridgedCastExprClass: { 11212 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 11213 if (isa<ExplicitCastExpr>(E)) { 11214 if (const FloatingLiteral *FL 11215 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 11216 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 11217 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 11218 APSInt IgnoredVal(DestWidth, !DestSigned); 11219 bool Ignored; 11220 // If the value does not fit in the destination type, the behavior is 11221 // undefined, so we are not required to treat it as a constant 11222 // expression. 11223 if (FL->getValue().convertToInteger(IgnoredVal, 11224 llvm::APFloat::rmTowardZero, 11225 &Ignored) & APFloat::opInvalidOp) 11226 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11227 return NoDiag(); 11228 } 11229 } 11230 switch (cast<CastExpr>(E)->getCastKind()) { 11231 case CK_LValueToRValue: 11232 case CK_AtomicToNonAtomic: 11233 case CK_NonAtomicToAtomic: 11234 case CK_NoOp: 11235 case CK_IntegralToBoolean: 11236 case CK_IntegralCast: 11237 return CheckICE(SubExpr, Ctx); 11238 default: 11239 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11240 } 11241 } 11242 case Expr::BinaryConditionalOperatorClass: { 11243 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 11244 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 11245 if (CommonResult.Kind == IK_NotICE) return CommonResult; 11246 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 11247 if (FalseResult.Kind == IK_NotICE) return FalseResult; 11248 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 11249 if (FalseResult.Kind == IK_ICEIfUnevaluated && 11250 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 11251 return FalseResult; 11252 } 11253 case Expr::ConditionalOperatorClass: { 11254 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 11255 // If the condition (ignoring parens) is a __builtin_constant_p call, 11256 // then only the true side is actually considered in an integer constant 11257 // expression, and it is fully evaluated. This is an important GNU 11258 // extension. See GCC PR38377 for discussion. 11259 if (const CallExpr *CallCE 11260 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 11261 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 11262 return CheckEvalInICE(E, Ctx); 11263 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 11264 if (CondResult.Kind == IK_NotICE) 11265 return CondResult; 11266 11267 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 11268 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 11269 11270 if (TrueResult.Kind == IK_NotICE) 11271 return TrueResult; 11272 if (FalseResult.Kind == IK_NotICE) 11273 return FalseResult; 11274 if (CondResult.Kind == IK_ICEIfUnevaluated) 11275 return CondResult; 11276 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 11277 return NoDiag(); 11278 // Rare case where the diagnostics depend on which side is evaluated 11279 // Note that if we get here, CondResult is 0, and at least one of 11280 // TrueResult and FalseResult is non-zero. 11281 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 11282 return FalseResult; 11283 return TrueResult; 11284 } 11285 case Expr::CXXDefaultArgExprClass: 11286 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 11287 case Expr::CXXDefaultInitExprClass: 11288 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 11289 case Expr::ChooseExprClass: { 11290 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 11291 } 11292 } 11293 11294 llvm_unreachable("Invalid StmtClass!"); 11295 } 11296 11297 /// Evaluate an expression as a C++11 integral constant expression. 11298 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 11299 const Expr *E, 11300 llvm::APSInt *Value, 11301 SourceLocation *Loc) { 11302 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 11303 if (Loc) *Loc = E->getExprLoc(); 11304 return false; 11305 } 11306 11307 APValue Result; 11308 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 11309 return false; 11310 11311 if (!Result.isInt()) { 11312 if (Loc) *Loc = E->getExprLoc(); 11313 return false; 11314 } 11315 11316 if (Value) *Value = Result.getInt(); 11317 return true; 11318 } 11319 11320 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 11321 SourceLocation *Loc) const { 11322 if (Ctx.getLangOpts().CPlusPlus11) 11323 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 11324 11325 ICEDiag D = CheckICE(this, Ctx); 11326 if (D.Kind != IK_ICE) { 11327 if (Loc) *Loc = D.Loc; 11328 return false; 11329 } 11330 return true; 11331 } 11332 11333 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 11334 SourceLocation *Loc, bool isEvaluated) const { 11335 if (Ctx.getLangOpts().CPlusPlus11) 11336 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 11337 11338 if (!isIntegerConstantExpr(Ctx, Loc)) 11339 return false; 11340 // The only possible side-effects here are due to UB discovered in the 11341 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 11342 // required to treat the expression as an ICE, so we produce the folded 11343 // value. 11344 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects)) 11345 llvm_unreachable("ICE cannot be evaluated!"); 11346 return true; 11347 } 11348 11349 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 11350 return CheckICE(this, Ctx).Kind == IK_ICE; 11351 } 11352 11353 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 11354 SourceLocation *Loc) const { 11355 // We support this checking in C++98 mode in order to diagnose compatibility 11356 // issues. 11357 assert(Ctx.getLangOpts().CPlusPlus); 11358 11359 // Build evaluation settings. 11360 Expr::EvalStatus Status; 11361 SmallVector<PartialDiagnosticAt, 8> Diags; 11362 Status.Diag = &Diags; 11363 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 11364 11365 APValue Scratch; 11366 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 11367 11368 if (!Diags.empty()) { 11369 IsConstExpr = false; 11370 if (Loc) *Loc = Diags[0].first; 11371 } else if (!IsConstExpr) { 11372 // FIXME: This shouldn't happen. 11373 if (Loc) *Loc = getExprLoc(); 11374 } 11375 11376 return IsConstExpr; 11377 } 11378 11379 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 11380 const FunctionDecl *Callee, 11381 ArrayRef<const Expr*> Args, 11382 const Expr *This) const { 11383 Expr::EvalStatus Status; 11384 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 11385 11386 LValue ThisVal; 11387 const LValue *ThisPtr = nullptr; 11388 if (This) { 11389 #ifndef NDEBUG 11390 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 11391 assert(MD && "Don't provide `this` for non-methods."); 11392 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 11393 #endif 11394 if (EvaluateObjectArgument(Info, This, ThisVal)) 11395 ThisPtr = &ThisVal; 11396 if (Info.EvalStatus.HasSideEffects) 11397 return false; 11398 } 11399 11400 ArgVector ArgValues(Args.size()); 11401 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 11402 I != E; ++I) { 11403 if ((*I)->isValueDependent() || 11404 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 11405 // If evaluation fails, throw away the argument entirely. 11406 ArgValues[I - Args.begin()] = APValue(); 11407 if (Info.EvalStatus.HasSideEffects) 11408 return false; 11409 } 11410 11411 // Build fake call to Callee. 11412 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 11413 ArgValues.data()); 11414 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 11415 } 11416 11417 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 11418 SmallVectorImpl< 11419 PartialDiagnosticAt> &Diags) { 11420 // FIXME: It would be useful to check constexpr function templates, but at the 11421 // moment the constant expression evaluator cannot cope with the non-rigorous 11422 // ASTs which we build for dependent expressions. 11423 if (FD->isDependentContext()) 11424 return true; 11425 11426 Expr::EvalStatus Status; 11427 Status.Diag = &Diags; 11428 11429 EvalInfo Info(FD->getASTContext(), Status, 11430 EvalInfo::EM_PotentialConstantExpression); 11431 11432 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 11433 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 11434 11435 // Fabricate an arbitrary expression on the stack and pretend that it 11436 // is a temporary being used as the 'this' pointer. 11437 LValue This; 11438 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 11439 This.set({&VIE, Info.CurrentCall->Index}); 11440 11441 ArrayRef<const Expr*> Args; 11442 11443 APValue Scratch; 11444 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 11445 // Evaluate the call as a constant initializer, to allow the construction 11446 // of objects of non-literal types. 11447 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 11448 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 11449 } else { 11450 SourceLocation Loc = FD->getLocation(); 11451 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 11452 Args, FD->getBody(), Info, Scratch, nullptr); 11453 } 11454 11455 return Diags.empty(); 11456 } 11457 11458 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 11459 const FunctionDecl *FD, 11460 SmallVectorImpl< 11461 PartialDiagnosticAt> &Diags) { 11462 Expr::EvalStatus Status; 11463 Status.Diag = &Diags; 11464 11465 EvalInfo Info(FD->getASTContext(), Status, 11466 EvalInfo::EM_PotentialConstantExpressionUnevaluated); 11467 11468 // Fabricate a call stack frame to give the arguments a plausible cover story. 11469 ArrayRef<const Expr*> Args; 11470 ArgVector ArgValues(0); 11471 bool Success = EvaluateArgs(Args, ArgValues, Info); 11472 (void)Success; 11473 assert(Success && 11474 "Failed to set up arguments for potential constant evaluation"); 11475 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 11476 11477 APValue ResultScratch; 11478 Evaluate(ResultScratch, Info, E); 11479 return Diags.empty(); 11480 } 11481 11482 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 11483 unsigned Type) const { 11484 if (!getType()->isPointerType()) 11485 return false; 11486 11487 Expr::EvalStatus Status; 11488 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 11489 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 11490 } 11491