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