1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Expr constant evaluator. 11 // 12 // Constant expression evaluation produces four main results: 13 // 14 // * A success/failure flag indicating whether constant folding was successful. 15 // This is the 'bool' return value used by most of the code in this file. A 16 // 'false' return value indicates that constant folding has failed, and any 17 // appropriate diagnostic has already been produced. 18 // 19 // * An evaluated result, valid only if constant folding has not failed. 20 // 21 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 23 // where it is possible to determine the evaluated result regardless. 24 // 25 // * A set of notes indicating why the evaluation was not a constant expression 26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 27 // too, why the expression could not be folded. 28 // 29 // If we are checking for a potential constant expression, failure to constant 30 // fold a potential constant sub-expression will be indicated by a 'false' 31 // return value (the expression could not be folded) and no diagnostic (the 32 // expression is not necessarily non-constant). 33 // 34 //===----------------------------------------------------------------------===// 35 36 #include "clang/AST/APValue.h" 37 #include "clang/AST/ASTContext.h" 38 #include "clang/AST/ASTDiagnostic.h" 39 #include "clang/AST/ASTLambda.h" 40 #include "clang/AST/CharUnits.h" 41 #include "clang/AST/Expr.h" 42 #include "clang/AST/OSLog.h" 43 #include "clang/AST/RecordLayout.h" 44 #include "clang/AST/StmtVisitor.h" 45 #include "clang/AST/TypeLoc.h" 46 #include "clang/Basic/Builtins.h" 47 #include "clang/Basic/TargetInfo.h" 48 #include "llvm/Support/raw_ostream.h" 49 #include <cstring> 50 #include <functional> 51 52 #define DEBUG_TYPE "exprconstant" 53 54 using namespace clang; 55 using llvm::APSInt; 56 using llvm::APFloat; 57 58 static bool IsGlobalLValue(APValue::LValueBase B); 59 60 namespace { 61 struct LValue; 62 struct CallStackFrame; 63 struct EvalInfo; 64 65 static QualType getType(APValue::LValueBase B) { 66 if (!B) return QualType(); 67 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 68 // FIXME: It's unclear where we're supposed to take the type from, and 69 // this actually matters for arrays of unknown bound. Eg: 70 // 71 // extern int arr[]; void f() { extern int arr[3]; }; 72 // constexpr int *p = &arr[1]; // valid? 73 // 74 // For now, we take the array bound from the most recent declaration. 75 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 76 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 77 QualType T = Redecl->getType(); 78 if (!T->isIncompleteArrayType()) 79 return T; 80 } 81 return D->getType(); 82 } 83 84 const Expr *Base = B.get<const Expr*>(); 85 86 // For a materialized temporary, the type of the temporary we materialized 87 // may not be the type of the expression. 88 if (const MaterializeTemporaryExpr *MTE = 89 dyn_cast<MaterializeTemporaryExpr>(Base)) { 90 SmallVector<const Expr *, 2> CommaLHSs; 91 SmallVector<SubobjectAdjustment, 2> Adjustments; 92 const Expr *Temp = MTE->GetTemporaryExpr(); 93 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 94 Adjustments); 95 // Keep any cv-qualifiers from the reference if we generated a temporary 96 // for it directly. Otherwise use the type after adjustment. 97 if (!Adjustments.empty()) 98 return Inner->getType(); 99 } 100 101 return Base->getType(); 102 } 103 104 /// Get an LValue path entry, which is known to not be an array index, as a 105 /// field or base class. 106 static 107 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) { 108 APValue::BaseOrMemberType Value; 109 Value.setFromOpaqueValue(E.BaseOrMember); 110 return Value; 111 } 112 113 /// Get an LValue path entry, which is known to not be an array index, as a 114 /// field declaration. 115 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 116 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer()); 117 } 118 /// Get an LValue path entry, which is known to not be an array index, as a 119 /// base class declaration. 120 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 121 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer()); 122 } 123 /// Determine whether this LValue path entry for a base class names a virtual 124 /// base class. 125 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 126 return getAsBaseOrMember(E).getInt(); 127 } 128 129 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 130 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 131 const FunctionDecl *Callee = CE->getDirectCallee(); 132 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 133 } 134 135 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 136 /// This will look through a single cast. 137 /// 138 /// Returns null if we couldn't unwrap a function with alloc_size. 139 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 140 if (!E->getType()->isPointerType()) 141 return nullptr; 142 143 E = E->IgnoreParens(); 144 // If we're doing a variable assignment from e.g. malloc(N), there will 145 // probably be a cast of some kind. In exotic cases, we might also see a 146 // top-level ExprWithCleanups. Ignore them either way. 147 if (const auto *FE = dyn_cast<FullExpr>(E)) 148 E = FE->getSubExpr()->IgnoreParens(); 149 150 if (const auto *Cast = dyn_cast<CastExpr>(E)) 151 E = Cast->getSubExpr()->IgnoreParens(); 152 153 if (const auto *CE = dyn_cast<CallExpr>(E)) 154 return getAllocSizeAttr(CE) ? CE : nullptr; 155 return nullptr; 156 } 157 158 /// Determines whether or not the given Base contains a call to a function 159 /// with the alloc_size attribute. 160 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 161 const auto *E = Base.dyn_cast<const Expr *>(); 162 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 163 } 164 165 /// The bound to claim that an array of unknown bound has. 166 /// The value in MostDerivedArraySize is undefined in this case. So, set it 167 /// to an arbitrary value that's likely to loudly break things if it's used. 168 static const uint64_t AssumedSizeForUnsizedArray = 169 std::numeric_limits<uint64_t>::max() / 2; 170 171 /// Determines if an LValue with the given LValueBase will have an unsized 172 /// array in its designator. 173 /// Find the path length and type of the most-derived subobject in the given 174 /// path, and find the size of the containing array, if any. 175 static unsigned 176 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 177 ArrayRef<APValue::LValuePathEntry> Path, 178 uint64_t &ArraySize, QualType &Type, bool &IsArray, 179 bool &FirstEntryIsUnsizedArray) { 180 // This only accepts LValueBases from APValues, and APValues don't support 181 // arrays that lack size info. 182 assert(!isBaseAnAllocSizeCall(Base) && 183 "Unsized arrays shouldn't appear here"); 184 unsigned MostDerivedLength = 0; 185 Type = getType(Base); 186 187 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 188 if (Type->isArrayType()) { 189 const ArrayType *AT = Ctx.getAsArrayType(Type); 190 Type = AT->getElementType(); 191 MostDerivedLength = I + 1; 192 IsArray = true; 193 194 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 195 ArraySize = CAT->getSize().getZExtValue(); 196 } else { 197 assert(I == 0 && "unexpected unsized array designator"); 198 FirstEntryIsUnsizedArray = true; 199 ArraySize = AssumedSizeForUnsizedArray; 200 } 201 } else if (Type->isAnyComplexType()) { 202 const ComplexType *CT = Type->castAs<ComplexType>(); 203 Type = CT->getElementType(); 204 ArraySize = 2; 205 MostDerivedLength = I + 1; 206 IsArray = true; 207 } else if (const FieldDecl *FD = getAsField(Path[I])) { 208 Type = FD->getType(); 209 ArraySize = 0; 210 MostDerivedLength = I + 1; 211 IsArray = false; 212 } else { 213 // Path[I] describes a base class. 214 ArraySize = 0; 215 IsArray = false; 216 } 217 } 218 return MostDerivedLength; 219 } 220 221 // The order of this enum is important for diagnostics. 222 enum CheckSubobjectKind { 223 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 224 CSK_This, CSK_Real, CSK_Imag 225 }; 226 227 /// A path from a glvalue to a subobject of that glvalue. 228 struct SubobjectDesignator { 229 /// True if the subobject was named in a manner not supported by C++11. Such 230 /// lvalues can still be folded, but they are not core constant expressions 231 /// and we cannot perform lvalue-to-rvalue conversions on them. 232 unsigned Invalid : 1; 233 234 /// Is this a pointer one past the end of an object? 235 unsigned IsOnePastTheEnd : 1; 236 237 /// Indicator of whether the first entry is an unsized array. 238 unsigned FirstEntryIsAnUnsizedArray : 1; 239 240 /// Indicator of whether the most-derived object is an array element. 241 unsigned MostDerivedIsArrayElement : 1; 242 243 /// The length of the path to the most-derived object of which this is a 244 /// subobject. 245 unsigned MostDerivedPathLength : 28; 246 247 /// The size of the array of which the most-derived object is an element. 248 /// This will always be 0 if the most-derived object is not an array 249 /// element. 0 is not an indicator of whether or not the most-derived object 250 /// is an array, however, because 0-length arrays are allowed. 251 /// 252 /// If the current array is an unsized array, the value of this is 253 /// undefined. 254 uint64_t MostDerivedArraySize; 255 256 /// The type of the most derived object referred to by this address. 257 QualType MostDerivedType; 258 259 typedef APValue::LValuePathEntry PathEntry; 260 261 /// The entries on the path from the glvalue to the designated subobject. 262 SmallVector<PathEntry, 8> Entries; 263 264 SubobjectDesignator() : Invalid(true) {} 265 266 explicit SubobjectDesignator(QualType T) 267 : Invalid(false), IsOnePastTheEnd(false), 268 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 269 MostDerivedPathLength(0), MostDerivedArraySize(0), 270 MostDerivedType(T) {} 271 272 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 273 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 274 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 275 MostDerivedPathLength(0), MostDerivedArraySize(0) { 276 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 277 if (!Invalid) { 278 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 279 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 280 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 281 if (V.getLValueBase()) { 282 bool IsArray = false; 283 bool FirstIsUnsizedArray = false; 284 MostDerivedPathLength = findMostDerivedSubobject( 285 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 286 MostDerivedType, IsArray, FirstIsUnsizedArray); 287 MostDerivedIsArrayElement = IsArray; 288 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 289 } 290 } 291 } 292 293 void setInvalid() { 294 Invalid = true; 295 Entries.clear(); 296 } 297 298 /// Determine whether the most derived subobject is an array without a 299 /// known bound. 300 bool isMostDerivedAnUnsizedArray() const { 301 assert(!Invalid && "Calling this makes no sense on invalid designators"); 302 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 303 } 304 305 /// Determine what the most derived array's size is. Results in an assertion 306 /// failure if the most derived array lacks a size. 307 uint64_t getMostDerivedArraySize() const { 308 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 309 return MostDerivedArraySize; 310 } 311 312 /// Determine whether this is a one-past-the-end pointer. 313 bool isOnePastTheEnd() const { 314 assert(!Invalid); 315 if (IsOnePastTheEnd) 316 return true; 317 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 318 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize) 319 return true; 320 return false; 321 } 322 323 /// Get the range of valid index adjustments in the form 324 /// {maximum value that can be subtracted from this pointer, 325 /// maximum value that can be added to this pointer} 326 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 327 if (Invalid || isMostDerivedAnUnsizedArray()) 328 return {0, 0}; 329 330 // [expr.add]p4: For the purposes of these operators, a pointer to a 331 // nonarray object behaves the same as a pointer to the first element of 332 // an array of length one with the type of the object as its element type. 333 bool IsArray = MostDerivedPathLength == Entries.size() && 334 MostDerivedIsArrayElement; 335 uint64_t ArrayIndex = 336 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; 337 uint64_t ArraySize = 338 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 339 return {ArrayIndex, ArraySize - ArrayIndex}; 340 } 341 342 /// Check that this refers to a valid subobject. 343 bool isValidSubobject() const { 344 if (Invalid) 345 return false; 346 return !isOnePastTheEnd(); 347 } 348 /// Check that this refers to a valid subobject, and if not, produce a 349 /// relevant diagnostic and set the designator as invalid. 350 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 351 352 /// Get the type of the designated object. 353 QualType getType(ASTContext &Ctx) const { 354 assert(!Invalid && "invalid designator has no subobject type"); 355 return MostDerivedPathLength == Entries.size() 356 ? MostDerivedType 357 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 358 } 359 360 /// Update this designator to refer to the first element within this array. 361 void addArrayUnchecked(const ConstantArrayType *CAT) { 362 PathEntry Entry; 363 Entry.ArrayIndex = 0; 364 Entries.push_back(Entry); 365 366 // This is a most-derived object. 367 MostDerivedType = CAT->getElementType(); 368 MostDerivedIsArrayElement = true; 369 MostDerivedArraySize = CAT->getSize().getZExtValue(); 370 MostDerivedPathLength = Entries.size(); 371 } 372 /// Update this designator to refer to the first element within the array of 373 /// elements of type T. This is an array of unknown size. 374 void addUnsizedArrayUnchecked(QualType ElemTy) { 375 PathEntry Entry; 376 Entry.ArrayIndex = 0; 377 Entries.push_back(Entry); 378 379 MostDerivedType = ElemTy; 380 MostDerivedIsArrayElement = true; 381 // The value in MostDerivedArraySize is undefined in this case. So, set it 382 // to an arbitrary value that's likely to loudly break things if it's 383 // used. 384 MostDerivedArraySize = AssumedSizeForUnsizedArray; 385 MostDerivedPathLength = Entries.size(); 386 } 387 /// Update this designator to refer to the given base or member of this 388 /// object. 389 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 390 PathEntry Entry; 391 APValue::BaseOrMemberType Value(D, Virtual); 392 Entry.BaseOrMember = Value.getOpaqueValue(); 393 Entries.push_back(Entry); 394 395 // If this isn't a base class, it's a new most-derived object. 396 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 397 MostDerivedType = FD->getType(); 398 MostDerivedIsArrayElement = false; 399 MostDerivedArraySize = 0; 400 MostDerivedPathLength = Entries.size(); 401 } 402 } 403 /// Update this designator to refer to the given complex component. 404 void addComplexUnchecked(QualType EltTy, bool Imag) { 405 PathEntry Entry; 406 Entry.ArrayIndex = Imag; 407 Entries.push_back(Entry); 408 409 // This is technically a most-derived object, though in practice this 410 // is unlikely to matter. 411 MostDerivedType = EltTy; 412 MostDerivedIsArrayElement = true; 413 MostDerivedArraySize = 2; 414 MostDerivedPathLength = Entries.size(); 415 } 416 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 417 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 418 const APSInt &N); 419 /// Add N to the address of this subobject. 420 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 421 if (Invalid || !N) return; 422 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 423 if (isMostDerivedAnUnsizedArray()) { 424 diagnoseUnsizedArrayPointerArithmetic(Info, E); 425 // Can't verify -- trust that the user is doing the right thing (or if 426 // not, trust that the caller will catch the bad behavior). 427 // FIXME: Should we reject if this overflows, at least? 428 Entries.back().ArrayIndex += TruncatedN; 429 return; 430 } 431 432 // [expr.add]p4: For the purposes of these operators, a pointer to a 433 // nonarray object behaves the same as a pointer to the first element of 434 // an array of length one with the type of the object as its element type. 435 bool IsArray = MostDerivedPathLength == Entries.size() && 436 MostDerivedIsArrayElement; 437 uint64_t ArrayIndex = 438 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd; 439 uint64_t ArraySize = 440 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 441 442 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 443 // Calculate the actual index in a wide enough type, so we can include 444 // it in the note. 445 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 446 (llvm::APInt&)N += ArrayIndex; 447 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 448 diagnosePointerArithmetic(Info, E, N); 449 setInvalid(); 450 return; 451 } 452 453 ArrayIndex += TruncatedN; 454 assert(ArrayIndex <= ArraySize && 455 "bounds check succeeded for out-of-bounds index"); 456 457 if (IsArray) 458 Entries.back().ArrayIndex = ArrayIndex; 459 else 460 IsOnePastTheEnd = (ArrayIndex != 0); 461 } 462 }; 463 464 /// A stack frame in the constexpr call stack. 465 struct CallStackFrame { 466 EvalInfo &Info; 467 468 /// Parent - The caller of this stack frame. 469 CallStackFrame *Caller; 470 471 /// Callee - The function which was called. 472 const FunctionDecl *Callee; 473 474 /// This - The binding for the this pointer in this call, if any. 475 const LValue *This; 476 477 /// Arguments - Parameter bindings for this function call, indexed by 478 /// parameters' function scope indices. 479 APValue *Arguments; 480 481 // Note that we intentionally use std::map here so that references to 482 // values are stable. 483 typedef std::pair<const void *, unsigned> MapKeyTy; 484 typedef std::map<MapKeyTy, APValue> MapTy; 485 /// Temporaries - Temporary lvalues materialized within this stack frame. 486 MapTy Temporaries; 487 488 /// CallLoc - The location of the call expression for this call. 489 SourceLocation CallLoc; 490 491 /// Index - The call index of this call. 492 unsigned Index; 493 494 /// The stack of integers for tracking version numbers for temporaries. 495 SmallVector<unsigned, 2> TempVersionStack = {1}; 496 unsigned CurTempVersion = TempVersionStack.back(); 497 498 unsigned getTempVersion() const { return TempVersionStack.back(); } 499 500 void pushTempVersion() { 501 TempVersionStack.push_back(++CurTempVersion); 502 } 503 504 void popTempVersion() { 505 TempVersionStack.pop_back(); 506 } 507 508 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 509 // on the overall stack usage of deeply-recursing constexpr evaluataions. 510 // (We should cache this map rather than recomputing it repeatedly.) 511 // But let's try this and see how it goes; we can look into caching the map 512 // as a later change. 513 514 /// LambdaCaptureFields - Mapping from captured variables/this to 515 /// corresponding data members in the closure class. 516 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 517 FieldDecl *LambdaThisCaptureField; 518 519 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 520 const FunctionDecl *Callee, const LValue *This, 521 APValue *Arguments); 522 ~CallStackFrame(); 523 524 // Return the temporary for Key whose version number is Version. 525 APValue *getTemporary(const void *Key, unsigned Version) { 526 MapKeyTy KV(Key, Version); 527 auto LB = Temporaries.lower_bound(KV); 528 if (LB != Temporaries.end() && LB->first == KV) 529 return &LB->second; 530 // Pair (Key,Version) wasn't found in the map. Check that no elements 531 // in the map have 'Key' as their key. 532 assert((LB == Temporaries.end() || LB->first.first != Key) && 533 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 534 "Element with key 'Key' found in map"); 535 return nullptr; 536 } 537 538 // Return the current temporary for Key in the map. 539 APValue *getCurrentTemporary(const void *Key) { 540 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 541 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 542 return &std::prev(UB)->second; 543 return nullptr; 544 } 545 546 // Return the version number of the current temporary for Key. 547 unsigned getCurrentTemporaryVersion(const void *Key) const { 548 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 549 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 550 return std::prev(UB)->first.second; 551 return 0; 552 } 553 554 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 555 }; 556 557 /// Temporarily override 'this'. 558 class ThisOverrideRAII { 559 public: 560 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 561 : Frame(Frame), OldThis(Frame.This) { 562 if (Enable) 563 Frame.This = NewThis; 564 } 565 ~ThisOverrideRAII() { 566 Frame.This = OldThis; 567 } 568 private: 569 CallStackFrame &Frame; 570 const LValue *OldThis; 571 }; 572 573 /// A partial diagnostic which we might know in advance that we are not going 574 /// to emit. 575 class OptionalDiagnostic { 576 PartialDiagnostic *Diag; 577 578 public: 579 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr) 580 : Diag(Diag) {} 581 582 template<typename T> 583 OptionalDiagnostic &operator<<(const T &v) { 584 if (Diag) 585 *Diag << v; 586 return *this; 587 } 588 589 OptionalDiagnostic &operator<<(const APSInt &I) { 590 if (Diag) { 591 SmallVector<char, 32> Buffer; 592 I.toString(Buffer); 593 *Diag << StringRef(Buffer.data(), Buffer.size()); 594 } 595 return *this; 596 } 597 598 OptionalDiagnostic &operator<<(const APFloat &F) { 599 if (Diag) { 600 // FIXME: Force the precision of the source value down so we don't 601 // print digits which are usually useless (we don't really care here if 602 // we truncate a digit by accident in edge cases). Ideally, 603 // APFloat::toString would automatically print the shortest 604 // representation which rounds to the correct value, but it's a bit 605 // tricky to implement. 606 unsigned precision = 607 llvm::APFloat::semanticsPrecision(F.getSemantics()); 608 precision = (precision * 59 + 195) / 196; 609 SmallVector<char, 32> Buffer; 610 F.toString(Buffer, precision); 611 *Diag << StringRef(Buffer.data(), Buffer.size()); 612 } 613 return *this; 614 } 615 }; 616 617 /// A cleanup, and a flag indicating whether it is lifetime-extended. 618 class Cleanup { 619 llvm::PointerIntPair<APValue*, 1, bool> Value; 620 621 public: 622 Cleanup(APValue *Val, bool IsLifetimeExtended) 623 : Value(Val, IsLifetimeExtended) {} 624 625 bool isLifetimeExtended() const { return Value.getInt(); } 626 void endLifetime() { 627 *Value.getPointer() = APValue(); 628 } 629 }; 630 631 /// EvalInfo - This is a private struct used by the evaluator to capture 632 /// information about a subexpression as it is folded. It retains information 633 /// about the AST context, but also maintains information about the folded 634 /// expression. 635 /// 636 /// If an expression could be evaluated, it is still possible it is not a C 637 /// "integer constant expression" or constant expression. If not, this struct 638 /// captures information about how and why not. 639 /// 640 /// One bit of information passed *into* the request for constant folding 641 /// indicates whether the subexpression is "evaluated" or not according to C 642 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 643 /// evaluate the expression regardless of what the RHS is, but C only allows 644 /// certain things in certain situations. 645 struct EvalInfo { 646 ASTContext &Ctx; 647 648 /// EvalStatus - Contains information about the evaluation. 649 Expr::EvalStatus &EvalStatus; 650 651 /// CurrentCall - The top of the constexpr call stack. 652 CallStackFrame *CurrentCall; 653 654 /// CallStackDepth - The number of calls in the call stack right now. 655 unsigned CallStackDepth; 656 657 /// NextCallIndex - The next call index to assign. 658 unsigned NextCallIndex; 659 660 /// StepsLeft - The remaining number of evaluation steps we're permitted 661 /// to perform. This is essentially a limit for the number of statements 662 /// we will evaluate. 663 unsigned StepsLeft; 664 665 /// BottomFrame - The frame in which evaluation started. This must be 666 /// initialized after CurrentCall and CallStackDepth. 667 CallStackFrame BottomFrame; 668 669 /// A stack of values whose lifetimes end at the end of some surrounding 670 /// evaluation frame. 671 llvm::SmallVector<Cleanup, 16> CleanupStack; 672 673 /// EvaluatingDecl - This is the declaration whose initializer is being 674 /// evaluated, if any. 675 APValue::LValueBase EvaluatingDecl; 676 677 /// EvaluatingDeclValue - This is the value being constructed for the 678 /// declaration whose initializer is being evaluated, if any. 679 APValue *EvaluatingDeclValue; 680 681 /// EvaluatingObject - Pair of the AST node that an lvalue represents and 682 /// the call index that that lvalue was allocated in. 683 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>> 684 EvaluatingObject; 685 686 /// EvaluatingConstructors - Set of objects that are currently being 687 /// constructed. 688 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors; 689 690 struct EvaluatingConstructorRAII { 691 EvalInfo &EI; 692 EvaluatingObject Object; 693 bool DidInsert; 694 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object) 695 : EI(EI), Object(Object) { 696 DidInsert = EI.EvaluatingConstructors.insert(Object).second; 697 } 698 ~EvaluatingConstructorRAII() { 699 if (DidInsert) EI.EvaluatingConstructors.erase(Object); 700 } 701 }; 702 703 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex, 704 unsigned Version) { 705 return EvaluatingConstructors.count( 706 EvaluatingObject(Decl, {CallIndex, Version})); 707 } 708 709 /// The current array initialization index, if we're performing array 710 /// initialization. 711 uint64_t ArrayInitIndex = -1; 712 713 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 714 /// notes attached to it will also be stored, otherwise they will not be. 715 bool HasActiveDiagnostic; 716 717 /// Have we emitted a diagnostic explaining why we couldn't constant 718 /// fold (not just why it's not strictly a constant expression)? 719 bool HasFoldFailureDiagnostic; 720 721 /// Whether or not we're currently speculatively evaluating. 722 bool IsSpeculativelyEvaluating; 723 724 enum EvaluationMode { 725 /// Evaluate as a constant expression. Stop if we find that the expression 726 /// is not a constant expression. 727 EM_ConstantExpression, 728 729 /// Evaluate as a potential constant expression. Keep going if we hit a 730 /// construct that we can't evaluate yet (because we don't yet know the 731 /// value of something) but stop if we hit something that could never be 732 /// a constant expression. 733 EM_PotentialConstantExpression, 734 735 /// Fold the expression to a constant. Stop if we hit a side-effect that 736 /// we can't model. 737 EM_ConstantFold, 738 739 /// Evaluate the expression looking for integer overflow and similar 740 /// issues. Don't worry about side-effects, and try to visit all 741 /// subexpressions. 742 EM_EvaluateForOverflow, 743 744 /// Evaluate in any way we know how. Don't worry about side-effects that 745 /// can't be modeled. 746 EM_IgnoreSideEffects, 747 748 /// Evaluate as a constant expression. Stop if we find that the expression 749 /// is not a constant expression. Some expressions can be retried in the 750 /// optimizer if we don't constant fold them here, but in an unevaluated 751 /// context we try to fold them immediately since the optimizer never 752 /// gets a chance to look at it. 753 EM_ConstantExpressionUnevaluated, 754 755 /// Evaluate as a potential constant expression. Keep going if we hit a 756 /// construct that we can't evaluate yet (because we don't yet know the 757 /// value of something) but stop if we hit something that could never be 758 /// a constant expression. Some expressions can be retried in the 759 /// optimizer if we don't constant fold them here, but in an unevaluated 760 /// context we try to fold them immediately since the optimizer never 761 /// gets a chance to look at it. 762 EM_PotentialConstantExpressionUnevaluated, 763 } EvalMode; 764 765 /// Are we checking whether the expression is a potential constant 766 /// expression? 767 bool checkingPotentialConstantExpression() const { 768 return EvalMode == EM_PotentialConstantExpression || 769 EvalMode == EM_PotentialConstantExpressionUnevaluated; 770 } 771 772 /// Are we checking an expression for overflow? 773 // FIXME: We should check for any kind of undefined or suspicious behavior 774 // in such constructs, not just overflow. 775 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; } 776 777 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 778 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 779 CallStackDepth(0), NextCallIndex(1), 780 StepsLeft(getLangOpts().ConstexprStepLimit), 781 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 782 EvaluatingDecl((const ValueDecl *)nullptr), 783 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 784 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false), 785 EvalMode(Mode) {} 786 787 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 788 EvaluatingDecl = Base; 789 EvaluatingDeclValue = &Value; 790 EvaluatingConstructors.insert({Base, {0, 0}}); 791 } 792 793 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 794 795 bool CheckCallLimit(SourceLocation Loc) { 796 // Don't perform any constexpr calls (other than the call we're checking) 797 // when checking a potential constant expression. 798 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 799 return false; 800 if (NextCallIndex == 0) { 801 // NextCallIndex has wrapped around. 802 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 803 return false; 804 } 805 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 806 return true; 807 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 808 << getLangOpts().ConstexprCallDepth; 809 return false; 810 } 811 812 CallStackFrame *getCallFrame(unsigned CallIndex) { 813 assert(CallIndex && "no call index in getCallFrame"); 814 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 815 // be null in this loop. 816 CallStackFrame *Frame = CurrentCall; 817 while (Frame->Index > CallIndex) 818 Frame = Frame->Caller; 819 return (Frame->Index == CallIndex) ? Frame : nullptr; 820 } 821 822 bool nextStep(const Stmt *S) { 823 if (!StepsLeft) { 824 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 825 return false; 826 } 827 --StepsLeft; 828 return true; 829 } 830 831 private: 832 /// Add a diagnostic to the diagnostics list. 833 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 834 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 835 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 836 return EvalStatus.Diag->back().second; 837 } 838 839 /// Add notes containing a call stack to the current point of evaluation. 840 void addCallStack(unsigned Limit); 841 842 private: 843 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, 844 unsigned ExtraNotes, bool IsCCEDiag) { 845 846 if (EvalStatus.Diag) { 847 // If we have a prior diagnostic, it will be noting that the expression 848 // isn't a constant expression. This diagnostic is more important, 849 // unless we require this evaluation to produce a constant expression. 850 // 851 // FIXME: We might want to show both diagnostics to the user in 852 // EM_ConstantFold mode. 853 if (!EvalStatus.Diag->empty()) { 854 switch (EvalMode) { 855 case EM_ConstantFold: 856 case EM_IgnoreSideEffects: 857 case EM_EvaluateForOverflow: 858 if (!HasFoldFailureDiagnostic) 859 break; 860 // We've already failed to fold something. Keep that diagnostic. 861 LLVM_FALLTHROUGH; 862 case EM_ConstantExpression: 863 case EM_PotentialConstantExpression: 864 case EM_ConstantExpressionUnevaluated: 865 case EM_PotentialConstantExpressionUnevaluated: 866 HasActiveDiagnostic = false; 867 return OptionalDiagnostic(); 868 } 869 } 870 871 unsigned CallStackNotes = CallStackDepth - 1; 872 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 873 if (Limit) 874 CallStackNotes = std::min(CallStackNotes, Limit + 1); 875 if (checkingPotentialConstantExpression()) 876 CallStackNotes = 0; 877 878 HasActiveDiagnostic = true; 879 HasFoldFailureDiagnostic = !IsCCEDiag; 880 EvalStatus.Diag->clear(); 881 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 882 addDiag(Loc, DiagId); 883 if (!checkingPotentialConstantExpression()) 884 addCallStack(Limit); 885 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 886 } 887 HasActiveDiagnostic = false; 888 return OptionalDiagnostic(); 889 } 890 public: 891 // Diagnose that the evaluation could not be folded (FF => FoldFailure) 892 OptionalDiagnostic 893 FFDiag(SourceLocation Loc, 894 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, 895 unsigned ExtraNotes = 0) { 896 return Diag(Loc, DiagId, ExtraNotes, false); 897 } 898 899 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId 900 = diag::note_invalid_subexpr_in_const_expr, 901 unsigned ExtraNotes = 0) { 902 if (EvalStatus.Diag) 903 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false); 904 HasActiveDiagnostic = false; 905 return OptionalDiagnostic(); 906 } 907 908 /// Diagnose that the evaluation does not produce a C++11 core constant 909 /// expression. 910 /// 911 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or 912 /// EM_PotentialConstantExpression mode and we produce one of these. 913 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 914 = diag::note_invalid_subexpr_in_const_expr, 915 unsigned ExtraNotes = 0) { 916 // Don't override a previous diagnostic. Don't bother collecting 917 // diagnostics if we're evaluating for overflow. 918 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 919 HasActiveDiagnostic = false; 920 return OptionalDiagnostic(); 921 } 922 return Diag(Loc, DiagId, ExtraNotes, true); 923 } 924 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId 925 = diag::note_invalid_subexpr_in_const_expr, 926 unsigned ExtraNotes = 0) { 927 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes); 928 } 929 /// Add a note to a prior diagnostic. 930 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 931 if (!HasActiveDiagnostic) 932 return OptionalDiagnostic(); 933 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 934 } 935 936 /// Add a stack of notes to a prior diagnostic. 937 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 938 if (HasActiveDiagnostic) { 939 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 940 Diags.begin(), Diags.end()); 941 } 942 } 943 944 /// Should we continue evaluation after encountering a side-effect that we 945 /// couldn't model? 946 bool keepEvaluatingAfterSideEffect() { 947 switch (EvalMode) { 948 case EM_PotentialConstantExpression: 949 case EM_PotentialConstantExpressionUnevaluated: 950 case EM_EvaluateForOverflow: 951 case EM_IgnoreSideEffects: 952 return true; 953 954 case EM_ConstantExpression: 955 case EM_ConstantExpressionUnevaluated: 956 case EM_ConstantFold: 957 return false; 958 } 959 llvm_unreachable("Missed EvalMode case"); 960 } 961 962 /// Note that we have had a side-effect, and determine whether we should 963 /// keep evaluating. 964 bool noteSideEffect() { 965 EvalStatus.HasSideEffects = true; 966 return keepEvaluatingAfterSideEffect(); 967 } 968 969 /// Should we continue evaluation after encountering undefined behavior? 970 bool keepEvaluatingAfterUndefinedBehavior() { 971 switch (EvalMode) { 972 case EM_EvaluateForOverflow: 973 case EM_IgnoreSideEffects: 974 case EM_ConstantFold: 975 return true; 976 977 case EM_PotentialConstantExpression: 978 case EM_PotentialConstantExpressionUnevaluated: 979 case EM_ConstantExpression: 980 case EM_ConstantExpressionUnevaluated: 981 return false; 982 } 983 llvm_unreachable("Missed EvalMode case"); 984 } 985 986 /// Note that we hit something that was technically undefined behavior, but 987 /// that we can evaluate past it (such as signed overflow or floating-point 988 /// division by zero.) 989 bool noteUndefinedBehavior() { 990 EvalStatus.HasUndefinedBehavior = true; 991 return keepEvaluatingAfterUndefinedBehavior(); 992 } 993 994 /// Should we continue evaluation as much as possible after encountering a 995 /// construct which can't be reduced to a value? 996 bool keepEvaluatingAfterFailure() { 997 if (!StepsLeft) 998 return false; 999 1000 switch (EvalMode) { 1001 case EM_PotentialConstantExpression: 1002 case EM_PotentialConstantExpressionUnevaluated: 1003 case EM_EvaluateForOverflow: 1004 return true; 1005 1006 case EM_ConstantExpression: 1007 case EM_ConstantExpressionUnevaluated: 1008 case EM_ConstantFold: 1009 case EM_IgnoreSideEffects: 1010 return false; 1011 } 1012 llvm_unreachable("Missed EvalMode case"); 1013 } 1014 1015 /// Notes that we failed to evaluate an expression that other expressions 1016 /// directly depend on, and determine if we should keep evaluating. This 1017 /// should only be called if we actually intend to keep evaluating. 1018 /// 1019 /// Call noteSideEffect() instead if we may be able to ignore the value that 1020 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1021 /// 1022 /// (Foo(), 1) // use noteSideEffect 1023 /// (Foo() || true) // use noteSideEffect 1024 /// Foo() + 1 // use noteFailure 1025 LLVM_NODISCARD bool noteFailure() { 1026 // Failure when evaluating some expression often means there is some 1027 // subexpression whose evaluation was skipped. Therefore, (because we 1028 // don't track whether we skipped an expression when unwinding after an 1029 // evaluation failure) every evaluation failure that bubbles up from a 1030 // subexpression implies that a side-effect has potentially happened. We 1031 // skip setting the HasSideEffects flag to true until we decide to 1032 // continue evaluating after that point, which happens here. 1033 bool KeepGoing = keepEvaluatingAfterFailure(); 1034 EvalStatus.HasSideEffects |= KeepGoing; 1035 return KeepGoing; 1036 } 1037 1038 class ArrayInitLoopIndex { 1039 EvalInfo &Info; 1040 uint64_t OuterIndex; 1041 1042 public: 1043 ArrayInitLoopIndex(EvalInfo &Info) 1044 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1045 Info.ArrayInitIndex = 0; 1046 } 1047 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1048 1049 operator uint64_t&() { return Info.ArrayInitIndex; } 1050 }; 1051 }; 1052 1053 /// Object used to treat all foldable expressions as constant expressions. 1054 struct FoldConstant { 1055 EvalInfo &Info; 1056 bool Enabled; 1057 bool HadNoPriorDiags; 1058 EvalInfo::EvaluationMode OldMode; 1059 1060 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1061 : Info(Info), 1062 Enabled(Enabled), 1063 HadNoPriorDiags(Info.EvalStatus.Diag && 1064 Info.EvalStatus.Diag->empty() && 1065 !Info.EvalStatus.HasSideEffects), 1066 OldMode(Info.EvalMode) { 1067 if (Enabled && 1068 (Info.EvalMode == EvalInfo::EM_ConstantExpression || 1069 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated)) 1070 Info.EvalMode = EvalInfo::EM_ConstantFold; 1071 } 1072 void keepDiagnostics() { Enabled = false; } 1073 ~FoldConstant() { 1074 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1075 !Info.EvalStatus.HasSideEffects) 1076 Info.EvalStatus.Diag->clear(); 1077 Info.EvalMode = OldMode; 1078 } 1079 }; 1080 1081 /// RAII object used to set the current evaluation mode to ignore 1082 /// side-effects. 1083 struct IgnoreSideEffectsRAII { 1084 EvalInfo &Info; 1085 EvalInfo::EvaluationMode OldMode; 1086 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1087 : Info(Info), OldMode(Info.EvalMode) { 1088 if (!Info.checkingPotentialConstantExpression()) 1089 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1090 } 1091 1092 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1093 }; 1094 1095 /// RAII object used to optionally suppress diagnostics and side-effects from 1096 /// a speculative evaluation. 1097 class SpeculativeEvaluationRAII { 1098 EvalInfo *Info = nullptr; 1099 Expr::EvalStatus OldStatus; 1100 bool OldIsSpeculativelyEvaluating; 1101 1102 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1103 Info = Other.Info; 1104 OldStatus = Other.OldStatus; 1105 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating; 1106 Other.Info = nullptr; 1107 } 1108 1109 void maybeRestoreState() { 1110 if (!Info) 1111 return; 1112 1113 Info->EvalStatus = OldStatus; 1114 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating; 1115 } 1116 1117 public: 1118 SpeculativeEvaluationRAII() = default; 1119 1120 SpeculativeEvaluationRAII( 1121 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1122 : Info(&Info), OldStatus(Info.EvalStatus), 1123 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) { 1124 Info.EvalStatus.Diag = NewDiag; 1125 Info.IsSpeculativelyEvaluating = true; 1126 } 1127 1128 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1129 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1130 moveFromAndCancel(std::move(Other)); 1131 } 1132 1133 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1134 maybeRestoreState(); 1135 moveFromAndCancel(std::move(Other)); 1136 return *this; 1137 } 1138 1139 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1140 }; 1141 1142 /// RAII object wrapping a full-expression or block scope, and handling 1143 /// the ending of the lifetime of temporaries created within it. 1144 template<bool IsFullExpression> 1145 class ScopeRAII { 1146 EvalInfo &Info; 1147 unsigned OldStackSize; 1148 public: 1149 ScopeRAII(EvalInfo &Info) 1150 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1151 // Push a new temporary version. This is needed to distinguish between 1152 // temporaries created in different iterations of a loop. 1153 Info.CurrentCall->pushTempVersion(); 1154 } 1155 ~ScopeRAII() { 1156 // Body moved to a static method to encourage the compiler to inline away 1157 // instances of this class. 1158 cleanup(Info, OldStackSize); 1159 Info.CurrentCall->popTempVersion(); 1160 } 1161 private: 1162 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 1163 unsigned NewEnd = OldStackSize; 1164 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 1165 I != N; ++I) { 1166 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 1167 // Full-expression cleanup of a lifetime-extended temporary: nothing 1168 // to do, just move this cleanup to the right place in the stack. 1169 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 1170 ++NewEnd; 1171 } else { 1172 // End the lifetime of the object. 1173 Info.CleanupStack[I].endLifetime(); 1174 } 1175 } 1176 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 1177 Info.CleanupStack.end()); 1178 } 1179 }; 1180 typedef ScopeRAII<false> BlockScopeRAII; 1181 typedef ScopeRAII<true> FullExpressionRAII; 1182 } 1183 1184 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1185 CheckSubobjectKind CSK) { 1186 if (Invalid) 1187 return false; 1188 if (isOnePastTheEnd()) { 1189 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1190 << CSK; 1191 setInvalid(); 1192 return false; 1193 } 1194 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1195 // must actually be at least one array element; even a VLA cannot have a 1196 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1197 return true; 1198 } 1199 1200 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1201 const Expr *E) { 1202 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1203 // Do not set the designator as invalid: we can represent this situation, 1204 // and correct handling of __builtin_object_size requires us to do so. 1205 } 1206 1207 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1208 const Expr *E, 1209 const APSInt &N) { 1210 // If we're complaining, we must be able to statically determine the size of 1211 // the most derived array. 1212 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1213 Info.CCEDiag(E, diag::note_constexpr_array_index) 1214 << N << /*array*/ 0 1215 << static_cast<unsigned>(getMostDerivedArraySize()); 1216 else 1217 Info.CCEDiag(E, diag::note_constexpr_array_index) 1218 << N << /*non-array*/ 1; 1219 setInvalid(); 1220 } 1221 1222 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1223 const FunctionDecl *Callee, const LValue *This, 1224 APValue *Arguments) 1225 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1226 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1227 Info.CurrentCall = this; 1228 ++Info.CallStackDepth; 1229 } 1230 1231 CallStackFrame::~CallStackFrame() { 1232 assert(Info.CurrentCall == this && "calls retired out of order"); 1233 --Info.CallStackDepth; 1234 Info.CurrentCall = Caller; 1235 } 1236 1237 APValue &CallStackFrame::createTemporary(const void *Key, 1238 bool IsLifetimeExtended) { 1239 unsigned Version = Info.CurrentCall->getTempVersion(); 1240 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1241 assert(Result.isUninit() && "temporary created multiple times"); 1242 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 1243 return Result; 1244 } 1245 1246 static void describeCall(CallStackFrame *Frame, raw_ostream &Out); 1247 1248 void EvalInfo::addCallStack(unsigned Limit) { 1249 // Determine which calls to skip, if any. 1250 unsigned ActiveCalls = CallStackDepth - 1; 1251 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 1252 if (Limit && Limit < ActiveCalls) { 1253 SkipStart = Limit / 2 + Limit % 2; 1254 SkipEnd = ActiveCalls - Limit / 2; 1255 } 1256 1257 // Walk the call stack and add the diagnostics. 1258 unsigned CallIdx = 0; 1259 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 1260 Frame = Frame->Caller, ++CallIdx) { 1261 // Skip this call? 1262 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 1263 if (CallIdx == SkipStart) { 1264 // Note that we're skipping calls. 1265 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 1266 << unsigned(ActiveCalls - Limit); 1267 } 1268 continue; 1269 } 1270 1271 // Use a different note for an inheriting constructor, because from the 1272 // user's perspective it's not really a function at all. 1273 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) { 1274 if (CD->isInheritingConstructor()) { 1275 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here) 1276 << CD->getParent(); 1277 continue; 1278 } 1279 } 1280 1281 SmallVector<char, 128> Buffer; 1282 llvm::raw_svector_ostream Out(Buffer); 1283 describeCall(Frame, Out); 1284 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 1285 } 1286 } 1287 1288 namespace { 1289 struct ComplexValue { 1290 private: 1291 bool IsInt; 1292 1293 public: 1294 APSInt IntReal, IntImag; 1295 APFloat FloatReal, FloatImag; 1296 1297 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1298 1299 void makeComplexFloat() { IsInt = false; } 1300 bool isComplexFloat() const { return !IsInt; } 1301 APFloat &getComplexFloatReal() { return FloatReal; } 1302 APFloat &getComplexFloatImag() { return FloatImag; } 1303 1304 void makeComplexInt() { IsInt = true; } 1305 bool isComplexInt() const { return IsInt; } 1306 APSInt &getComplexIntReal() { return IntReal; } 1307 APSInt &getComplexIntImag() { return IntImag; } 1308 1309 void moveInto(APValue &v) const { 1310 if (isComplexFloat()) 1311 v = APValue(FloatReal, FloatImag); 1312 else 1313 v = APValue(IntReal, IntImag); 1314 } 1315 void setFrom(const APValue &v) { 1316 assert(v.isComplexFloat() || v.isComplexInt()); 1317 if (v.isComplexFloat()) { 1318 makeComplexFloat(); 1319 FloatReal = v.getComplexFloatReal(); 1320 FloatImag = v.getComplexFloatImag(); 1321 } else { 1322 makeComplexInt(); 1323 IntReal = v.getComplexIntReal(); 1324 IntImag = v.getComplexIntImag(); 1325 } 1326 } 1327 }; 1328 1329 struct LValue { 1330 APValue::LValueBase Base; 1331 CharUnits Offset; 1332 SubobjectDesignator Designator; 1333 bool IsNullPtr : 1; 1334 bool InvalidBase : 1; 1335 1336 const APValue::LValueBase getLValueBase() const { return Base; } 1337 CharUnits &getLValueOffset() { return Offset; } 1338 const CharUnits &getLValueOffset() const { return Offset; } 1339 SubobjectDesignator &getLValueDesignator() { return Designator; } 1340 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1341 bool isNullPointer() const { return IsNullPtr;} 1342 1343 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1344 unsigned getLValueVersion() const { return Base.getVersion(); } 1345 1346 void moveInto(APValue &V) const { 1347 if (Designator.Invalid) 1348 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1349 else { 1350 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1351 V = APValue(Base, Offset, Designator.Entries, 1352 Designator.IsOnePastTheEnd, IsNullPtr); 1353 } 1354 } 1355 void setFrom(ASTContext &Ctx, const APValue &V) { 1356 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1357 Base = V.getLValueBase(); 1358 Offset = V.getLValueOffset(); 1359 InvalidBase = false; 1360 Designator = SubobjectDesignator(Ctx, V); 1361 IsNullPtr = V.isNullPointer(); 1362 } 1363 1364 void set(APValue::LValueBase B, bool BInvalid = false) { 1365 #ifndef NDEBUG 1366 // We only allow a few types of invalid bases. Enforce that here. 1367 if (BInvalid) { 1368 const auto *E = B.get<const Expr *>(); 1369 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1370 "Unexpected type of invalid base"); 1371 } 1372 #endif 1373 1374 Base = B; 1375 Offset = CharUnits::fromQuantity(0); 1376 InvalidBase = BInvalid; 1377 Designator = SubobjectDesignator(getType(B)); 1378 IsNullPtr = false; 1379 } 1380 1381 void setNull(QualType PointerTy, uint64_t TargetVal) { 1382 Base = (Expr *)nullptr; 1383 Offset = CharUnits::fromQuantity(TargetVal); 1384 InvalidBase = false; 1385 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1386 IsNullPtr = true; 1387 } 1388 1389 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1390 set(B, true); 1391 } 1392 1393 // Check that this LValue is not based on a null pointer. If it is, produce 1394 // a diagnostic and mark the designator as invalid. 1395 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1396 CheckSubobjectKind CSK) { 1397 if (Designator.Invalid) 1398 return false; 1399 if (IsNullPtr) { 1400 Info.CCEDiag(E, diag::note_constexpr_null_subobject) 1401 << CSK; 1402 Designator.setInvalid(); 1403 return false; 1404 } 1405 return true; 1406 } 1407 1408 // Check this LValue refers to an object. If not, set the designator to be 1409 // invalid and emit a diagnostic. 1410 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1411 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1412 Designator.checkSubobject(Info, E, CSK); 1413 } 1414 1415 void addDecl(EvalInfo &Info, const Expr *E, 1416 const Decl *D, bool Virtual = false) { 1417 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1418 Designator.addDeclUnchecked(D, Virtual); 1419 } 1420 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1421 if (!Designator.Entries.empty()) { 1422 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1423 Designator.setInvalid(); 1424 return; 1425 } 1426 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1427 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1428 Designator.FirstEntryIsAnUnsizedArray = true; 1429 Designator.addUnsizedArrayUnchecked(ElemTy); 1430 } 1431 } 1432 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1433 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1434 Designator.addArrayUnchecked(CAT); 1435 } 1436 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1437 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1438 Designator.addComplexUnchecked(EltTy, Imag); 1439 } 1440 void clearIsNullPointer() { 1441 IsNullPtr = false; 1442 } 1443 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1444 const APSInt &Index, CharUnits ElementSize) { 1445 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1446 // but we're not required to diagnose it and it's valid in C++.) 1447 if (!Index) 1448 return; 1449 1450 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1451 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1452 // offsets. 1453 uint64_t Offset64 = Offset.getQuantity(); 1454 uint64_t ElemSize64 = ElementSize.getQuantity(); 1455 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1456 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1457 1458 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1459 Designator.adjustIndex(Info, E, Index); 1460 clearIsNullPointer(); 1461 } 1462 void adjustOffset(CharUnits N) { 1463 Offset += N; 1464 if (N.getQuantity()) 1465 clearIsNullPointer(); 1466 } 1467 }; 1468 1469 struct MemberPtr { 1470 MemberPtr() {} 1471 explicit MemberPtr(const ValueDecl *Decl) : 1472 DeclAndIsDerivedMember(Decl, false), Path() {} 1473 1474 /// The member or (direct or indirect) field referred to by this member 1475 /// pointer, or 0 if this is a null member pointer. 1476 const ValueDecl *getDecl() const { 1477 return DeclAndIsDerivedMember.getPointer(); 1478 } 1479 /// Is this actually a member of some type derived from the relevant class? 1480 bool isDerivedMember() const { 1481 return DeclAndIsDerivedMember.getInt(); 1482 } 1483 /// Get the class which the declaration actually lives in. 1484 const CXXRecordDecl *getContainingRecord() const { 1485 return cast<CXXRecordDecl>( 1486 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1487 } 1488 1489 void moveInto(APValue &V) const { 1490 V = APValue(getDecl(), isDerivedMember(), Path); 1491 } 1492 void setFrom(const APValue &V) { 1493 assert(V.isMemberPointer()); 1494 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1495 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1496 Path.clear(); 1497 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1498 Path.insert(Path.end(), P.begin(), P.end()); 1499 } 1500 1501 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1502 /// whether the member is a member of some class derived from the class type 1503 /// of the member pointer. 1504 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1505 /// Path - The path of base/derived classes from the member declaration's 1506 /// class (exclusive) to the class type of the member pointer (inclusive). 1507 SmallVector<const CXXRecordDecl*, 4> Path; 1508 1509 /// Perform a cast towards the class of the Decl (either up or down the 1510 /// hierarchy). 1511 bool castBack(const CXXRecordDecl *Class) { 1512 assert(!Path.empty()); 1513 const CXXRecordDecl *Expected; 1514 if (Path.size() >= 2) 1515 Expected = Path[Path.size() - 2]; 1516 else 1517 Expected = getContainingRecord(); 1518 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1519 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1520 // if B does not contain the original member and is not a base or 1521 // derived class of the class containing the original member, the result 1522 // of the cast is undefined. 1523 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1524 // (D::*). We consider that to be a language defect. 1525 return false; 1526 } 1527 Path.pop_back(); 1528 return true; 1529 } 1530 /// Perform a base-to-derived member pointer cast. 1531 bool castToDerived(const CXXRecordDecl *Derived) { 1532 if (!getDecl()) 1533 return true; 1534 if (!isDerivedMember()) { 1535 Path.push_back(Derived); 1536 return true; 1537 } 1538 if (!castBack(Derived)) 1539 return false; 1540 if (Path.empty()) 1541 DeclAndIsDerivedMember.setInt(false); 1542 return true; 1543 } 1544 /// Perform a derived-to-base member pointer cast. 1545 bool castToBase(const CXXRecordDecl *Base) { 1546 if (!getDecl()) 1547 return true; 1548 if (Path.empty()) 1549 DeclAndIsDerivedMember.setInt(true); 1550 if (isDerivedMember()) { 1551 Path.push_back(Base); 1552 return true; 1553 } 1554 return castBack(Base); 1555 } 1556 }; 1557 1558 /// Compare two member pointers, which are assumed to be of the same type. 1559 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1560 if (!LHS.getDecl() || !RHS.getDecl()) 1561 return !LHS.getDecl() && !RHS.getDecl(); 1562 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1563 return false; 1564 return LHS.Path == RHS.Path; 1565 } 1566 } 1567 1568 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1569 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1570 const LValue &This, const Expr *E, 1571 bool AllowNonLiteralTypes = false); 1572 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1573 bool InvalidBaseOK = false); 1574 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1575 bool InvalidBaseOK = false); 1576 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1577 EvalInfo &Info); 1578 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1579 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1580 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1581 EvalInfo &Info); 1582 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1583 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1584 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1585 EvalInfo &Info); 1586 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1587 1588 //===----------------------------------------------------------------------===// 1589 // Misc utilities 1590 //===----------------------------------------------------------------------===// 1591 1592 /// A helper function to create a temporary and set an LValue. 1593 template <class KeyTy> 1594 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended, 1595 LValue &LV, CallStackFrame &Frame) { 1596 LV.set({Key, Frame.Info.CurrentCall->Index, 1597 Frame.Info.CurrentCall->getTempVersion()}); 1598 return Frame.createTemporary(Key, IsLifetimeExtended); 1599 } 1600 1601 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1602 /// preserving its value (by extending by up to one bit as needed). 1603 static void negateAsSigned(APSInt &Int) { 1604 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1605 Int = Int.extend(Int.getBitWidth() + 1); 1606 Int.setIsSigned(true); 1607 } 1608 Int = -Int; 1609 } 1610 1611 /// Produce a string describing the given constexpr call. 1612 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) { 1613 unsigned ArgIndex = 0; 1614 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 1615 !isa<CXXConstructorDecl>(Frame->Callee) && 1616 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 1617 1618 if (!IsMemberCall) 1619 Out << *Frame->Callee << '('; 1620 1621 if (Frame->This && IsMemberCall) { 1622 APValue Val; 1623 Frame->This->moveInto(Val); 1624 Val.printPretty(Out, Frame->Info.Ctx, 1625 Frame->This->Designator.MostDerivedType); 1626 // FIXME: Add parens around Val if needed. 1627 Out << "->" << *Frame->Callee << '('; 1628 IsMemberCall = false; 1629 } 1630 1631 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 1632 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 1633 if (ArgIndex > (unsigned)IsMemberCall) 1634 Out << ", "; 1635 1636 const ParmVarDecl *Param = *I; 1637 const APValue &Arg = Frame->Arguments[ArgIndex]; 1638 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 1639 1640 if (ArgIndex == 0 && IsMemberCall) 1641 Out << "->" << *Frame->Callee << '('; 1642 } 1643 1644 Out << ')'; 1645 } 1646 1647 /// Evaluate an expression to see if it had side-effects, and discard its 1648 /// result. 1649 /// \return \c true if the caller should keep evaluating. 1650 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1651 APValue Scratch; 1652 if (!Evaluate(Scratch, Info, E)) 1653 // We don't need the value, but we might have skipped a side effect here. 1654 return Info.noteSideEffect(); 1655 return true; 1656 } 1657 1658 /// Should this call expression be treated as a string literal? 1659 static bool IsStringLiteralCall(const CallExpr *E) { 1660 unsigned Builtin = E->getBuiltinCallee(); 1661 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1662 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1663 } 1664 1665 static bool IsGlobalLValue(APValue::LValueBase B) { 1666 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1667 // constant expression of pointer type that evaluates to... 1668 1669 // ... a null pointer value, or a prvalue core constant expression of type 1670 // std::nullptr_t. 1671 if (!B) return true; 1672 1673 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1674 // ... the address of an object with static storage duration, 1675 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1676 return VD->hasGlobalStorage(); 1677 // ... the address of a function, 1678 return isa<FunctionDecl>(D); 1679 } 1680 1681 const Expr *E = B.get<const Expr*>(); 1682 switch (E->getStmtClass()) { 1683 default: 1684 return false; 1685 case Expr::CompoundLiteralExprClass: { 1686 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1687 return CLE->isFileScope() && CLE->isLValue(); 1688 } 1689 case Expr::MaterializeTemporaryExprClass: 1690 // A materialized temporary might have been lifetime-extended to static 1691 // storage duration. 1692 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1693 // A string literal has static storage duration. 1694 case Expr::StringLiteralClass: 1695 case Expr::PredefinedExprClass: 1696 case Expr::ObjCStringLiteralClass: 1697 case Expr::ObjCEncodeExprClass: 1698 case Expr::CXXTypeidExprClass: 1699 case Expr::CXXUuidofExprClass: 1700 return true; 1701 case Expr::CallExprClass: 1702 return IsStringLiteralCall(cast<CallExpr>(E)); 1703 // For GCC compatibility, &&label has static storage duration. 1704 case Expr::AddrLabelExprClass: 1705 return true; 1706 // A Block literal expression may be used as the initialization value for 1707 // Block variables at global or local static scope. 1708 case Expr::BlockExprClass: 1709 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1710 case Expr::ImplicitValueInitExprClass: 1711 // FIXME: 1712 // We can never form an lvalue with an implicit value initialization as its 1713 // base through expression evaluation, so these only appear in one case: the 1714 // implicit variable declaration we invent when checking whether a constexpr 1715 // constructor can produce a constant expression. We must assume that such 1716 // an expression might be a global lvalue. 1717 return true; 1718 } 1719 } 1720 1721 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1722 return LVal.Base.dyn_cast<const ValueDecl*>(); 1723 } 1724 1725 static bool IsLiteralLValue(const LValue &Value) { 1726 if (Value.getLValueCallIndex()) 1727 return false; 1728 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1729 return E && !isa<MaterializeTemporaryExpr>(E); 1730 } 1731 1732 static bool IsWeakLValue(const LValue &Value) { 1733 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1734 return Decl && Decl->isWeak(); 1735 } 1736 1737 static bool isZeroSized(const LValue &Value) { 1738 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1739 if (Decl && isa<VarDecl>(Decl)) { 1740 QualType Ty = Decl->getType(); 1741 if (Ty->isArrayType()) 1742 return Ty->isIncompleteType() || 1743 Decl->getASTContext().getTypeSize(Ty) == 0; 1744 } 1745 return false; 1746 } 1747 1748 static bool HasSameBase(const LValue &A, const LValue &B) { 1749 if (!A.getLValueBase()) 1750 return !B.getLValueBase(); 1751 if (!B.getLValueBase()) 1752 return false; 1753 1754 if (A.getLValueBase().getOpaqueValue() != 1755 B.getLValueBase().getOpaqueValue()) { 1756 const Decl *ADecl = GetLValueBaseDecl(A); 1757 if (!ADecl) 1758 return false; 1759 const Decl *BDecl = GetLValueBaseDecl(B); 1760 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1761 return false; 1762 } 1763 1764 return IsGlobalLValue(A.getLValueBase()) || 1765 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1766 A.getLValueVersion() == B.getLValueVersion()); 1767 } 1768 1769 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1770 assert(Base && "no location for a null lvalue"); 1771 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1772 if (VD) 1773 Info.Note(VD->getLocation(), diag::note_declared_at); 1774 else 1775 Info.Note(Base.get<const Expr*>()->getExprLoc(), 1776 diag::note_constexpr_temporary_here); 1777 } 1778 1779 /// Check that this reference or pointer core constant expression is a valid 1780 /// value for an address or reference constant expression. Return true if we 1781 /// can fold this expression, whether or not it's a constant expression. 1782 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1783 QualType Type, const LValue &LVal, 1784 Expr::ConstExprUsage Usage) { 1785 bool IsReferenceType = Type->isReferenceType(); 1786 1787 APValue::LValueBase Base = LVal.getLValueBase(); 1788 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1789 1790 // Check that the object is a global. Note that the fake 'this' object we 1791 // manufacture when checking potential constant expressions is conservatively 1792 // assumed to be global here. 1793 if (!IsGlobalLValue(Base)) { 1794 if (Info.getLangOpts().CPlusPlus11) { 1795 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1796 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1797 << IsReferenceType << !Designator.Entries.empty() 1798 << !!VD << VD; 1799 NoteLValueLocation(Info, Base); 1800 } else { 1801 Info.FFDiag(Loc); 1802 } 1803 // Don't allow references to temporaries to escape. 1804 return false; 1805 } 1806 assert((Info.checkingPotentialConstantExpression() || 1807 LVal.getLValueCallIndex() == 0) && 1808 "have call index for global lvalue"); 1809 1810 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1811 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1812 // Check if this is a thread-local variable. 1813 if (Var->getTLSKind()) 1814 return false; 1815 1816 // A dllimport variable never acts like a constant. 1817 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 1818 return false; 1819 } 1820 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1821 // __declspec(dllimport) must be handled very carefully: 1822 // We must never initialize an expression with the thunk in C++. 1823 // Doing otherwise would allow the same id-expression to yield 1824 // different addresses for the same function in different translation 1825 // units. However, this means that we must dynamically initialize the 1826 // expression with the contents of the import address table at runtime. 1827 // 1828 // The C language has no notion of ODR; furthermore, it has no notion of 1829 // dynamic initialization. This means that we are permitted to 1830 // perform initialization with the address of the thunk. 1831 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 1832 FD->hasAttr<DLLImportAttr>()) 1833 return false; 1834 } 1835 } 1836 1837 // Allow address constant expressions to be past-the-end pointers. This is 1838 // an extension: the standard requires them to point to an object. 1839 if (!IsReferenceType) 1840 return true; 1841 1842 // A reference constant expression must refer to an object. 1843 if (!Base) { 1844 // FIXME: diagnostic 1845 Info.CCEDiag(Loc); 1846 return true; 1847 } 1848 1849 // Does this refer one past the end of some object? 1850 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1851 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1852 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1853 << !Designator.Entries.empty() << !!VD << VD; 1854 NoteLValueLocation(Info, Base); 1855 } 1856 1857 return true; 1858 } 1859 1860 /// Member pointers are constant expressions unless they point to a 1861 /// non-virtual dllimport member function. 1862 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 1863 SourceLocation Loc, 1864 QualType Type, 1865 const APValue &Value, 1866 Expr::ConstExprUsage Usage) { 1867 const ValueDecl *Member = Value.getMemberPointerDecl(); 1868 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 1869 if (!FD) 1870 return true; 1871 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 1872 !FD->hasAttr<DLLImportAttr>(); 1873 } 1874 1875 /// Check that this core constant expression is of literal type, and if not, 1876 /// produce an appropriate diagnostic. 1877 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 1878 const LValue *This = nullptr) { 1879 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 1880 return true; 1881 1882 // C++1y: A constant initializer for an object o [...] may also invoke 1883 // constexpr constructors for o and its subobjects even if those objects 1884 // are of non-literal class types. 1885 // 1886 // C++11 missed this detail for aggregates, so classes like this: 1887 // struct foo_t { union { int i; volatile int j; } u; }; 1888 // are not (obviously) initializable like so: 1889 // __attribute__((__require_constant_initialization__)) 1890 // static const foo_t x = {{0}}; 1891 // because "i" is a subobject with non-literal initialization (due to the 1892 // volatile member of the union). See: 1893 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 1894 // Therefore, we use the C++1y behavior. 1895 if (This && Info.EvaluatingDecl == This->getLValueBase()) 1896 return true; 1897 1898 // Prvalue constant expressions must be of literal types. 1899 if (Info.getLangOpts().CPlusPlus11) 1900 Info.FFDiag(E, diag::note_constexpr_nonliteral) 1901 << E->getType(); 1902 else 1903 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 1904 return false; 1905 } 1906 1907 /// Check that this core constant expression value is a valid value for a 1908 /// constant expression. If not, report an appropriate diagnostic. Does not 1909 /// check that the expression is of literal type. 1910 static bool 1911 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 1912 const APValue &Value, 1913 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 1914 if (Value.isUninit()) { 1915 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 1916 << true << Type; 1917 return false; 1918 } 1919 1920 // We allow _Atomic(T) to be initialized from anything that T can be 1921 // initialized from. 1922 if (const AtomicType *AT = Type->getAs<AtomicType>()) 1923 Type = AT->getValueType(); 1924 1925 // Core issue 1454: For a literal constant expression of array or class type, 1926 // each subobject of its value shall have been initialized by a constant 1927 // expression. 1928 if (Value.isArray()) { 1929 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 1930 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 1931 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 1932 Value.getArrayInitializedElt(I), Usage)) 1933 return false; 1934 } 1935 if (!Value.hasArrayFiller()) 1936 return true; 1937 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(), 1938 Usage); 1939 } 1940 if (Value.isUnion() && Value.getUnionField()) { 1941 return CheckConstantExpression(Info, DiagLoc, 1942 Value.getUnionField()->getType(), 1943 Value.getUnionValue(), Usage); 1944 } 1945 if (Value.isStruct()) { 1946 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 1947 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 1948 unsigned BaseIndex = 0; 1949 for (const CXXBaseSpecifier &BS : CD->bases()) { 1950 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(), 1951 Value.getStructBase(BaseIndex), Usage)) 1952 return false; 1953 ++BaseIndex; 1954 } 1955 } 1956 for (const auto *I : RD->fields()) { 1957 if (I->isUnnamedBitfield()) 1958 continue; 1959 1960 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 1961 Value.getStructField(I->getFieldIndex()), 1962 Usage)) 1963 return false; 1964 } 1965 } 1966 1967 if (Value.isLValue()) { 1968 LValue LVal; 1969 LVal.setFrom(Info.Ctx, Value); 1970 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage); 1971 } 1972 1973 if (Value.isMemberPointer()) 1974 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 1975 1976 // Everything else is fine. 1977 return true; 1978 } 1979 1980 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 1981 // A null base expression indicates a null pointer. These are always 1982 // evaluatable, and they are false unless the offset is zero. 1983 if (!Value.getLValueBase()) { 1984 Result = !Value.getLValueOffset().isZero(); 1985 return true; 1986 } 1987 1988 // We have a non-null base. These are generally known to be true, but if it's 1989 // a weak declaration it can be null at runtime. 1990 Result = true; 1991 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 1992 return !Decl || !Decl->isWeak(); 1993 } 1994 1995 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 1996 switch (Val.getKind()) { 1997 case APValue::Uninitialized: 1998 return false; 1999 case APValue::Int: 2000 Result = Val.getInt().getBoolValue(); 2001 return true; 2002 case APValue::Float: 2003 Result = !Val.getFloat().isZero(); 2004 return true; 2005 case APValue::ComplexInt: 2006 Result = Val.getComplexIntReal().getBoolValue() || 2007 Val.getComplexIntImag().getBoolValue(); 2008 return true; 2009 case APValue::ComplexFloat: 2010 Result = !Val.getComplexFloatReal().isZero() || 2011 !Val.getComplexFloatImag().isZero(); 2012 return true; 2013 case APValue::LValue: 2014 return EvalPointerValueAsBool(Val, Result); 2015 case APValue::MemberPointer: 2016 Result = Val.getMemberPointerDecl(); 2017 return true; 2018 case APValue::Vector: 2019 case APValue::Array: 2020 case APValue::Struct: 2021 case APValue::Union: 2022 case APValue::AddrLabelDiff: 2023 return false; 2024 } 2025 2026 llvm_unreachable("unknown APValue kind"); 2027 } 2028 2029 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2030 EvalInfo &Info) { 2031 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2032 APValue Val; 2033 if (!Evaluate(Val, Info, E)) 2034 return false; 2035 return HandleConversionToBool(Val, Result); 2036 } 2037 2038 template<typename T> 2039 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2040 const T &SrcValue, QualType DestType) { 2041 Info.CCEDiag(E, diag::note_constexpr_overflow) 2042 << SrcValue << DestType; 2043 return Info.noteUndefinedBehavior(); 2044 } 2045 2046 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2047 QualType SrcType, const APFloat &Value, 2048 QualType DestType, APSInt &Result) { 2049 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2050 // Determine whether we are converting to unsigned or signed. 2051 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2052 2053 Result = APSInt(DestWidth, !DestSigned); 2054 bool ignored; 2055 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2056 & APFloat::opInvalidOp) 2057 return HandleOverflow(Info, E, Value, DestType); 2058 return true; 2059 } 2060 2061 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2062 QualType SrcType, QualType DestType, 2063 APFloat &Result) { 2064 APFloat Value = Result; 2065 bool ignored; 2066 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2067 APFloat::rmNearestTiesToEven, &ignored) 2068 & APFloat::opOverflow) 2069 return HandleOverflow(Info, E, Value, DestType); 2070 return true; 2071 } 2072 2073 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2074 QualType DestType, QualType SrcType, 2075 const APSInt &Value) { 2076 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2077 APSInt Result = Value; 2078 // Figure out if this is a truncate, extend or noop cast. 2079 // If the input is signed, do a sign extend, noop, or truncate. 2080 Result = Result.extOrTrunc(DestWidth); 2081 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2082 return Result; 2083 } 2084 2085 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2086 QualType SrcType, const APSInt &Value, 2087 QualType DestType, APFloat &Result) { 2088 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2089 if (Result.convertFromAPInt(Value, Value.isSigned(), 2090 APFloat::rmNearestTiesToEven) 2091 & APFloat::opOverflow) 2092 return HandleOverflow(Info, E, Value, DestType); 2093 return true; 2094 } 2095 2096 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2097 APValue &Value, const FieldDecl *FD) { 2098 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2099 2100 if (!Value.isInt()) { 2101 // Trying to store a pointer-cast-to-integer into a bitfield. 2102 // FIXME: In this case, we should provide the diagnostic for casting 2103 // a pointer to an integer. 2104 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2105 Info.FFDiag(E); 2106 return false; 2107 } 2108 2109 APSInt &Int = Value.getInt(); 2110 unsigned OldBitWidth = Int.getBitWidth(); 2111 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2112 if (NewBitWidth < OldBitWidth) 2113 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2114 return true; 2115 } 2116 2117 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2118 llvm::APInt &Res) { 2119 APValue SVal; 2120 if (!Evaluate(SVal, Info, E)) 2121 return false; 2122 if (SVal.isInt()) { 2123 Res = SVal.getInt(); 2124 return true; 2125 } 2126 if (SVal.isFloat()) { 2127 Res = SVal.getFloat().bitcastToAPInt(); 2128 return true; 2129 } 2130 if (SVal.isVector()) { 2131 QualType VecTy = E->getType(); 2132 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2133 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2134 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2135 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2136 Res = llvm::APInt::getNullValue(VecSize); 2137 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2138 APValue &Elt = SVal.getVectorElt(i); 2139 llvm::APInt EltAsInt; 2140 if (Elt.isInt()) { 2141 EltAsInt = Elt.getInt(); 2142 } else if (Elt.isFloat()) { 2143 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2144 } else { 2145 // Don't try to handle vectors of anything other than int or float 2146 // (not sure if it's possible to hit this case). 2147 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2148 return false; 2149 } 2150 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2151 if (BigEndian) 2152 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2153 else 2154 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2155 } 2156 return true; 2157 } 2158 // Give up if the input isn't an int, float, or vector. For example, we 2159 // reject "(v4i16)(intptr_t)&a". 2160 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2161 return false; 2162 } 2163 2164 /// Perform the given integer operation, which is known to need at most BitWidth 2165 /// bits, and check for overflow in the original type (if that type was not an 2166 /// unsigned type). 2167 template<typename Operation> 2168 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2169 const APSInt &LHS, const APSInt &RHS, 2170 unsigned BitWidth, Operation Op, 2171 APSInt &Result) { 2172 if (LHS.isUnsigned()) { 2173 Result = Op(LHS, RHS); 2174 return true; 2175 } 2176 2177 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2178 Result = Value.trunc(LHS.getBitWidth()); 2179 if (Result.extend(BitWidth) != Value) { 2180 if (Info.checkingForOverflow()) 2181 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2182 diag::warn_integer_constant_overflow) 2183 << Result.toString(10) << E->getType(); 2184 else 2185 return HandleOverflow(Info, E, Value, E->getType()); 2186 } 2187 return true; 2188 } 2189 2190 /// Perform the given binary integer operation. 2191 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2192 BinaryOperatorKind Opcode, APSInt RHS, 2193 APSInt &Result) { 2194 switch (Opcode) { 2195 default: 2196 Info.FFDiag(E); 2197 return false; 2198 case BO_Mul: 2199 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2200 std::multiplies<APSInt>(), Result); 2201 case BO_Add: 2202 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2203 std::plus<APSInt>(), Result); 2204 case BO_Sub: 2205 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2206 std::minus<APSInt>(), Result); 2207 case BO_And: Result = LHS & RHS; return true; 2208 case BO_Xor: Result = LHS ^ RHS; return true; 2209 case BO_Or: Result = LHS | RHS; return true; 2210 case BO_Div: 2211 case BO_Rem: 2212 if (RHS == 0) { 2213 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2214 return false; 2215 } 2216 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2217 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2218 // this operation and gives the two's complement result. 2219 if (RHS.isNegative() && RHS.isAllOnesValue() && 2220 LHS.isSigned() && LHS.isMinSignedValue()) 2221 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2222 E->getType()); 2223 return true; 2224 case BO_Shl: { 2225 if (Info.getLangOpts().OpenCL) 2226 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2227 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2228 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2229 RHS.isUnsigned()); 2230 else if (RHS.isSigned() && RHS.isNegative()) { 2231 // During constant-folding, a negative shift is an opposite shift. Such 2232 // a shift is not a constant expression. 2233 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2234 RHS = -RHS; 2235 goto shift_right; 2236 } 2237 shift_left: 2238 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2239 // the shifted type. 2240 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2241 if (SA != RHS) { 2242 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2243 << RHS << E->getType() << LHS.getBitWidth(); 2244 } else if (LHS.isSigned()) { 2245 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2246 // operand, and must not overflow the corresponding unsigned type. 2247 if (LHS.isNegative()) 2248 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2249 else if (LHS.countLeadingZeros() < SA) 2250 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2251 } 2252 Result = LHS << SA; 2253 return true; 2254 } 2255 case BO_Shr: { 2256 if (Info.getLangOpts().OpenCL) 2257 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2258 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2259 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2260 RHS.isUnsigned()); 2261 else if (RHS.isSigned() && RHS.isNegative()) { 2262 // During constant-folding, a negative shift is an opposite shift. Such a 2263 // shift is not a constant expression. 2264 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2265 RHS = -RHS; 2266 goto shift_left; 2267 } 2268 shift_right: 2269 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2270 // shifted type. 2271 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2272 if (SA != RHS) 2273 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2274 << RHS << E->getType() << LHS.getBitWidth(); 2275 Result = LHS >> SA; 2276 return true; 2277 } 2278 2279 case BO_LT: Result = LHS < RHS; return true; 2280 case BO_GT: Result = LHS > RHS; return true; 2281 case BO_LE: Result = LHS <= RHS; return true; 2282 case BO_GE: Result = LHS >= RHS; return true; 2283 case BO_EQ: Result = LHS == RHS; return true; 2284 case BO_NE: Result = LHS != RHS; return true; 2285 case BO_Cmp: 2286 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2287 } 2288 } 2289 2290 /// Perform the given binary floating-point operation, in-place, on LHS. 2291 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2292 APFloat &LHS, BinaryOperatorKind Opcode, 2293 const APFloat &RHS) { 2294 switch (Opcode) { 2295 default: 2296 Info.FFDiag(E); 2297 return false; 2298 case BO_Mul: 2299 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2300 break; 2301 case BO_Add: 2302 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2303 break; 2304 case BO_Sub: 2305 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2306 break; 2307 case BO_Div: 2308 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2309 break; 2310 } 2311 2312 if (LHS.isInfinity() || LHS.isNaN()) { 2313 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2314 return Info.noteUndefinedBehavior(); 2315 } 2316 return true; 2317 } 2318 2319 /// Cast an lvalue referring to a base subobject to a derived class, by 2320 /// truncating the lvalue's path to the given length. 2321 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2322 const RecordDecl *TruncatedType, 2323 unsigned TruncatedElements) { 2324 SubobjectDesignator &D = Result.Designator; 2325 2326 // Check we actually point to a derived class object. 2327 if (TruncatedElements == D.Entries.size()) 2328 return true; 2329 assert(TruncatedElements >= D.MostDerivedPathLength && 2330 "not casting to a derived class"); 2331 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2332 return false; 2333 2334 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2335 const RecordDecl *RD = TruncatedType; 2336 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2337 if (RD->isInvalidDecl()) return false; 2338 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2339 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2340 if (isVirtualBaseClass(D.Entries[I])) 2341 Result.Offset -= Layout.getVBaseClassOffset(Base); 2342 else 2343 Result.Offset -= Layout.getBaseClassOffset(Base); 2344 RD = Base; 2345 } 2346 D.Entries.resize(TruncatedElements); 2347 return true; 2348 } 2349 2350 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2351 const CXXRecordDecl *Derived, 2352 const CXXRecordDecl *Base, 2353 const ASTRecordLayout *RL = nullptr) { 2354 if (!RL) { 2355 if (Derived->isInvalidDecl()) return false; 2356 RL = &Info.Ctx.getASTRecordLayout(Derived); 2357 } 2358 2359 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2360 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2361 return true; 2362 } 2363 2364 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2365 const CXXRecordDecl *DerivedDecl, 2366 const CXXBaseSpecifier *Base) { 2367 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2368 2369 if (!Base->isVirtual()) 2370 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2371 2372 SubobjectDesignator &D = Obj.Designator; 2373 if (D.Invalid) 2374 return false; 2375 2376 // Extract most-derived object and corresponding type. 2377 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2378 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2379 return false; 2380 2381 // Find the virtual base class. 2382 if (DerivedDecl->isInvalidDecl()) return false; 2383 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2384 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2385 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2386 return true; 2387 } 2388 2389 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2390 QualType Type, LValue &Result) { 2391 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2392 PathE = E->path_end(); 2393 PathI != PathE; ++PathI) { 2394 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2395 *PathI)) 2396 return false; 2397 Type = (*PathI)->getType(); 2398 } 2399 return true; 2400 } 2401 2402 /// Update LVal to refer to the given field, which must be a member of the type 2403 /// currently described by LVal. 2404 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2405 const FieldDecl *FD, 2406 const ASTRecordLayout *RL = nullptr) { 2407 if (!RL) { 2408 if (FD->getParent()->isInvalidDecl()) return false; 2409 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2410 } 2411 2412 unsigned I = FD->getFieldIndex(); 2413 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2414 LVal.addDecl(Info, E, FD); 2415 return true; 2416 } 2417 2418 /// Update LVal to refer to the given indirect field. 2419 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2420 LValue &LVal, 2421 const IndirectFieldDecl *IFD) { 2422 for (const auto *C : IFD->chain()) 2423 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2424 return false; 2425 return true; 2426 } 2427 2428 /// Get the size of the given type in char units. 2429 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2430 QualType Type, CharUnits &Size) { 2431 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2432 // extension. 2433 if (Type->isVoidType() || Type->isFunctionType()) { 2434 Size = CharUnits::One(); 2435 return true; 2436 } 2437 2438 if (Type->isDependentType()) { 2439 Info.FFDiag(Loc); 2440 return false; 2441 } 2442 2443 if (!Type->isConstantSizeType()) { 2444 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2445 // FIXME: Better diagnostic. 2446 Info.FFDiag(Loc); 2447 return false; 2448 } 2449 2450 Size = Info.Ctx.getTypeSizeInChars(Type); 2451 return true; 2452 } 2453 2454 /// Update a pointer value to model pointer arithmetic. 2455 /// \param Info - Information about the ongoing evaluation. 2456 /// \param E - The expression being evaluated, for diagnostic purposes. 2457 /// \param LVal - The pointer value to be updated. 2458 /// \param EltTy - The pointee type represented by LVal. 2459 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2460 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2461 LValue &LVal, QualType EltTy, 2462 APSInt Adjustment) { 2463 CharUnits SizeOfPointee; 2464 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2465 return false; 2466 2467 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2468 return true; 2469 } 2470 2471 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2472 LValue &LVal, QualType EltTy, 2473 int64_t Adjustment) { 2474 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2475 APSInt::get(Adjustment)); 2476 } 2477 2478 /// Update an lvalue to refer to a component of a complex number. 2479 /// \param Info - Information about the ongoing evaluation. 2480 /// \param LVal - The lvalue to be updated. 2481 /// \param EltTy - The complex number's component type. 2482 /// \param Imag - False for the real component, true for the imaginary. 2483 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2484 LValue &LVal, QualType EltTy, 2485 bool Imag) { 2486 if (Imag) { 2487 CharUnits SizeOfComponent; 2488 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2489 return false; 2490 LVal.Offset += SizeOfComponent; 2491 } 2492 LVal.addComplex(Info, E, EltTy, Imag); 2493 return true; 2494 } 2495 2496 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 2497 QualType Type, const LValue &LVal, 2498 APValue &RVal); 2499 2500 /// Try to evaluate the initializer for a variable declaration. 2501 /// 2502 /// \param Info Information about the ongoing evaluation. 2503 /// \param E An expression to be used when printing diagnostics. 2504 /// \param VD The variable whose initializer should be obtained. 2505 /// \param Frame The frame in which the variable was created. Must be null 2506 /// if this variable is not local to the evaluation. 2507 /// \param Result Filled in with a pointer to the value of the variable. 2508 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2509 const VarDecl *VD, CallStackFrame *Frame, 2510 APValue *&Result, const LValue *LVal) { 2511 2512 // If this is a parameter to an active constexpr function call, perform 2513 // argument substitution. 2514 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2515 // Assume arguments of a potential constant expression are unknown 2516 // constant expressions. 2517 if (Info.checkingPotentialConstantExpression()) 2518 return false; 2519 if (!Frame || !Frame->Arguments) { 2520 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2521 return false; 2522 } 2523 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2524 return true; 2525 } 2526 2527 // If this is a local variable, dig out its value. 2528 if (Frame) { 2529 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 2530 : Frame->getCurrentTemporary(VD); 2531 if (!Result) { 2532 // Assume variables referenced within a lambda's call operator that were 2533 // not declared within the call operator are captures and during checking 2534 // of a potential constant expression, assume they are unknown constant 2535 // expressions. 2536 assert(isLambdaCallOperator(Frame->Callee) && 2537 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2538 "missing value for local variable"); 2539 if (Info.checkingPotentialConstantExpression()) 2540 return false; 2541 // FIXME: implement capture evaluation during constant expr evaluation. 2542 Info.FFDiag(E->getBeginLoc(), 2543 diag::note_unimplemented_constexpr_lambda_feature_ast) 2544 << "captures not currently allowed"; 2545 return false; 2546 } 2547 return true; 2548 } 2549 2550 // Dig out the initializer, and use the declaration which it's attached to. 2551 const Expr *Init = VD->getAnyInitializer(VD); 2552 if (!Init || Init->isValueDependent()) { 2553 // If we're checking a potential constant expression, the variable could be 2554 // initialized later. 2555 if (!Info.checkingPotentialConstantExpression()) 2556 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2557 return false; 2558 } 2559 2560 // If we're currently evaluating the initializer of this declaration, use that 2561 // in-flight value. 2562 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2563 Result = Info.EvaluatingDeclValue; 2564 return true; 2565 } 2566 2567 // Never evaluate the initializer of a weak variable. We can't be sure that 2568 // this is the definition which will be used. 2569 if (VD->isWeak()) { 2570 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2571 return false; 2572 } 2573 2574 // Check that we can fold the initializer. In C++, we will have already done 2575 // this in the cases where it matters for conformance. 2576 SmallVector<PartialDiagnosticAt, 8> Notes; 2577 if (!VD->evaluateValue(Notes)) { 2578 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2579 Notes.size() + 1) << VD; 2580 Info.Note(VD->getLocation(), diag::note_declared_at); 2581 Info.addNotes(Notes); 2582 return false; 2583 } else if (!VD->checkInitIsICE()) { 2584 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2585 Notes.size() + 1) << VD; 2586 Info.Note(VD->getLocation(), diag::note_declared_at); 2587 Info.addNotes(Notes); 2588 } 2589 2590 Result = VD->getEvaluatedValue(); 2591 return true; 2592 } 2593 2594 static bool IsConstNonVolatile(QualType T) { 2595 Qualifiers Quals = T.getQualifiers(); 2596 return Quals.hasConst() && !Quals.hasVolatile(); 2597 } 2598 2599 /// Get the base index of the given base class within an APValue representing 2600 /// the given derived class. 2601 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2602 const CXXRecordDecl *Base) { 2603 Base = Base->getCanonicalDecl(); 2604 unsigned Index = 0; 2605 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2606 E = Derived->bases_end(); I != E; ++I, ++Index) { 2607 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2608 return Index; 2609 } 2610 2611 llvm_unreachable("base class missing from derived class's bases list"); 2612 } 2613 2614 /// Extract the value of a character from a string literal. 2615 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2616 uint64_t Index) { 2617 // FIXME: Support MakeStringConstant 2618 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2619 std::string Str; 2620 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2621 assert(Index <= Str.size() && "Index too large"); 2622 return APSInt::getUnsigned(Str.c_str()[Index]); 2623 } 2624 2625 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2626 Lit = PE->getFunctionName(); 2627 const StringLiteral *S = cast<StringLiteral>(Lit); 2628 const ConstantArrayType *CAT = 2629 Info.Ctx.getAsConstantArrayType(S->getType()); 2630 assert(CAT && "string literal isn't an array"); 2631 QualType CharType = CAT->getElementType(); 2632 assert(CharType->isIntegerType() && "unexpected character type"); 2633 2634 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2635 CharType->isUnsignedIntegerType()); 2636 if (Index < S->getLength()) 2637 Value = S->getCodeUnit(Index); 2638 return Value; 2639 } 2640 2641 // Expand a string literal into an array of characters. 2642 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit, 2643 APValue &Result) { 2644 const StringLiteral *S = cast<StringLiteral>(Lit); 2645 const ConstantArrayType *CAT = 2646 Info.Ctx.getAsConstantArrayType(S->getType()); 2647 assert(CAT && "string literal isn't an array"); 2648 QualType CharType = CAT->getElementType(); 2649 assert(CharType->isIntegerType() && "unexpected character type"); 2650 2651 unsigned Elts = CAT->getSize().getZExtValue(); 2652 Result = APValue(APValue::UninitArray(), 2653 std::min(S->getLength(), Elts), Elts); 2654 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2655 CharType->isUnsignedIntegerType()); 2656 if (Result.hasArrayFiller()) 2657 Result.getArrayFiller() = APValue(Value); 2658 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2659 Value = S->getCodeUnit(I); 2660 Result.getArrayInitializedElt(I) = APValue(Value); 2661 } 2662 } 2663 2664 // Expand an array so that it has more than Index filled elements. 2665 static void expandArray(APValue &Array, unsigned Index) { 2666 unsigned Size = Array.getArraySize(); 2667 assert(Index < Size); 2668 2669 // Always at least double the number of elements for which we store a value. 2670 unsigned OldElts = Array.getArrayInitializedElts(); 2671 unsigned NewElts = std::max(Index+1, OldElts * 2); 2672 NewElts = std::min(Size, std::max(NewElts, 8u)); 2673 2674 // Copy the data across. 2675 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2676 for (unsigned I = 0; I != OldElts; ++I) 2677 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2678 for (unsigned I = OldElts; I != NewElts; ++I) 2679 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2680 if (NewValue.hasArrayFiller()) 2681 NewValue.getArrayFiller() = Array.getArrayFiller(); 2682 Array.swap(NewValue); 2683 } 2684 2685 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2686 /// conversion. If it's of class type, we may assume that the copy operation 2687 /// is trivial. Note that this is never true for a union type with fields 2688 /// (because the copy always "reads" the active member) and always true for 2689 /// a non-class type. 2690 static bool isReadByLvalueToRvalueConversion(QualType T) { 2691 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2692 if (!RD || (RD->isUnion() && !RD->field_empty())) 2693 return true; 2694 if (RD->isEmpty()) 2695 return false; 2696 2697 for (auto *Field : RD->fields()) 2698 if (isReadByLvalueToRvalueConversion(Field->getType())) 2699 return true; 2700 2701 for (auto &BaseSpec : RD->bases()) 2702 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2703 return true; 2704 2705 return false; 2706 } 2707 2708 /// Diagnose an attempt to read from any unreadable field within the specified 2709 /// type, which might be a class type. 2710 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2711 QualType T) { 2712 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2713 if (!RD) 2714 return false; 2715 2716 if (!RD->hasMutableFields()) 2717 return false; 2718 2719 for (auto *Field : RD->fields()) { 2720 // If we're actually going to read this field in some way, then it can't 2721 // be mutable. If we're in a union, then assigning to a mutable field 2722 // (even an empty one) can change the active member, so that's not OK. 2723 // FIXME: Add core issue number for the union case. 2724 if (Field->isMutable() && 2725 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2726 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2727 Info.Note(Field->getLocation(), diag::note_declared_at); 2728 return true; 2729 } 2730 2731 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2732 return true; 2733 } 2734 2735 for (auto &BaseSpec : RD->bases()) 2736 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2737 return true; 2738 2739 // All mutable fields were empty, and thus not actually read. 2740 return false; 2741 } 2742 2743 /// Kinds of access we can perform on an object, for diagnostics. 2744 enum AccessKinds { 2745 AK_Read, 2746 AK_Assign, 2747 AK_Increment, 2748 AK_Decrement 2749 }; 2750 2751 namespace { 2752 /// A handle to a complete object (an object that is not a subobject of 2753 /// another object). 2754 struct CompleteObject { 2755 /// The value of the complete object. 2756 APValue *Value; 2757 /// The type of the complete object. 2758 QualType Type; 2759 bool LifetimeStartedInEvaluation; 2760 2761 CompleteObject() : Value(nullptr) {} 2762 CompleteObject(APValue *Value, QualType Type, 2763 bool LifetimeStartedInEvaluation) 2764 : Value(Value), Type(Type), 2765 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) { 2766 assert(Value && "missing value for complete object"); 2767 } 2768 2769 explicit operator bool() const { return Value; } 2770 }; 2771 } // end anonymous namespace 2772 2773 /// Find the designated sub-object of an rvalue. 2774 template<typename SubobjectHandler> 2775 typename SubobjectHandler::result_type 2776 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2777 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2778 if (Sub.Invalid) 2779 // A diagnostic will have already been produced. 2780 return handler.failed(); 2781 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 2782 if (Info.getLangOpts().CPlusPlus11) 2783 Info.FFDiag(E, Sub.isOnePastTheEnd() 2784 ? diag::note_constexpr_access_past_end 2785 : diag::note_constexpr_access_unsized_array) 2786 << handler.AccessKind; 2787 else 2788 Info.FFDiag(E); 2789 return handler.failed(); 2790 } 2791 2792 APValue *O = Obj.Value; 2793 QualType ObjType = Obj.Type; 2794 const FieldDecl *LastField = nullptr; 2795 const bool MayReadMutableMembers = 2796 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14; 2797 2798 // Walk the designator's path to find the subobject. 2799 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 2800 if (O->isUninit()) { 2801 if (!Info.checkingPotentialConstantExpression()) 2802 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind; 2803 return handler.failed(); 2804 } 2805 2806 if (I == N) { 2807 // If we are reading an object of class type, there may still be more 2808 // things we need to check: if there are any mutable subobjects, we 2809 // cannot perform this read. (This only happens when performing a trivial 2810 // copy or assignment.) 2811 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 2812 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType)) 2813 return handler.failed(); 2814 2815 if (!handler.found(*O, ObjType)) 2816 return false; 2817 2818 // If we modified a bit-field, truncate it to the right width. 2819 if (handler.AccessKind != AK_Read && 2820 LastField && LastField->isBitField() && 2821 !truncateBitfieldValue(Info, E, *O, LastField)) 2822 return false; 2823 2824 return true; 2825 } 2826 2827 LastField = nullptr; 2828 if (ObjType->isArrayType()) { 2829 // Next subobject is an array element. 2830 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 2831 assert(CAT && "vla in literal type?"); 2832 uint64_t Index = Sub.Entries[I].ArrayIndex; 2833 if (CAT->getSize().ule(Index)) { 2834 // Note, it should not be possible to form a pointer with a valid 2835 // designator which points more than one past the end of the array. 2836 if (Info.getLangOpts().CPlusPlus11) 2837 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2838 << handler.AccessKind; 2839 else 2840 Info.FFDiag(E); 2841 return handler.failed(); 2842 } 2843 2844 ObjType = CAT->getElementType(); 2845 2846 // An array object is represented as either an Array APValue or as an 2847 // LValue which refers to a string literal. 2848 if (O->isLValue()) { 2849 assert(I == N - 1 && "extracting subobject of character?"); 2850 assert(!O->hasLValuePath() || O->getLValuePath().empty()); 2851 if (handler.AccessKind != AK_Read) 2852 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(), 2853 *O); 2854 else 2855 return handler.foundString(*O, ObjType, Index); 2856 } 2857 2858 if (O->getArrayInitializedElts() > Index) 2859 O = &O->getArrayInitializedElt(Index); 2860 else if (handler.AccessKind != AK_Read) { 2861 expandArray(*O, Index); 2862 O = &O->getArrayInitializedElt(Index); 2863 } else 2864 O = &O->getArrayFiller(); 2865 } else if (ObjType->isAnyComplexType()) { 2866 // Next subobject is a complex number. 2867 uint64_t Index = Sub.Entries[I].ArrayIndex; 2868 if (Index > 1) { 2869 if (Info.getLangOpts().CPlusPlus11) 2870 Info.FFDiag(E, diag::note_constexpr_access_past_end) 2871 << handler.AccessKind; 2872 else 2873 Info.FFDiag(E); 2874 return handler.failed(); 2875 } 2876 2877 bool WasConstQualified = ObjType.isConstQualified(); 2878 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 2879 if (WasConstQualified) 2880 ObjType.addConst(); 2881 2882 assert(I == N - 1 && "extracting subobject of scalar?"); 2883 if (O->isComplexInt()) { 2884 return handler.found(Index ? O->getComplexIntImag() 2885 : O->getComplexIntReal(), ObjType); 2886 } else { 2887 assert(O->isComplexFloat()); 2888 return handler.found(Index ? O->getComplexFloatImag() 2889 : O->getComplexFloatReal(), ObjType); 2890 } 2891 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 2892 // In C++14 onwards, it is permitted to read a mutable member whose 2893 // lifetime began within the evaluation. 2894 // FIXME: Should we also allow this in C++11? 2895 if (Field->isMutable() && handler.AccessKind == AK_Read && 2896 !MayReadMutableMembers) { 2897 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 2898 << Field; 2899 Info.Note(Field->getLocation(), diag::note_declared_at); 2900 return handler.failed(); 2901 } 2902 2903 // Next subobject is a class, struct or union field. 2904 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 2905 if (RD->isUnion()) { 2906 const FieldDecl *UnionField = O->getUnionField(); 2907 if (!UnionField || 2908 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 2909 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 2910 << handler.AccessKind << Field << !UnionField << UnionField; 2911 return handler.failed(); 2912 } 2913 O = &O->getUnionValue(); 2914 } else 2915 O = &O->getStructField(Field->getFieldIndex()); 2916 2917 bool WasConstQualified = ObjType.isConstQualified(); 2918 ObjType = Field->getType(); 2919 if (WasConstQualified && !Field->isMutable()) 2920 ObjType.addConst(); 2921 2922 if (ObjType.isVolatileQualified()) { 2923 if (Info.getLangOpts().CPlusPlus) { 2924 // FIXME: Include a description of the path to the volatile subobject. 2925 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 2926 << handler.AccessKind << 2 << Field; 2927 Info.Note(Field->getLocation(), diag::note_declared_at); 2928 } else { 2929 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2930 } 2931 return handler.failed(); 2932 } 2933 2934 LastField = Field; 2935 } else { 2936 // Next subobject is a base class. 2937 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 2938 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 2939 O = &O->getStructBase(getBaseIndex(Derived, Base)); 2940 2941 bool WasConstQualified = ObjType.isConstQualified(); 2942 ObjType = Info.Ctx.getRecordType(Base); 2943 if (WasConstQualified) 2944 ObjType.addConst(); 2945 } 2946 } 2947 } 2948 2949 namespace { 2950 struct ExtractSubobjectHandler { 2951 EvalInfo &Info; 2952 APValue &Result; 2953 2954 static const AccessKinds AccessKind = AK_Read; 2955 2956 typedef bool result_type; 2957 bool failed() { return false; } 2958 bool found(APValue &Subobj, QualType SubobjType) { 2959 Result = Subobj; 2960 return true; 2961 } 2962 bool found(APSInt &Value, QualType SubobjType) { 2963 Result = APValue(Value); 2964 return true; 2965 } 2966 bool found(APFloat &Value, QualType SubobjType) { 2967 Result = APValue(Value); 2968 return true; 2969 } 2970 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 2971 Result = APValue(extractStringLiteralCharacter( 2972 Info, Subobj.getLValueBase().get<const Expr *>(), Character)); 2973 return true; 2974 } 2975 }; 2976 } // end anonymous namespace 2977 2978 const AccessKinds ExtractSubobjectHandler::AccessKind; 2979 2980 /// Extract the designated sub-object of an rvalue. 2981 static bool extractSubobject(EvalInfo &Info, const Expr *E, 2982 const CompleteObject &Obj, 2983 const SubobjectDesignator &Sub, 2984 APValue &Result) { 2985 ExtractSubobjectHandler Handler = { Info, Result }; 2986 return findSubobject(Info, E, Obj, Sub, Handler); 2987 } 2988 2989 namespace { 2990 struct ModifySubobjectHandler { 2991 EvalInfo &Info; 2992 APValue &NewVal; 2993 const Expr *E; 2994 2995 typedef bool result_type; 2996 static const AccessKinds AccessKind = AK_Assign; 2997 2998 bool checkConst(QualType QT) { 2999 // Assigning to a const object has undefined behavior. 3000 if (QT.isConstQualified()) { 3001 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3002 return false; 3003 } 3004 return true; 3005 } 3006 3007 bool failed() { return false; } 3008 bool found(APValue &Subobj, QualType SubobjType) { 3009 if (!checkConst(SubobjType)) 3010 return false; 3011 // We've been given ownership of NewVal, so just swap it in. 3012 Subobj.swap(NewVal); 3013 return true; 3014 } 3015 bool found(APSInt &Value, QualType SubobjType) { 3016 if (!checkConst(SubobjType)) 3017 return false; 3018 if (!NewVal.isInt()) { 3019 // Maybe trying to write a cast pointer value into a complex? 3020 Info.FFDiag(E); 3021 return false; 3022 } 3023 Value = NewVal.getInt(); 3024 return true; 3025 } 3026 bool found(APFloat &Value, QualType SubobjType) { 3027 if (!checkConst(SubobjType)) 3028 return false; 3029 Value = NewVal.getFloat(); 3030 return true; 3031 } 3032 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3033 llvm_unreachable("shouldn't encounter string elements with ExpandArrays"); 3034 } 3035 }; 3036 } // end anonymous namespace 3037 3038 const AccessKinds ModifySubobjectHandler::AccessKind; 3039 3040 /// Update the designated sub-object of an rvalue to the given value. 3041 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3042 const CompleteObject &Obj, 3043 const SubobjectDesignator &Sub, 3044 APValue &NewVal) { 3045 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3046 return findSubobject(Info, E, Obj, Sub, Handler); 3047 } 3048 3049 /// Find the position where two subobject designators diverge, or equivalently 3050 /// the length of the common initial subsequence. 3051 static unsigned FindDesignatorMismatch(QualType ObjType, 3052 const SubobjectDesignator &A, 3053 const SubobjectDesignator &B, 3054 bool &WasArrayIndex) { 3055 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3056 for (/**/; I != N; ++I) { 3057 if (!ObjType.isNull() && 3058 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3059 // Next subobject is an array element. 3060 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) { 3061 WasArrayIndex = true; 3062 return I; 3063 } 3064 if (ObjType->isAnyComplexType()) 3065 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3066 else 3067 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3068 } else { 3069 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) { 3070 WasArrayIndex = false; 3071 return I; 3072 } 3073 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3074 // Next subobject is a field. 3075 ObjType = FD->getType(); 3076 else 3077 // Next subobject is a base class. 3078 ObjType = QualType(); 3079 } 3080 } 3081 WasArrayIndex = false; 3082 return I; 3083 } 3084 3085 /// Determine whether the given subobject designators refer to elements of the 3086 /// same array object. 3087 static bool AreElementsOfSameArray(QualType ObjType, 3088 const SubobjectDesignator &A, 3089 const SubobjectDesignator &B) { 3090 if (A.Entries.size() != B.Entries.size()) 3091 return false; 3092 3093 bool IsArray = A.MostDerivedIsArrayElement; 3094 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3095 // A is a subobject of the array element. 3096 return false; 3097 3098 // If A (and B) designates an array element, the last entry will be the array 3099 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3100 // of length 1' case, and the entire path must match. 3101 bool WasArrayIndex; 3102 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3103 return CommonLength >= A.Entries.size() - IsArray; 3104 } 3105 3106 /// Find the complete object to which an LValue refers. 3107 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3108 AccessKinds AK, const LValue &LVal, 3109 QualType LValType) { 3110 if (!LVal.Base) { 3111 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3112 return CompleteObject(); 3113 } 3114 3115 CallStackFrame *Frame = nullptr; 3116 if (LVal.getLValueCallIndex()) { 3117 Frame = Info.getCallFrame(LVal.getLValueCallIndex()); 3118 if (!Frame) { 3119 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3120 << AK << LVal.Base.is<const ValueDecl*>(); 3121 NoteLValueLocation(Info, LVal.Base); 3122 return CompleteObject(); 3123 } 3124 } 3125 3126 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3127 // is not a constant expression (even if the object is non-volatile). We also 3128 // apply this rule to C++98, in order to conform to the expected 'volatile' 3129 // semantics. 3130 if (LValType.isVolatileQualified()) { 3131 if (Info.getLangOpts().CPlusPlus) 3132 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3133 << AK << LValType; 3134 else 3135 Info.FFDiag(E); 3136 return CompleteObject(); 3137 } 3138 3139 // Compute value storage location and type of base object. 3140 APValue *BaseVal = nullptr; 3141 QualType BaseType = getType(LVal.Base); 3142 bool LifetimeStartedInEvaluation = Frame; 3143 3144 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3145 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3146 // In C++11, constexpr, non-volatile variables initialized with constant 3147 // expressions are constant expressions too. Inside constexpr functions, 3148 // parameters are constant expressions even if they're non-const. 3149 // In C++1y, objects local to a constant expression (those with a Frame) are 3150 // both readable and writable inside constant expressions. 3151 // In C, such things can also be folded, although they are not ICEs. 3152 const VarDecl *VD = dyn_cast<VarDecl>(D); 3153 if (VD) { 3154 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3155 VD = VDef; 3156 } 3157 if (!VD || VD->isInvalidDecl()) { 3158 Info.FFDiag(E); 3159 return CompleteObject(); 3160 } 3161 3162 // Accesses of volatile-qualified objects are not allowed. 3163 if (BaseType.isVolatileQualified()) { 3164 if (Info.getLangOpts().CPlusPlus) { 3165 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3166 << AK << 1 << VD; 3167 Info.Note(VD->getLocation(), diag::note_declared_at); 3168 } else { 3169 Info.FFDiag(E); 3170 } 3171 return CompleteObject(); 3172 } 3173 3174 // Unless we're looking at a local variable or argument in a constexpr call, 3175 // the variable we're reading must be const. 3176 if (!Frame) { 3177 if (Info.getLangOpts().CPlusPlus14 && 3178 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) { 3179 // OK, we can read and modify an object if we're in the process of 3180 // evaluating its initializer, because its lifetime began in this 3181 // evaluation. 3182 } else if (AK != AK_Read) { 3183 // All the remaining cases only permit reading. 3184 Info.FFDiag(E, diag::note_constexpr_modify_global); 3185 return CompleteObject(); 3186 } else if (VD->isConstexpr()) { 3187 // OK, we can read this variable. 3188 } else if (BaseType->isIntegralOrEnumerationType()) { 3189 // In OpenCL if a variable is in constant address space it is a const value. 3190 if (!(BaseType.isConstQualified() || 3191 (Info.getLangOpts().OpenCL && 3192 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3193 if (Info.getLangOpts().CPlusPlus) { 3194 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3195 Info.Note(VD->getLocation(), diag::note_declared_at); 3196 } else { 3197 Info.FFDiag(E); 3198 } 3199 return CompleteObject(); 3200 } 3201 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3202 // We support folding of const floating-point types, in order to make 3203 // static const data members of such types (supported as an extension) 3204 // more useful. 3205 if (Info.getLangOpts().CPlusPlus11) { 3206 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3207 Info.Note(VD->getLocation(), diag::note_declared_at); 3208 } else { 3209 Info.CCEDiag(E); 3210 } 3211 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3212 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3213 // Keep evaluating to see what we can do. 3214 } else { 3215 // FIXME: Allow folding of values of any literal type in all languages. 3216 if (Info.checkingPotentialConstantExpression() && 3217 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3218 // The definition of this variable could be constexpr. We can't 3219 // access it right now, but may be able to in future. 3220 } else if (Info.getLangOpts().CPlusPlus11) { 3221 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3222 Info.Note(VD->getLocation(), diag::note_declared_at); 3223 } else { 3224 Info.FFDiag(E); 3225 } 3226 return CompleteObject(); 3227 } 3228 } 3229 3230 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3231 return CompleteObject(); 3232 } else { 3233 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3234 3235 if (!Frame) { 3236 if (const MaterializeTemporaryExpr *MTE = 3237 dyn_cast<MaterializeTemporaryExpr>(Base)) { 3238 assert(MTE->getStorageDuration() == SD_Static && 3239 "should have a frame for a non-global materialized temporary"); 3240 3241 // Per C++1y [expr.const]p2: 3242 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3243 // - a [...] glvalue of integral or enumeration type that refers to 3244 // a non-volatile const object [...] 3245 // [...] 3246 // - a [...] glvalue of literal type that refers to a non-volatile 3247 // object whose lifetime began within the evaluation of e. 3248 // 3249 // C++11 misses the 'began within the evaluation of e' check and 3250 // instead allows all temporaries, including things like: 3251 // int &&r = 1; 3252 // int x = ++r; 3253 // constexpr int k = r; 3254 // Therefore we use the C++14 rules in C++11 too. 3255 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3256 const ValueDecl *ED = MTE->getExtendingDecl(); 3257 if (!(BaseType.isConstQualified() && 3258 BaseType->isIntegralOrEnumerationType()) && 3259 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 3260 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3261 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3262 return CompleteObject(); 3263 } 3264 3265 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3266 assert(BaseVal && "got reference to unevaluated temporary"); 3267 LifetimeStartedInEvaluation = true; 3268 } else { 3269 Info.FFDiag(E); 3270 return CompleteObject(); 3271 } 3272 } else { 3273 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3274 assert(BaseVal && "missing value for temporary"); 3275 } 3276 3277 // Volatile temporary objects cannot be accessed in constant expressions. 3278 if (BaseType.isVolatileQualified()) { 3279 if (Info.getLangOpts().CPlusPlus) { 3280 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3281 << AK << 0; 3282 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here); 3283 } else { 3284 Info.FFDiag(E); 3285 } 3286 return CompleteObject(); 3287 } 3288 } 3289 3290 // During the construction of an object, it is not yet 'const'. 3291 // FIXME: This doesn't do quite the right thing for const subobjects of the 3292 // object under construction. 3293 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), 3294 LVal.getLValueCallIndex(), 3295 LVal.getLValueVersion())) { 3296 BaseType = Info.Ctx.getCanonicalType(BaseType); 3297 BaseType.removeLocalConst(); 3298 LifetimeStartedInEvaluation = true; 3299 } 3300 3301 // In C++14, we can't safely access any mutable state when we might be 3302 // evaluating after an unmodeled side effect. 3303 // 3304 // FIXME: Not all local state is mutable. Allow local constant subobjects 3305 // to be read here (but take care with 'mutable' fields). 3306 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3307 Info.EvalStatus.HasSideEffects) || 3308 (AK != AK_Read && Info.IsSpeculativelyEvaluating)) 3309 return CompleteObject(); 3310 3311 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation); 3312 } 3313 3314 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3315 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3316 /// glvalue referred to by an entity of reference type. 3317 /// 3318 /// \param Info - Information about the ongoing evaluation. 3319 /// \param Conv - The expression for which we are performing the conversion. 3320 /// Used for diagnostics. 3321 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3322 /// case of a non-class type). 3323 /// \param LVal - The glvalue on which we are attempting to perform this action. 3324 /// \param RVal - The produced value will be placed here. 3325 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 3326 QualType Type, 3327 const LValue &LVal, APValue &RVal) { 3328 if (LVal.Designator.Invalid) 3329 return false; 3330 3331 // Check for special cases where there is no existing APValue to look at. 3332 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3333 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 3334 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3335 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3336 // initializer until now for such expressions. Such an expression can't be 3337 // an ICE in C, so this only matters for fold. 3338 if (Type.isVolatileQualified()) { 3339 Info.FFDiag(Conv); 3340 return false; 3341 } 3342 APValue Lit; 3343 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3344 return false; 3345 CompleteObject LitObj(&Lit, Base->getType(), false); 3346 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 3347 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3348 // We represent a string literal array as an lvalue pointing at the 3349 // corresponding expression, rather than building an array of chars. 3350 // FIXME: Support ObjCEncodeExpr, MakeStringConstant 3351 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0); 3352 CompleteObject StrObj(&Str, Base->getType(), false); 3353 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal); 3354 } 3355 } 3356 3357 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 3358 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 3359 } 3360 3361 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3362 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3363 QualType LValType, APValue &Val) { 3364 if (LVal.Designator.Invalid) 3365 return false; 3366 3367 if (!Info.getLangOpts().CPlusPlus14) { 3368 Info.FFDiag(E); 3369 return false; 3370 } 3371 3372 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3373 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3374 } 3375 3376 namespace { 3377 struct CompoundAssignSubobjectHandler { 3378 EvalInfo &Info; 3379 const Expr *E; 3380 QualType PromotedLHSType; 3381 BinaryOperatorKind Opcode; 3382 const APValue &RHS; 3383 3384 static const AccessKinds AccessKind = AK_Assign; 3385 3386 typedef bool result_type; 3387 3388 bool checkConst(QualType QT) { 3389 // Assigning to a const object has undefined behavior. 3390 if (QT.isConstQualified()) { 3391 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3392 return false; 3393 } 3394 return true; 3395 } 3396 3397 bool failed() { return false; } 3398 bool found(APValue &Subobj, QualType SubobjType) { 3399 switch (Subobj.getKind()) { 3400 case APValue::Int: 3401 return found(Subobj.getInt(), SubobjType); 3402 case APValue::Float: 3403 return found(Subobj.getFloat(), SubobjType); 3404 case APValue::ComplexInt: 3405 case APValue::ComplexFloat: 3406 // FIXME: Implement complex compound assignment. 3407 Info.FFDiag(E); 3408 return false; 3409 case APValue::LValue: 3410 return foundPointer(Subobj, SubobjType); 3411 default: 3412 // FIXME: can this happen? 3413 Info.FFDiag(E); 3414 return false; 3415 } 3416 } 3417 bool found(APSInt &Value, QualType SubobjType) { 3418 if (!checkConst(SubobjType)) 3419 return false; 3420 3421 if (!SubobjType->isIntegerType() || !RHS.isInt()) { 3422 // We don't support compound assignment on integer-cast-to-pointer 3423 // values. 3424 Info.FFDiag(E); 3425 return false; 3426 } 3427 3428 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType, 3429 SubobjType, Value); 3430 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3431 return false; 3432 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3433 return true; 3434 } 3435 bool found(APFloat &Value, QualType SubobjType) { 3436 return checkConst(SubobjType) && 3437 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3438 Value) && 3439 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3440 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3441 } 3442 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3443 if (!checkConst(SubobjType)) 3444 return false; 3445 3446 QualType PointeeType; 3447 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3448 PointeeType = PT->getPointeeType(); 3449 3450 if (PointeeType.isNull() || !RHS.isInt() || 3451 (Opcode != BO_Add && Opcode != BO_Sub)) { 3452 Info.FFDiag(E); 3453 return false; 3454 } 3455 3456 APSInt Offset = RHS.getInt(); 3457 if (Opcode == BO_Sub) 3458 negateAsSigned(Offset); 3459 3460 LValue LVal; 3461 LVal.setFrom(Info.Ctx, Subobj); 3462 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3463 return false; 3464 LVal.moveInto(Subobj); 3465 return true; 3466 } 3467 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3468 llvm_unreachable("shouldn't encounter string elements here"); 3469 } 3470 }; 3471 } // end anonymous namespace 3472 3473 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3474 3475 /// Perform a compound assignment of LVal <op>= RVal. 3476 static bool handleCompoundAssignment( 3477 EvalInfo &Info, const Expr *E, 3478 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3479 BinaryOperatorKind Opcode, const APValue &RVal) { 3480 if (LVal.Designator.Invalid) 3481 return false; 3482 3483 if (!Info.getLangOpts().CPlusPlus14) { 3484 Info.FFDiag(E); 3485 return false; 3486 } 3487 3488 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3489 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3490 RVal }; 3491 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3492 } 3493 3494 namespace { 3495 struct IncDecSubobjectHandler { 3496 EvalInfo &Info; 3497 const UnaryOperator *E; 3498 AccessKinds AccessKind; 3499 APValue *Old; 3500 3501 typedef bool result_type; 3502 3503 bool checkConst(QualType QT) { 3504 // Assigning to a const object has undefined behavior. 3505 if (QT.isConstQualified()) { 3506 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3507 return false; 3508 } 3509 return true; 3510 } 3511 3512 bool failed() { return false; } 3513 bool found(APValue &Subobj, QualType SubobjType) { 3514 // Stash the old value. Also clear Old, so we don't clobber it later 3515 // if we're post-incrementing a complex. 3516 if (Old) { 3517 *Old = Subobj; 3518 Old = nullptr; 3519 } 3520 3521 switch (Subobj.getKind()) { 3522 case APValue::Int: 3523 return found(Subobj.getInt(), SubobjType); 3524 case APValue::Float: 3525 return found(Subobj.getFloat(), SubobjType); 3526 case APValue::ComplexInt: 3527 return found(Subobj.getComplexIntReal(), 3528 SubobjType->castAs<ComplexType>()->getElementType() 3529 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3530 case APValue::ComplexFloat: 3531 return found(Subobj.getComplexFloatReal(), 3532 SubobjType->castAs<ComplexType>()->getElementType() 3533 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3534 case APValue::LValue: 3535 return foundPointer(Subobj, SubobjType); 3536 default: 3537 // FIXME: can this happen? 3538 Info.FFDiag(E); 3539 return false; 3540 } 3541 } 3542 bool found(APSInt &Value, QualType SubobjType) { 3543 if (!checkConst(SubobjType)) 3544 return false; 3545 3546 if (!SubobjType->isIntegerType()) { 3547 // We don't support increment / decrement on integer-cast-to-pointer 3548 // values. 3549 Info.FFDiag(E); 3550 return false; 3551 } 3552 3553 if (Old) *Old = APValue(Value); 3554 3555 // bool arithmetic promotes to int, and the conversion back to bool 3556 // doesn't reduce mod 2^n, so special-case it. 3557 if (SubobjType->isBooleanType()) { 3558 if (AccessKind == AK_Increment) 3559 Value = 1; 3560 else 3561 Value = !Value; 3562 return true; 3563 } 3564 3565 bool WasNegative = Value.isNegative(); 3566 if (AccessKind == AK_Increment) { 3567 ++Value; 3568 3569 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 3570 APSInt ActualValue(Value, /*IsUnsigned*/true); 3571 return HandleOverflow(Info, E, ActualValue, SubobjType); 3572 } 3573 } else { 3574 --Value; 3575 3576 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 3577 unsigned BitWidth = Value.getBitWidth(); 3578 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3579 ActualValue.setBit(BitWidth); 3580 return HandleOverflow(Info, E, ActualValue, SubobjType); 3581 } 3582 } 3583 return true; 3584 } 3585 bool found(APFloat &Value, QualType SubobjType) { 3586 if (!checkConst(SubobjType)) 3587 return false; 3588 3589 if (Old) *Old = APValue(Value); 3590 3591 APFloat One(Value.getSemantics(), 1); 3592 if (AccessKind == AK_Increment) 3593 Value.add(One, APFloat::rmNearestTiesToEven); 3594 else 3595 Value.subtract(One, APFloat::rmNearestTiesToEven); 3596 return true; 3597 } 3598 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3599 if (!checkConst(SubobjType)) 3600 return false; 3601 3602 QualType PointeeType; 3603 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3604 PointeeType = PT->getPointeeType(); 3605 else { 3606 Info.FFDiag(E); 3607 return false; 3608 } 3609 3610 LValue LVal; 3611 LVal.setFrom(Info.Ctx, Subobj); 3612 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3613 AccessKind == AK_Increment ? 1 : -1)) 3614 return false; 3615 LVal.moveInto(Subobj); 3616 return true; 3617 } 3618 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) { 3619 llvm_unreachable("shouldn't encounter string elements here"); 3620 } 3621 }; 3622 } // end anonymous namespace 3623 3624 /// Perform an increment or decrement on LVal. 3625 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3626 QualType LValType, bool IsIncrement, APValue *Old) { 3627 if (LVal.Designator.Invalid) 3628 return false; 3629 3630 if (!Info.getLangOpts().CPlusPlus14) { 3631 Info.FFDiag(E); 3632 return false; 3633 } 3634 3635 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3636 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3637 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 3638 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3639 } 3640 3641 /// Build an lvalue for the object argument of a member function call. 3642 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3643 LValue &This) { 3644 if (Object->getType()->isPointerType()) 3645 return EvaluatePointer(Object, This, Info); 3646 3647 if (Object->isGLValue()) 3648 return EvaluateLValue(Object, This, Info); 3649 3650 if (Object->getType()->isLiteralType(Info.Ctx)) 3651 return EvaluateTemporary(Object, This, Info); 3652 3653 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3654 return false; 3655 } 3656 3657 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3658 /// lvalue referring to the result. 3659 /// 3660 /// \param Info - Information about the ongoing evaluation. 3661 /// \param LV - An lvalue referring to the base of the member pointer. 3662 /// \param RHS - The member pointer expression. 3663 /// \param IncludeMember - Specifies whether the member itself is included in 3664 /// the resulting LValue subobject designator. This is not possible when 3665 /// creating a bound member function. 3666 /// \return The field or method declaration to which the member pointer refers, 3667 /// or 0 if evaluation fails. 3668 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3669 QualType LVType, 3670 LValue &LV, 3671 const Expr *RHS, 3672 bool IncludeMember = true) { 3673 MemberPtr MemPtr; 3674 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3675 return nullptr; 3676 3677 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3678 // member value, the behavior is undefined. 3679 if (!MemPtr.getDecl()) { 3680 // FIXME: Specific diagnostic. 3681 Info.FFDiag(RHS); 3682 return nullptr; 3683 } 3684 3685 if (MemPtr.isDerivedMember()) { 3686 // This is a member of some derived class. Truncate LV appropriately. 3687 // The end of the derived-to-base path for the base object must match the 3688 // derived-to-base path for the member pointer. 3689 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3690 LV.Designator.Entries.size()) { 3691 Info.FFDiag(RHS); 3692 return nullptr; 3693 } 3694 unsigned PathLengthToMember = 3695 LV.Designator.Entries.size() - MemPtr.Path.size(); 3696 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3697 const CXXRecordDecl *LVDecl = getAsBaseClass( 3698 LV.Designator.Entries[PathLengthToMember + I]); 3699 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3700 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3701 Info.FFDiag(RHS); 3702 return nullptr; 3703 } 3704 } 3705 3706 // Truncate the lvalue to the appropriate derived class. 3707 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3708 PathLengthToMember)) 3709 return nullptr; 3710 } else if (!MemPtr.Path.empty()) { 3711 // Extend the LValue path with the member pointer's path. 3712 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3713 MemPtr.Path.size() + IncludeMember); 3714 3715 // Walk down to the appropriate base class. 3716 if (const PointerType *PT = LVType->getAs<PointerType>()) 3717 LVType = PT->getPointeeType(); 3718 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3719 assert(RD && "member pointer access on non-class-type expression"); 3720 // The first class in the path is that of the lvalue. 3721 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3722 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3723 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3724 return nullptr; 3725 RD = Base; 3726 } 3727 // Finally cast to the class containing the member. 3728 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3729 MemPtr.getContainingRecord())) 3730 return nullptr; 3731 } 3732 3733 // Add the member. Note that we cannot build bound member functions here. 3734 if (IncludeMember) { 3735 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3736 if (!HandleLValueMember(Info, RHS, LV, FD)) 3737 return nullptr; 3738 } else if (const IndirectFieldDecl *IFD = 3739 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3740 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3741 return nullptr; 3742 } else { 3743 llvm_unreachable("can't construct reference to bound member function"); 3744 } 3745 } 3746 3747 return MemPtr.getDecl(); 3748 } 3749 3750 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3751 const BinaryOperator *BO, 3752 LValue &LV, 3753 bool IncludeMember = true) { 3754 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3755 3756 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3757 if (Info.noteFailure()) { 3758 MemberPtr MemPtr; 3759 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3760 } 3761 return nullptr; 3762 } 3763 3764 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3765 BO->getRHS(), IncludeMember); 3766 } 3767 3768 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3769 /// the provided lvalue, which currently refers to the base object. 3770 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3771 LValue &Result) { 3772 SubobjectDesignator &D = Result.Designator; 3773 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3774 return false; 3775 3776 QualType TargetQT = E->getType(); 3777 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 3778 TargetQT = PT->getPointeeType(); 3779 3780 // Check this cast lands within the final derived-to-base subobject path. 3781 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 3782 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3783 << D.MostDerivedType << TargetQT; 3784 return false; 3785 } 3786 3787 // Check the type of the final cast. We don't need to check the path, 3788 // since a cast can only be formed if the path is unique. 3789 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 3790 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 3791 const CXXRecordDecl *FinalType; 3792 if (NewEntriesSize == D.MostDerivedPathLength) 3793 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 3794 else 3795 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 3796 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 3797 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 3798 << D.MostDerivedType << TargetQT; 3799 return false; 3800 } 3801 3802 // Truncate the lvalue to the appropriate derived class. 3803 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 3804 } 3805 3806 namespace { 3807 enum EvalStmtResult { 3808 /// Evaluation failed. 3809 ESR_Failed, 3810 /// Hit a 'return' statement. 3811 ESR_Returned, 3812 /// Evaluation succeeded. 3813 ESR_Succeeded, 3814 /// Hit a 'continue' statement. 3815 ESR_Continue, 3816 /// Hit a 'break' statement. 3817 ESR_Break, 3818 /// Still scanning for 'case' or 'default' statement. 3819 ESR_CaseNotFound 3820 }; 3821 } 3822 3823 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 3824 // We don't need to evaluate the initializer for a static local. 3825 if (!VD->hasLocalStorage()) 3826 return true; 3827 3828 LValue Result; 3829 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall); 3830 3831 const Expr *InitE = VD->getInit(); 3832 if (!InitE) { 3833 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized) 3834 << false << VD->getType(); 3835 Val = APValue(); 3836 return false; 3837 } 3838 3839 if (InitE->isValueDependent()) 3840 return false; 3841 3842 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 3843 // Wipe out any partially-computed value, to allow tracking that this 3844 // evaluation failed. 3845 Val = APValue(); 3846 return false; 3847 } 3848 3849 return true; 3850 } 3851 3852 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 3853 bool OK = true; 3854 3855 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 3856 OK &= EvaluateVarDecl(Info, VD); 3857 3858 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 3859 for (auto *BD : DD->bindings()) 3860 if (auto *VD = BD->getHoldingVar()) 3861 OK &= EvaluateDecl(Info, VD); 3862 3863 return OK; 3864 } 3865 3866 3867 /// Evaluate a condition (either a variable declaration or an expression). 3868 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 3869 const Expr *Cond, bool &Result) { 3870 FullExpressionRAII Scope(Info); 3871 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 3872 return false; 3873 return EvaluateAsBooleanCondition(Cond, Result, Info); 3874 } 3875 3876 namespace { 3877 /// A location where the result (returned value) of evaluating a 3878 /// statement should be stored. 3879 struct StmtResult { 3880 /// The APValue that should be filled in with the returned value. 3881 APValue &Value; 3882 /// The location containing the result, if any (used to support RVO). 3883 const LValue *Slot; 3884 }; 3885 3886 struct TempVersionRAII { 3887 CallStackFrame &Frame; 3888 3889 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 3890 Frame.pushTempVersion(); 3891 } 3892 3893 ~TempVersionRAII() { 3894 Frame.popTempVersion(); 3895 } 3896 }; 3897 3898 } 3899 3900 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3901 const Stmt *S, 3902 const SwitchCase *SC = nullptr); 3903 3904 /// Evaluate the body of a loop, and translate the result as appropriate. 3905 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 3906 const Stmt *Body, 3907 const SwitchCase *Case = nullptr) { 3908 BlockScopeRAII Scope(Info); 3909 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 3910 case ESR_Break: 3911 return ESR_Succeeded; 3912 case ESR_Succeeded: 3913 case ESR_Continue: 3914 return ESR_Continue; 3915 case ESR_Failed: 3916 case ESR_Returned: 3917 case ESR_CaseNotFound: 3918 return ESR; 3919 } 3920 llvm_unreachable("Invalid EvalStmtResult!"); 3921 } 3922 3923 /// Evaluate a switch statement. 3924 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 3925 const SwitchStmt *SS) { 3926 BlockScopeRAII Scope(Info); 3927 3928 // Evaluate the switch condition. 3929 APSInt Value; 3930 { 3931 FullExpressionRAII Scope(Info); 3932 if (const Stmt *Init = SS->getInit()) { 3933 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 3934 if (ESR != ESR_Succeeded) 3935 return ESR; 3936 } 3937 if (SS->getConditionVariable() && 3938 !EvaluateDecl(Info, SS->getConditionVariable())) 3939 return ESR_Failed; 3940 if (!EvaluateInteger(SS->getCond(), Value, Info)) 3941 return ESR_Failed; 3942 } 3943 3944 // Find the switch case corresponding to the value of the condition. 3945 // FIXME: Cache this lookup. 3946 const SwitchCase *Found = nullptr; 3947 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 3948 SC = SC->getNextSwitchCase()) { 3949 if (isa<DefaultStmt>(SC)) { 3950 Found = SC; 3951 continue; 3952 } 3953 3954 const CaseStmt *CS = cast<CaseStmt>(SC); 3955 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 3956 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 3957 : LHS; 3958 if (LHS <= Value && Value <= RHS) { 3959 Found = SC; 3960 break; 3961 } 3962 } 3963 3964 if (!Found) 3965 return ESR_Succeeded; 3966 3967 // Search the switch body for the switch case and evaluate it from there. 3968 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 3969 case ESR_Break: 3970 return ESR_Succeeded; 3971 case ESR_Succeeded: 3972 case ESR_Continue: 3973 case ESR_Failed: 3974 case ESR_Returned: 3975 return ESR; 3976 case ESR_CaseNotFound: 3977 // This can only happen if the switch case is nested within a statement 3978 // expression. We have no intention of supporting that. 3979 Info.FFDiag(Found->getBeginLoc(), 3980 diag::note_constexpr_stmt_expr_unsupported); 3981 return ESR_Failed; 3982 } 3983 llvm_unreachable("Invalid EvalStmtResult!"); 3984 } 3985 3986 // Evaluate a statement. 3987 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 3988 const Stmt *S, const SwitchCase *Case) { 3989 if (!Info.nextStep(S)) 3990 return ESR_Failed; 3991 3992 // If we're hunting down a 'case' or 'default' label, recurse through 3993 // substatements until we hit the label. 3994 if (Case) { 3995 // FIXME: We don't start the lifetime of objects whose initialization we 3996 // jump over. However, such objects must be of class type with a trivial 3997 // default constructor that initialize all subobjects, so must be empty, 3998 // so this almost never matters. 3999 switch (S->getStmtClass()) { 4000 case Stmt::CompoundStmtClass: 4001 // FIXME: Precompute which substatement of a compound statement we 4002 // would jump to, and go straight there rather than performing a 4003 // linear scan each time. 4004 case Stmt::LabelStmtClass: 4005 case Stmt::AttributedStmtClass: 4006 case Stmt::DoStmtClass: 4007 break; 4008 4009 case Stmt::CaseStmtClass: 4010 case Stmt::DefaultStmtClass: 4011 if (Case == S) 4012 Case = nullptr; 4013 break; 4014 4015 case Stmt::IfStmtClass: { 4016 // FIXME: Precompute which side of an 'if' we would jump to, and go 4017 // straight there rather than scanning both sides. 4018 const IfStmt *IS = cast<IfStmt>(S); 4019 4020 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4021 // preceded by our switch label. 4022 BlockScopeRAII Scope(Info); 4023 4024 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4025 if (ESR != ESR_CaseNotFound || !IS->getElse()) 4026 return ESR; 4027 return EvaluateStmt(Result, Info, IS->getElse(), Case); 4028 } 4029 4030 case Stmt::WhileStmtClass: { 4031 EvalStmtResult ESR = 4032 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4033 if (ESR != ESR_Continue) 4034 return ESR; 4035 break; 4036 } 4037 4038 case Stmt::ForStmtClass: { 4039 const ForStmt *FS = cast<ForStmt>(S); 4040 EvalStmtResult ESR = 4041 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4042 if (ESR != ESR_Continue) 4043 return ESR; 4044 if (FS->getInc()) { 4045 FullExpressionRAII IncScope(Info); 4046 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4047 return ESR_Failed; 4048 } 4049 break; 4050 } 4051 4052 case Stmt::DeclStmtClass: 4053 // FIXME: If the variable has initialization that can't be jumped over, 4054 // bail out of any immediately-surrounding compound-statement too. 4055 default: 4056 return ESR_CaseNotFound; 4057 } 4058 } 4059 4060 switch (S->getStmtClass()) { 4061 default: 4062 if (const Expr *E = dyn_cast<Expr>(S)) { 4063 // Don't bother evaluating beyond an expression-statement which couldn't 4064 // be evaluated. 4065 FullExpressionRAII Scope(Info); 4066 if (!EvaluateIgnoredValue(Info, E)) 4067 return ESR_Failed; 4068 return ESR_Succeeded; 4069 } 4070 4071 Info.FFDiag(S->getBeginLoc()); 4072 return ESR_Failed; 4073 4074 case Stmt::NullStmtClass: 4075 return ESR_Succeeded; 4076 4077 case Stmt::DeclStmtClass: { 4078 const DeclStmt *DS = cast<DeclStmt>(S); 4079 for (const auto *DclIt : DS->decls()) { 4080 // Each declaration initialization is its own full-expression. 4081 // FIXME: This isn't quite right; if we're performing aggregate 4082 // initialization, each braced subexpression is its own full-expression. 4083 FullExpressionRAII Scope(Info); 4084 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 4085 return ESR_Failed; 4086 } 4087 return ESR_Succeeded; 4088 } 4089 4090 case Stmt::ReturnStmtClass: { 4091 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4092 FullExpressionRAII Scope(Info); 4093 if (RetExpr && 4094 !(Result.Slot 4095 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4096 : Evaluate(Result.Value, Info, RetExpr))) 4097 return ESR_Failed; 4098 return ESR_Returned; 4099 } 4100 4101 case Stmt::CompoundStmtClass: { 4102 BlockScopeRAII Scope(Info); 4103 4104 const CompoundStmt *CS = cast<CompoundStmt>(S); 4105 for (const auto *BI : CS->body()) { 4106 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4107 if (ESR == ESR_Succeeded) 4108 Case = nullptr; 4109 else if (ESR != ESR_CaseNotFound) 4110 return ESR; 4111 } 4112 return Case ? ESR_CaseNotFound : ESR_Succeeded; 4113 } 4114 4115 case Stmt::IfStmtClass: { 4116 const IfStmt *IS = cast<IfStmt>(S); 4117 4118 // Evaluate the condition, as either a var decl or as an expression. 4119 BlockScopeRAII Scope(Info); 4120 if (const Stmt *Init = IS->getInit()) { 4121 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4122 if (ESR != ESR_Succeeded) 4123 return ESR; 4124 } 4125 bool Cond; 4126 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4127 return ESR_Failed; 4128 4129 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4130 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4131 if (ESR != ESR_Succeeded) 4132 return ESR; 4133 } 4134 return ESR_Succeeded; 4135 } 4136 4137 case Stmt::WhileStmtClass: { 4138 const WhileStmt *WS = cast<WhileStmt>(S); 4139 while (true) { 4140 BlockScopeRAII Scope(Info); 4141 bool Continue; 4142 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4143 Continue)) 4144 return ESR_Failed; 4145 if (!Continue) 4146 break; 4147 4148 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4149 if (ESR != ESR_Continue) 4150 return ESR; 4151 } 4152 return ESR_Succeeded; 4153 } 4154 4155 case Stmt::DoStmtClass: { 4156 const DoStmt *DS = cast<DoStmt>(S); 4157 bool Continue; 4158 do { 4159 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4160 if (ESR != ESR_Continue) 4161 return ESR; 4162 Case = nullptr; 4163 4164 FullExpressionRAII CondScope(Info); 4165 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 4166 return ESR_Failed; 4167 } while (Continue); 4168 return ESR_Succeeded; 4169 } 4170 4171 case Stmt::ForStmtClass: { 4172 const ForStmt *FS = cast<ForStmt>(S); 4173 BlockScopeRAII Scope(Info); 4174 if (FS->getInit()) { 4175 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4176 if (ESR != ESR_Succeeded) 4177 return ESR; 4178 } 4179 while (true) { 4180 BlockScopeRAII Scope(Info); 4181 bool Continue = true; 4182 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4183 FS->getCond(), Continue)) 4184 return ESR_Failed; 4185 if (!Continue) 4186 break; 4187 4188 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4189 if (ESR != ESR_Continue) 4190 return ESR; 4191 4192 if (FS->getInc()) { 4193 FullExpressionRAII IncScope(Info); 4194 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4195 return ESR_Failed; 4196 } 4197 } 4198 return ESR_Succeeded; 4199 } 4200 4201 case Stmt::CXXForRangeStmtClass: { 4202 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4203 BlockScopeRAII Scope(Info); 4204 4205 // Evaluate the init-statement if present. 4206 if (FS->getInit()) { 4207 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4208 if (ESR != ESR_Succeeded) 4209 return ESR; 4210 } 4211 4212 // Initialize the __range variable. 4213 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4214 if (ESR != ESR_Succeeded) 4215 return ESR; 4216 4217 // Create the __begin and __end iterators. 4218 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4219 if (ESR != ESR_Succeeded) 4220 return ESR; 4221 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4222 if (ESR != ESR_Succeeded) 4223 return ESR; 4224 4225 while (true) { 4226 // Condition: __begin != __end. 4227 { 4228 bool Continue = true; 4229 FullExpressionRAII CondExpr(Info); 4230 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4231 return ESR_Failed; 4232 if (!Continue) 4233 break; 4234 } 4235 4236 // User's variable declaration, initialized by *__begin. 4237 BlockScopeRAII InnerScope(Info); 4238 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4239 if (ESR != ESR_Succeeded) 4240 return ESR; 4241 4242 // Loop body. 4243 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4244 if (ESR != ESR_Continue) 4245 return ESR; 4246 4247 // Increment: ++__begin 4248 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4249 return ESR_Failed; 4250 } 4251 4252 return ESR_Succeeded; 4253 } 4254 4255 case Stmt::SwitchStmtClass: 4256 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4257 4258 case Stmt::ContinueStmtClass: 4259 return ESR_Continue; 4260 4261 case Stmt::BreakStmtClass: 4262 return ESR_Break; 4263 4264 case Stmt::LabelStmtClass: 4265 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4266 4267 case Stmt::AttributedStmtClass: 4268 // As a general principle, C++11 attributes can be ignored without 4269 // any semantic impact. 4270 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4271 Case); 4272 4273 case Stmt::CaseStmtClass: 4274 case Stmt::DefaultStmtClass: 4275 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4276 } 4277 } 4278 4279 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4280 /// default constructor. If so, we'll fold it whether or not it's marked as 4281 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4282 /// so we need special handling. 4283 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4284 const CXXConstructorDecl *CD, 4285 bool IsValueInitialization) { 4286 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4287 return false; 4288 4289 // Value-initialization does not call a trivial default constructor, so such a 4290 // call is a core constant expression whether or not the constructor is 4291 // constexpr. 4292 if (!CD->isConstexpr() && !IsValueInitialization) { 4293 if (Info.getLangOpts().CPlusPlus11) { 4294 // FIXME: If DiagDecl is an implicitly-declared special member function, 4295 // we should be much more explicit about why it's not constexpr. 4296 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4297 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4298 Info.Note(CD->getLocation(), diag::note_declared_at); 4299 } else { 4300 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4301 } 4302 } 4303 return true; 4304 } 4305 4306 /// CheckConstexprFunction - Check that a function can be called in a constant 4307 /// expression. 4308 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4309 const FunctionDecl *Declaration, 4310 const FunctionDecl *Definition, 4311 const Stmt *Body) { 4312 // Potential constant expressions can contain calls to declared, but not yet 4313 // defined, constexpr functions. 4314 if (Info.checkingPotentialConstantExpression() && !Definition && 4315 Declaration->isConstexpr()) 4316 return false; 4317 4318 // Bail out if the function declaration itself is invalid. We will 4319 // have produced a relevant diagnostic while parsing it, so just 4320 // note the problematic sub-expression. 4321 if (Declaration->isInvalidDecl()) { 4322 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4323 return false; 4324 } 4325 4326 // Can we evaluate this function call? 4327 if (Definition && Definition->isConstexpr() && 4328 !Definition->isInvalidDecl() && Body) 4329 return true; 4330 4331 if (Info.getLangOpts().CPlusPlus11) { 4332 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4333 4334 // If this function is not constexpr because it is an inherited 4335 // non-constexpr constructor, diagnose that directly. 4336 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4337 if (CD && CD->isInheritingConstructor()) { 4338 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4339 if (!Inherited->isConstexpr()) 4340 DiagDecl = CD = Inherited; 4341 } 4342 4343 // FIXME: If DiagDecl is an implicitly-declared special member function 4344 // or an inheriting constructor, we should be much more explicit about why 4345 // it's not constexpr. 4346 if (CD && CD->isInheritingConstructor()) 4347 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4348 << CD->getInheritedConstructor().getConstructor()->getParent(); 4349 else 4350 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4351 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4352 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4353 } else { 4354 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4355 } 4356 return false; 4357 } 4358 4359 /// Determine if a class has any fields that might need to be copied by a 4360 /// trivial copy or move operation. 4361 static bool hasFields(const CXXRecordDecl *RD) { 4362 if (!RD || RD->isEmpty()) 4363 return false; 4364 for (auto *FD : RD->fields()) { 4365 if (FD->isUnnamedBitfield()) 4366 continue; 4367 return true; 4368 } 4369 for (auto &Base : RD->bases()) 4370 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 4371 return true; 4372 return false; 4373 } 4374 4375 namespace { 4376 typedef SmallVector<APValue, 8> ArgVector; 4377 } 4378 4379 /// EvaluateArgs - Evaluate the arguments to a function call. 4380 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 4381 EvalInfo &Info) { 4382 bool Success = true; 4383 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 4384 I != E; ++I) { 4385 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 4386 // If we're checking for a potential constant expression, evaluate all 4387 // initializers even if some of them fail. 4388 if (!Info.noteFailure()) 4389 return false; 4390 Success = false; 4391 } 4392 } 4393 return Success; 4394 } 4395 4396 /// Evaluate a function call. 4397 static bool HandleFunctionCall(SourceLocation CallLoc, 4398 const FunctionDecl *Callee, const LValue *This, 4399 ArrayRef<const Expr*> Args, const Stmt *Body, 4400 EvalInfo &Info, APValue &Result, 4401 const LValue *ResultSlot) { 4402 ArgVector ArgValues(Args.size()); 4403 if (!EvaluateArgs(Args, ArgValues, Info)) 4404 return false; 4405 4406 if (!Info.CheckCallLimit(CallLoc)) 4407 return false; 4408 4409 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 4410 4411 // For a trivial copy or move assignment, perform an APValue copy. This is 4412 // essential for unions, where the operations performed by the assignment 4413 // operator cannot be represented as statements. 4414 // 4415 // Skip this for non-union classes with no fields; in that case, the defaulted 4416 // copy/move does not actually read the object. 4417 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 4418 if (MD && MD->isDefaulted() && 4419 (MD->getParent()->isUnion() || 4420 (MD->isTrivial() && hasFields(MD->getParent())))) { 4421 assert(This && 4422 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 4423 LValue RHS; 4424 RHS.setFrom(Info.Ctx, ArgValues[0]); 4425 APValue RHSValue; 4426 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 4427 RHS, RHSValue)) 4428 return false; 4429 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx), 4430 RHSValue)) 4431 return false; 4432 This->moveInto(Result); 4433 return true; 4434 } else if (MD && isLambdaCallOperator(MD)) { 4435 // We're in a lambda; determine the lambda capture field maps unless we're 4436 // just constexpr checking a lambda's call operator. constexpr checking is 4437 // done before the captures have been added to the closure object (unless 4438 // we're inferring constexpr-ness), so we don't have access to them in this 4439 // case. But since we don't need the captures to constexpr check, we can 4440 // just ignore them. 4441 if (!Info.checkingPotentialConstantExpression()) 4442 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 4443 Frame.LambdaThisCaptureField); 4444 } 4445 4446 StmtResult Ret = {Result, ResultSlot}; 4447 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 4448 if (ESR == ESR_Succeeded) { 4449 if (Callee->getReturnType()->isVoidType()) 4450 return true; 4451 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 4452 } 4453 return ESR == ESR_Returned; 4454 } 4455 4456 /// Evaluate a constructor call. 4457 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4458 APValue *ArgValues, 4459 const CXXConstructorDecl *Definition, 4460 EvalInfo &Info, APValue &Result) { 4461 SourceLocation CallLoc = E->getExprLoc(); 4462 if (!Info.CheckCallLimit(CallLoc)) 4463 return false; 4464 4465 const CXXRecordDecl *RD = Definition->getParent(); 4466 if (RD->getNumVBases()) { 4467 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 4468 return false; 4469 } 4470 4471 EvalInfo::EvaluatingConstructorRAII EvalObj( 4472 Info, {This.getLValueBase(), 4473 {This.getLValueCallIndex(), This.getLValueVersion()}}); 4474 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 4475 4476 // FIXME: Creating an APValue just to hold a nonexistent return value is 4477 // wasteful. 4478 APValue RetVal; 4479 StmtResult Ret = {RetVal, nullptr}; 4480 4481 // If it's a delegating constructor, delegate. 4482 if (Definition->isDelegatingConstructor()) { 4483 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 4484 { 4485 FullExpressionRAII InitScope(Info); 4486 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 4487 return false; 4488 } 4489 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4490 } 4491 4492 // For a trivial copy or move constructor, perform an APValue copy. This is 4493 // essential for unions (or classes with anonymous union members), where the 4494 // operations performed by the constructor cannot be represented by 4495 // ctor-initializers. 4496 // 4497 // Skip this for empty non-union classes; we should not perform an 4498 // lvalue-to-rvalue conversion on them because their copy constructor does not 4499 // actually read them. 4500 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 4501 (Definition->getParent()->isUnion() || 4502 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 4503 LValue RHS; 4504 RHS.setFrom(Info.Ctx, ArgValues[0]); 4505 return handleLValueToRValueConversion( 4506 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 4507 RHS, Result); 4508 } 4509 4510 // Reserve space for the struct members. 4511 if (!RD->isUnion() && Result.isUninit()) 4512 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 4513 std::distance(RD->field_begin(), RD->field_end())); 4514 4515 if (RD->isInvalidDecl()) return false; 4516 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 4517 4518 // A scope for temporaries lifetime-extended by reference members. 4519 BlockScopeRAII LifetimeExtendedScope(Info); 4520 4521 bool Success = true; 4522 unsigned BasesSeen = 0; 4523 #ifndef NDEBUG 4524 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 4525 #endif 4526 for (const auto *I : Definition->inits()) { 4527 LValue Subobject = This; 4528 LValue SubobjectParent = This; 4529 APValue *Value = &Result; 4530 4531 // Determine the subobject to initialize. 4532 FieldDecl *FD = nullptr; 4533 if (I->isBaseInitializer()) { 4534 QualType BaseType(I->getBaseClass(), 0); 4535 #ifndef NDEBUG 4536 // Non-virtual base classes are initialized in the order in the class 4537 // definition. We have already checked for virtual base classes. 4538 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 4539 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 4540 "base class initializers not in expected order"); 4541 ++BaseIt; 4542 #endif 4543 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 4544 BaseType->getAsCXXRecordDecl(), &Layout)) 4545 return false; 4546 Value = &Result.getStructBase(BasesSeen++); 4547 } else if ((FD = I->getMember())) { 4548 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 4549 return false; 4550 if (RD->isUnion()) { 4551 Result = APValue(FD); 4552 Value = &Result.getUnionValue(); 4553 } else { 4554 Value = &Result.getStructField(FD->getFieldIndex()); 4555 } 4556 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 4557 // Walk the indirect field decl's chain to find the object to initialize, 4558 // and make sure we've initialized every step along it. 4559 auto IndirectFieldChain = IFD->chain(); 4560 for (auto *C : IndirectFieldChain) { 4561 FD = cast<FieldDecl>(C); 4562 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 4563 // Switch the union field if it differs. This happens if we had 4564 // preceding zero-initialization, and we're now initializing a union 4565 // subobject other than the first. 4566 // FIXME: In this case, the values of the other subobjects are 4567 // specified, since zero-initialization sets all padding bits to zero. 4568 if (Value->isUninit() || 4569 (Value->isUnion() && Value->getUnionField() != FD)) { 4570 if (CD->isUnion()) 4571 *Value = APValue(FD); 4572 else 4573 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 4574 std::distance(CD->field_begin(), CD->field_end())); 4575 } 4576 // Store Subobject as its parent before updating it for the last element 4577 // in the chain. 4578 if (C == IndirectFieldChain.back()) 4579 SubobjectParent = Subobject; 4580 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 4581 return false; 4582 if (CD->isUnion()) 4583 Value = &Value->getUnionValue(); 4584 else 4585 Value = &Value->getStructField(FD->getFieldIndex()); 4586 } 4587 } else { 4588 llvm_unreachable("unknown base initializer kind"); 4589 } 4590 4591 // Need to override This for implicit field initializers as in this case 4592 // This refers to innermost anonymous struct/union containing initializer, 4593 // not to currently constructed class. 4594 const Expr *Init = I->getInit(); 4595 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 4596 isa<CXXDefaultInitExpr>(Init)); 4597 FullExpressionRAII InitScope(Info); 4598 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 4599 (FD && FD->isBitField() && 4600 !truncateBitfieldValue(Info, Init, *Value, FD))) { 4601 // If we're checking for a potential constant expression, evaluate all 4602 // initializers even if some of them fail. 4603 if (!Info.noteFailure()) 4604 return false; 4605 Success = false; 4606 } 4607 } 4608 4609 return Success && 4610 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 4611 } 4612 4613 static bool HandleConstructorCall(const Expr *E, const LValue &This, 4614 ArrayRef<const Expr*> Args, 4615 const CXXConstructorDecl *Definition, 4616 EvalInfo &Info, APValue &Result) { 4617 ArgVector ArgValues(Args.size()); 4618 if (!EvaluateArgs(Args, ArgValues, Info)) 4619 return false; 4620 4621 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 4622 Info, Result); 4623 } 4624 4625 //===----------------------------------------------------------------------===// 4626 // Generic Evaluation 4627 //===----------------------------------------------------------------------===// 4628 namespace { 4629 4630 template <class Derived> 4631 class ExprEvaluatorBase 4632 : public ConstStmtVisitor<Derived, bool> { 4633 private: 4634 Derived &getDerived() { return static_cast<Derived&>(*this); } 4635 bool DerivedSuccess(const APValue &V, const Expr *E) { 4636 return getDerived().Success(V, E); 4637 } 4638 bool DerivedZeroInitialization(const Expr *E) { 4639 return getDerived().ZeroInitialization(E); 4640 } 4641 4642 // Check whether a conditional operator with a non-constant condition is a 4643 // potential constant expression. If neither arm is a potential constant 4644 // expression, then the conditional operator is not either. 4645 template<typename ConditionalOperator> 4646 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 4647 assert(Info.checkingPotentialConstantExpression()); 4648 4649 // Speculatively evaluate both arms. 4650 SmallVector<PartialDiagnosticAt, 8> Diag; 4651 { 4652 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4653 StmtVisitorTy::Visit(E->getFalseExpr()); 4654 if (Diag.empty()) 4655 return; 4656 } 4657 4658 { 4659 SpeculativeEvaluationRAII Speculate(Info, &Diag); 4660 Diag.clear(); 4661 StmtVisitorTy::Visit(E->getTrueExpr()); 4662 if (Diag.empty()) 4663 return; 4664 } 4665 4666 Error(E, diag::note_constexpr_conditional_never_const); 4667 } 4668 4669 4670 template<typename ConditionalOperator> 4671 bool HandleConditionalOperator(const ConditionalOperator *E) { 4672 bool BoolResult; 4673 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 4674 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 4675 CheckPotentialConstantConditional(E); 4676 return false; 4677 } 4678 if (Info.noteFailure()) { 4679 StmtVisitorTy::Visit(E->getTrueExpr()); 4680 StmtVisitorTy::Visit(E->getFalseExpr()); 4681 } 4682 return false; 4683 } 4684 4685 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 4686 return StmtVisitorTy::Visit(EvalExpr); 4687 } 4688 4689 protected: 4690 EvalInfo &Info; 4691 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 4692 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 4693 4694 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 4695 return Info.CCEDiag(E, D); 4696 } 4697 4698 bool ZeroInitialization(const Expr *E) { return Error(E); } 4699 4700 public: 4701 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 4702 4703 EvalInfo &getEvalInfo() { return Info; } 4704 4705 /// Report an evaluation error. This should only be called when an error is 4706 /// first discovered. When propagating an error, just return false. 4707 bool Error(const Expr *E, diag::kind D) { 4708 Info.FFDiag(E, D); 4709 return false; 4710 } 4711 bool Error(const Expr *E) { 4712 return Error(E, diag::note_invalid_subexpr_in_const_expr); 4713 } 4714 4715 bool VisitStmt(const Stmt *) { 4716 llvm_unreachable("Expression evaluator should not be called on stmts"); 4717 } 4718 bool VisitExpr(const Expr *E) { 4719 return Error(E); 4720 } 4721 4722 bool VisitParenExpr(const ParenExpr *E) 4723 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4724 bool VisitUnaryExtension(const UnaryOperator *E) 4725 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4726 bool VisitUnaryPlus(const UnaryOperator *E) 4727 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4728 bool VisitChooseExpr(const ChooseExpr *E) 4729 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 4730 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 4731 { return StmtVisitorTy::Visit(E->getResultExpr()); } 4732 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 4733 { return StmtVisitorTy::Visit(E->getReplacement()); } 4734 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 4735 TempVersionRAII RAII(*Info.CurrentCall); 4736 return StmtVisitorTy::Visit(E->getExpr()); 4737 } 4738 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 4739 TempVersionRAII RAII(*Info.CurrentCall); 4740 // The initializer may not have been parsed yet, or might be erroneous. 4741 if (!E->getExpr()) 4742 return Error(E); 4743 return StmtVisitorTy::Visit(E->getExpr()); 4744 } 4745 // We cannot create any objects for which cleanups are required, so there is 4746 // nothing to do here; all cleanups must come from unevaluated subexpressions. 4747 bool VisitExprWithCleanups(const ExprWithCleanups *E) 4748 { return StmtVisitorTy::Visit(E->getSubExpr()); } 4749 4750 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 4751 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 4752 return static_cast<Derived*>(this)->VisitCastExpr(E); 4753 } 4754 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 4755 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 4756 return static_cast<Derived*>(this)->VisitCastExpr(E); 4757 } 4758 4759 bool VisitBinaryOperator(const BinaryOperator *E) { 4760 switch (E->getOpcode()) { 4761 default: 4762 return Error(E); 4763 4764 case BO_Comma: 4765 VisitIgnoredValue(E->getLHS()); 4766 return StmtVisitorTy::Visit(E->getRHS()); 4767 4768 case BO_PtrMemD: 4769 case BO_PtrMemI: { 4770 LValue Obj; 4771 if (!HandleMemberPointerAccess(Info, E, Obj)) 4772 return false; 4773 APValue Result; 4774 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 4775 return false; 4776 return DerivedSuccess(Result, E); 4777 } 4778 } 4779 } 4780 4781 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 4782 // Evaluate and cache the common expression. We treat it as a temporary, 4783 // even though it's not quite the same thing. 4784 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 4785 Info, E->getCommon())) 4786 return false; 4787 4788 return HandleConditionalOperator(E); 4789 } 4790 4791 bool VisitConditionalOperator(const ConditionalOperator *E) { 4792 bool IsBcpCall = false; 4793 // If the condition (ignoring parens) is a __builtin_constant_p call, 4794 // the result is a constant expression if it can be folded without 4795 // side-effects. This is an important GNU extension. See GCC PR38377 4796 // for discussion. 4797 if (const CallExpr *CallCE = 4798 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 4799 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 4800 IsBcpCall = true; 4801 4802 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 4803 // constant expression; we can't check whether it's potentially foldable. 4804 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 4805 return false; 4806 4807 FoldConstant Fold(Info, IsBcpCall); 4808 if (!HandleConditionalOperator(E)) { 4809 Fold.keepDiagnostics(); 4810 return false; 4811 } 4812 4813 return true; 4814 } 4815 4816 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 4817 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 4818 return DerivedSuccess(*Value, E); 4819 4820 const Expr *Source = E->getSourceExpr(); 4821 if (!Source) 4822 return Error(E); 4823 if (Source == E) { // sanity checking. 4824 assert(0 && "OpaqueValueExpr recursively refers to itself"); 4825 return Error(E); 4826 } 4827 return StmtVisitorTy::Visit(Source); 4828 } 4829 4830 bool VisitCallExpr(const CallExpr *E) { 4831 APValue Result; 4832 if (!handleCallExpr(E, Result, nullptr)) 4833 return false; 4834 return DerivedSuccess(Result, E); 4835 } 4836 4837 bool handleCallExpr(const CallExpr *E, APValue &Result, 4838 const LValue *ResultSlot) { 4839 const Expr *Callee = E->getCallee()->IgnoreParens(); 4840 QualType CalleeType = Callee->getType(); 4841 4842 const FunctionDecl *FD = nullptr; 4843 LValue *This = nullptr, ThisVal; 4844 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 4845 bool HasQualifier = false; 4846 4847 // Extract function decl and 'this' pointer from the callee. 4848 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 4849 const ValueDecl *Member = nullptr; 4850 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 4851 // Explicit bound member calls, such as x.f() or p->g(); 4852 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 4853 return false; 4854 Member = ME->getMemberDecl(); 4855 This = &ThisVal; 4856 HasQualifier = ME->hasQualifier(); 4857 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 4858 // Indirect bound member calls ('.*' or '->*'). 4859 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false); 4860 if (!Member) return false; 4861 This = &ThisVal; 4862 } else 4863 return Error(Callee); 4864 4865 FD = dyn_cast<FunctionDecl>(Member); 4866 if (!FD) 4867 return Error(Callee); 4868 } else if (CalleeType->isFunctionPointerType()) { 4869 LValue Call; 4870 if (!EvaluatePointer(Callee, Call, Info)) 4871 return false; 4872 4873 if (!Call.getLValueOffset().isZero()) 4874 return Error(Callee); 4875 FD = dyn_cast_or_null<FunctionDecl>( 4876 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 4877 if (!FD) 4878 return Error(Callee); 4879 // Don't call function pointers which have been cast to some other type. 4880 // Per DR (no number yet), the caller and callee can differ in noexcept. 4881 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 4882 CalleeType->getPointeeType(), FD->getType())) { 4883 return Error(E); 4884 } 4885 4886 // Overloaded operator calls to member functions are represented as normal 4887 // calls with '*this' as the first argument. 4888 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 4889 if (MD && !MD->isStatic()) { 4890 // FIXME: When selecting an implicit conversion for an overloaded 4891 // operator delete, we sometimes try to evaluate calls to conversion 4892 // operators without a 'this' parameter! 4893 if (Args.empty()) 4894 return Error(E); 4895 4896 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 4897 return false; 4898 This = &ThisVal; 4899 Args = Args.slice(1); 4900 } else if (MD && MD->isLambdaStaticInvoker()) { 4901 // Map the static invoker for the lambda back to the call operator. 4902 // Conveniently, we don't have to slice out the 'this' argument (as is 4903 // being done for the non-static case), since a static member function 4904 // doesn't have an implicit argument passed in. 4905 const CXXRecordDecl *ClosureClass = MD->getParent(); 4906 assert( 4907 ClosureClass->captures_begin() == ClosureClass->captures_end() && 4908 "Number of captures must be zero for conversion to function-ptr"); 4909 4910 const CXXMethodDecl *LambdaCallOp = 4911 ClosureClass->getLambdaCallOperator(); 4912 4913 // Set 'FD', the function that will be called below, to the call 4914 // operator. If the closure object represents a generic lambda, find 4915 // the corresponding specialization of the call operator. 4916 4917 if (ClosureClass->isGenericLambda()) { 4918 assert(MD->isFunctionTemplateSpecialization() && 4919 "A generic lambda's static-invoker function must be a " 4920 "template specialization"); 4921 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 4922 FunctionTemplateDecl *CallOpTemplate = 4923 LambdaCallOp->getDescribedFunctionTemplate(); 4924 void *InsertPos = nullptr; 4925 FunctionDecl *CorrespondingCallOpSpecialization = 4926 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 4927 assert(CorrespondingCallOpSpecialization && 4928 "We must always have a function call operator specialization " 4929 "that corresponds to our static invoker specialization"); 4930 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 4931 } else 4932 FD = LambdaCallOp; 4933 } 4934 4935 4936 } else 4937 return Error(E); 4938 4939 if (This && !This->checkSubobject(Info, E, CSK_This)) 4940 return false; 4941 4942 // DR1358 allows virtual constexpr functions in some cases. Don't allow 4943 // calls to such functions in constant expressions. 4944 if (This && !HasQualifier && 4945 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual()) 4946 return Error(E, diag::note_constexpr_virtual_call); 4947 4948 const FunctionDecl *Definition = nullptr; 4949 Stmt *Body = FD->getBody(Definition); 4950 4951 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 4952 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 4953 Result, ResultSlot)) 4954 return false; 4955 4956 return true; 4957 } 4958 4959 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 4960 return StmtVisitorTy::Visit(E->getInitializer()); 4961 } 4962 bool VisitInitListExpr(const InitListExpr *E) { 4963 if (E->getNumInits() == 0) 4964 return DerivedZeroInitialization(E); 4965 if (E->getNumInits() == 1) 4966 return StmtVisitorTy::Visit(E->getInit(0)); 4967 return Error(E); 4968 } 4969 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 4970 return DerivedZeroInitialization(E); 4971 } 4972 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 4973 return DerivedZeroInitialization(E); 4974 } 4975 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 4976 return DerivedZeroInitialization(E); 4977 } 4978 4979 /// A member expression where the object is a prvalue is itself a prvalue. 4980 bool VisitMemberExpr(const MemberExpr *E) { 4981 assert(!E->isArrow() && "missing call to bound member function?"); 4982 4983 APValue Val; 4984 if (!Evaluate(Val, Info, E->getBase())) 4985 return false; 4986 4987 QualType BaseTy = E->getBase()->getType(); 4988 4989 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 4990 if (!FD) return Error(E); 4991 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 4992 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 4993 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 4994 4995 CompleteObject Obj(&Val, BaseTy, true); 4996 SubobjectDesignator Designator(BaseTy); 4997 Designator.addDeclUnchecked(FD); 4998 4999 APValue Result; 5000 return extractSubobject(Info, E, Obj, Designator, Result) && 5001 DerivedSuccess(Result, E); 5002 } 5003 5004 bool VisitCastExpr(const CastExpr *E) { 5005 switch (E->getCastKind()) { 5006 default: 5007 break; 5008 5009 case CK_AtomicToNonAtomic: { 5010 APValue AtomicVal; 5011 // This does not need to be done in place even for class/array types: 5012 // atomic-to-non-atomic conversion implies copying the object 5013 // representation. 5014 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 5015 return false; 5016 return DerivedSuccess(AtomicVal, E); 5017 } 5018 5019 case CK_NoOp: 5020 case CK_UserDefinedConversion: 5021 return StmtVisitorTy::Visit(E->getSubExpr()); 5022 5023 case CK_LValueToRValue: { 5024 LValue LVal; 5025 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 5026 return false; 5027 APValue RVal; 5028 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5029 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5030 LVal, RVal)) 5031 return false; 5032 return DerivedSuccess(RVal, E); 5033 } 5034 } 5035 5036 return Error(E); 5037 } 5038 5039 bool VisitUnaryPostInc(const UnaryOperator *UO) { 5040 return VisitUnaryPostIncDec(UO); 5041 } 5042 bool VisitUnaryPostDec(const UnaryOperator *UO) { 5043 return VisitUnaryPostIncDec(UO); 5044 } 5045 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 5046 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5047 return Error(UO); 5048 5049 LValue LVal; 5050 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 5051 return false; 5052 APValue RVal; 5053 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 5054 UO->isIncrementOp(), &RVal)) 5055 return false; 5056 return DerivedSuccess(RVal, UO); 5057 } 5058 5059 bool VisitStmtExpr(const StmtExpr *E) { 5060 // We will have checked the full-expressions inside the statement expression 5061 // when they were completed, and don't need to check them again now. 5062 if (Info.checkingForOverflow()) 5063 return Error(E); 5064 5065 BlockScopeRAII Scope(Info); 5066 const CompoundStmt *CS = E->getSubStmt(); 5067 if (CS->body_empty()) 5068 return true; 5069 5070 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 5071 BE = CS->body_end(); 5072 /**/; ++BI) { 5073 if (BI + 1 == BE) { 5074 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 5075 if (!FinalExpr) { 5076 Info.FFDiag((*BI)->getBeginLoc(), 5077 diag::note_constexpr_stmt_expr_unsupported); 5078 return false; 5079 } 5080 return this->Visit(FinalExpr); 5081 } 5082 5083 APValue ReturnValue; 5084 StmtResult Result = { ReturnValue, nullptr }; 5085 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 5086 if (ESR != ESR_Succeeded) { 5087 // FIXME: If the statement-expression terminated due to 'return', 5088 // 'break', or 'continue', it would be nice to propagate that to 5089 // the outer statement evaluation rather than bailing out. 5090 if (ESR != ESR_Failed) 5091 Info.FFDiag((*BI)->getBeginLoc(), 5092 diag::note_constexpr_stmt_expr_unsupported); 5093 return false; 5094 } 5095 } 5096 5097 llvm_unreachable("Return from function from the loop above."); 5098 } 5099 5100 /// Visit a value which is evaluated, but whose value is ignored. 5101 void VisitIgnoredValue(const Expr *E) { 5102 EvaluateIgnoredValue(Info, E); 5103 } 5104 5105 /// Potentially visit a MemberExpr's base expression. 5106 void VisitIgnoredBaseExpression(const Expr *E) { 5107 // While MSVC doesn't evaluate the base expression, it does diagnose the 5108 // presence of side-effecting behavior. 5109 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 5110 return; 5111 VisitIgnoredValue(E); 5112 } 5113 }; 5114 5115 } // namespace 5116 5117 //===----------------------------------------------------------------------===// 5118 // Common base class for lvalue and temporary evaluation. 5119 //===----------------------------------------------------------------------===// 5120 namespace { 5121 template<class Derived> 5122 class LValueExprEvaluatorBase 5123 : public ExprEvaluatorBase<Derived> { 5124 protected: 5125 LValue &Result; 5126 bool InvalidBaseOK; 5127 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 5128 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 5129 5130 bool Success(APValue::LValueBase B) { 5131 Result.set(B); 5132 return true; 5133 } 5134 5135 bool evaluatePointer(const Expr *E, LValue &Result) { 5136 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 5137 } 5138 5139 public: 5140 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 5141 : ExprEvaluatorBaseTy(Info), Result(Result), 5142 InvalidBaseOK(InvalidBaseOK) {} 5143 5144 bool Success(const APValue &V, const Expr *E) { 5145 Result.setFrom(this->Info.Ctx, V); 5146 return true; 5147 } 5148 5149 bool VisitMemberExpr(const MemberExpr *E) { 5150 // Handle non-static data members. 5151 QualType BaseTy; 5152 bool EvalOK; 5153 if (E->isArrow()) { 5154 EvalOK = evaluatePointer(E->getBase(), Result); 5155 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 5156 } else if (E->getBase()->isRValue()) { 5157 assert(E->getBase()->getType()->isRecordType()); 5158 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 5159 BaseTy = E->getBase()->getType(); 5160 } else { 5161 EvalOK = this->Visit(E->getBase()); 5162 BaseTy = E->getBase()->getType(); 5163 } 5164 if (!EvalOK) { 5165 if (!InvalidBaseOK) 5166 return false; 5167 Result.setInvalid(E); 5168 return true; 5169 } 5170 5171 const ValueDecl *MD = E->getMemberDecl(); 5172 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 5173 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 5174 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 5175 (void)BaseTy; 5176 if (!HandleLValueMember(this->Info, E, Result, FD)) 5177 return false; 5178 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 5179 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 5180 return false; 5181 } else 5182 return this->Error(E); 5183 5184 if (MD->getType()->isReferenceType()) { 5185 APValue RefValue; 5186 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 5187 RefValue)) 5188 return false; 5189 return Success(RefValue, E); 5190 } 5191 return true; 5192 } 5193 5194 bool VisitBinaryOperator(const BinaryOperator *E) { 5195 switch (E->getOpcode()) { 5196 default: 5197 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5198 5199 case BO_PtrMemD: 5200 case BO_PtrMemI: 5201 return HandleMemberPointerAccess(this->Info, E, Result); 5202 } 5203 } 5204 5205 bool VisitCastExpr(const CastExpr *E) { 5206 switch (E->getCastKind()) { 5207 default: 5208 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5209 5210 case CK_DerivedToBase: 5211 case CK_UncheckedDerivedToBase: 5212 if (!this->Visit(E->getSubExpr())) 5213 return false; 5214 5215 // Now figure out the necessary offset to add to the base LV to get from 5216 // the derived class to the base class. 5217 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 5218 Result); 5219 } 5220 } 5221 }; 5222 } 5223 5224 //===----------------------------------------------------------------------===// 5225 // LValue Evaluation 5226 // 5227 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 5228 // function designators (in C), decl references to void objects (in C), and 5229 // temporaries (if building with -Wno-address-of-temporary). 5230 // 5231 // LValue evaluation produces values comprising a base expression of one of the 5232 // following types: 5233 // - Declarations 5234 // * VarDecl 5235 // * FunctionDecl 5236 // - Literals 5237 // * CompoundLiteralExpr in C (and in global scope in C++) 5238 // * StringLiteral 5239 // * CXXTypeidExpr 5240 // * PredefinedExpr 5241 // * ObjCStringLiteralExpr 5242 // * ObjCEncodeExpr 5243 // * AddrLabelExpr 5244 // * BlockExpr 5245 // * CallExpr for a MakeStringConstant builtin 5246 // - Locals and temporaries 5247 // * MaterializeTemporaryExpr 5248 // * Any Expr, with a CallIndex indicating the function in which the temporary 5249 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 5250 // from the AST (FIXME). 5251 // * A MaterializeTemporaryExpr that has static storage duration, with no 5252 // CallIndex, for a lifetime-extended temporary. 5253 // plus an offset in bytes. 5254 //===----------------------------------------------------------------------===// 5255 namespace { 5256 class LValueExprEvaluator 5257 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 5258 public: 5259 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 5260 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 5261 5262 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 5263 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 5264 5265 bool VisitDeclRefExpr(const DeclRefExpr *E); 5266 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 5267 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 5268 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 5269 bool VisitMemberExpr(const MemberExpr *E); 5270 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 5271 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 5272 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 5273 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 5274 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 5275 bool VisitUnaryDeref(const UnaryOperator *E); 5276 bool VisitUnaryReal(const UnaryOperator *E); 5277 bool VisitUnaryImag(const UnaryOperator *E); 5278 bool VisitUnaryPreInc(const UnaryOperator *UO) { 5279 return VisitUnaryPreIncDec(UO); 5280 } 5281 bool VisitUnaryPreDec(const UnaryOperator *UO) { 5282 return VisitUnaryPreIncDec(UO); 5283 } 5284 bool VisitBinAssign(const BinaryOperator *BO); 5285 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 5286 5287 bool VisitCastExpr(const CastExpr *E) { 5288 switch (E->getCastKind()) { 5289 default: 5290 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 5291 5292 case CK_LValueBitCast: 5293 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5294 if (!Visit(E->getSubExpr())) 5295 return false; 5296 Result.Designator.setInvalid(); 5297 return true; 5298 5299 case CK_BaseToDerived: 5300 if (!Visit(E->getSubExpr())) 5301 return false; 5302 return HandleBaseToDerivedCast(Info, E, Result); 5303 } 5304 } 5305 }; 5306 } // end anonymous namespace 5307 5308 /// Evaluate an expression as an lvalue. This can be legitimately called on 5309 /// expressions which are not glvalues, in three cases: 5310 /// * function designators in C, and 5311 /// * "extern void" objects 5312 /// * @selector() expressions in Objective-C 5313 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 5314 bool InvalidBaseOK) { 5315 assert(E->isGLValue() || E->getType()->isFunctionType() || 5316 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 5317 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5318 } 5319 5320 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 5321 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 5322 return Success(FD); 5323 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 5324 return VisitVarDecl(E, VD); 5325 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 5326 return Visit(BD->getBinding()); 5327 return Error(E); 5328 } 5329 5330 5331 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 5332 5333 // If we are within a lambda's call operator, check whether the 'VD' referred 5334 // to within 'E' actually represents a lambda-capture that maps to a 5335 // data-member/field within the closure object, and if so, evaluate to the 5336 // field or what the field refers to. 5337 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 5338 isa<DeclRefExpr>(E) && 5339 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 5340 // We don't always have a complete capture-map when checking or inferring if 5341 // the function call operator meets the requirements of a constexpr function 5342 // - but we don't need to evaluate the captures to determine constexprness 5343 // (dcl.constexpr C++17). 5344 if (Info.checkingPotentialConstantExpression()) 5345 return false; 5346 5347 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 5348 // Start with 'Result' referring to the complete closure object... 5349 Result = *Info.CurrentCall->This; 5350 // ... then update it to refer to the field of the closure object 5351 // that represents the capture. 5352 if (!HandleLValueMember(Info, E, Result, FD)) 5353 return false; 5354 // And if the field is of reference type, update 'Result' to refer to what 5355 // the field refers to. 5356 if (FD->getType()->isReferenceType()) { 5357 APValue RVal; 5358 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 5359 RVal)) 5360 return false; 5361 Result.setFrom(Info.Ctx, RVal); 5362 } 5363 return true; 5364 } 5365 } 5366 CallStackFrame *Frame = nullptr; 5367 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 5368 // Only if a local variable was declared in the function currently being 5369 // evaluated, do we expect to be able to find its value in the current 5370 // frame. (Otherwise it was likely declared in an enclosing context and 5371 // could either have a valid evaluatable value (for e.g. a constexpr 5372 // variable) or be ill-formed (and trigger an appropriate evaluation 5373 // diagnostic)). 5374 if (Info.CurrentCall->Callee && 5375 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 5376 Frame = Info.CurrentCall; 5377 } 5378 } 5379 5380 if (!VD->getType()->isReferenceType()) { 5381 if (Frame) { 5382 Result.set({VD, Frame->Index, 5383 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 5384 return true; 5385 } 5386 return Success(VD); 5387 } 5388 5389 APValue *V; 5390 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 5391 return false; 5392 if (V->isUninit()) { 5393 if (!Info.checkingPotentialConstantExpression()) 5394 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 5395 return false; 5396 } 5397 return Success(*V, E); 5398 } 5399 5400 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 5401 const MaterializeTemporaryExpr *E) { 5402 // Walk through the expression to find the materialized temporary itself. 5403 SmallVector<const Expr *, 2> CommaLHSs; 5404 SmallVector<SubobjectAdjustment, 2> Adjustments; 5405 const Expr *Inner = E->GetTemporaryExpr()-> 5406 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 5407 5408 // If we passed any comma operators, evaluate their LHSs. 5409 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 5410 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 5411 return false; 5412 5413 // A materialized temporary with static storage duration can appear within the 5414 // result of a constant expression evaluation, so we need to preserve its 5415 // value for use outside this evaluation. 5416 APValue *Value; 5417 if (E->getStorageDuration() == SD_Static) { 5418 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 5419 *Value = APValue(); 5420 Result.set(E); 5421 } else { 5422 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result, 5423 *Info.CurrentCall); 5424 } 5425 5426 QualType Type = Inner->getType(); 5427 5428 // Materialize the temporary itself. 5429 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 5430 (E->getStorageDuration() == SD_Static && 5431 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 5432 *Value = APValue(); 5433 return false; 5434 } 5435 5436 // Adjust our lvalue to refer to the desired subobject. 5437 for (unsigned I = Adjustments.size(); I != 0; /**/) { 5438 --I; 5439 switch (Adjustments[I].Kind) { 5440 case SubobjectAdjustment::DerivedToBaseAdjustment: 5441 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 5442 Type, Result)) 5443 return false; 5444 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 5445 break; 5446 5447 case SubobjectAdjustment::FieldAdjustment: 5448 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 5449 return false; 5450 Type = Adjustments[I].Field->getType(); 5451 break; 5452 5453 case SubobjectAdjustment::MemberPointerAdjustment: 5454 if (!HandleMemberPointerAccess(this->Info, Type, Result, 5455 Adjustments[I].Ptr.RHS)) 5456 return false; 5457 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 5458 break; 5459 } 5460 } 5461 5462 return true; 5463 } 5464 5465 bool 5466 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 5467 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 5468 "lvalue compound literal in c++?"); 5469 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 5470 // only see this when folding in C, so there's no standard to follow here. 5471 return Success(E); 5472 } 5473 5474 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 5475 if (!E->isPotentiallyEvaluated()) 5476 return Success(E); 5477 5478 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic) 5479 << E->getExprOperand()->getType() 5480 << E->getExprOperand()->getSourceRange(); 5481 return false; 5482 } 5483 5484 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 5485 return Success(E); 5486 } 5487 5488 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 5489 // Handle static data members. 5490 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 5491 VisitIgnoredBaseExpression(E->getBase()); 5492 return VisitVarDecl(E, VD); 5493 } 5494 5495 // Handle static member functions. 5496 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 5497 if (MD->isStatic()) { 5498 VisitIgnoredBaseExpression(E->getBase()); 5499 return Success(MD); 5500 } 5501 } 5502 5503 // Handle non-static data members. 5504 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 5505 } 5506 5507 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 5508 // FIXME: Deal with vectors as array subscript bases. 5509 if (E->getBase()->getType()->isVectorType()) 5510 return Error(E); 5511 5512 bool Success = true; 5513 if (!evaluatePointer(E->getBase(), Result)) { 5514 if (!Info.noteFailure()) 5515 return false; 5516 Success = false; 5517 } 5518 5519 APSInt Index; 5520 if (!EvaluateInteger(E->getIdx(), Index, Info)) 5521 return false; 5522 5523 return Success && 5524 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 5525 } 5526 5527 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 5528 return evaluatePointer(E->getSubExpr(), Result); 5529 } 5530 5531 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 5532 if (!Visit(E->getSubExpr())) 5533 return false; 5534 // __real is a no-op on scalar lvalues. 5535 if (E->getSubExpr()->getType()->isAnyComplexType()) 5536 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 5537 return true; 5538 } 5539 5540 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 5541 assert(E->getSubExpr()->getType()->isAnyComplexType() && 5542 "lvalue __imag__ on scalar?"); 5543 if (!Visit(E->getSubExpr())) 5544 return false; 5545 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 5546 return true; 5547 } 5548 5549 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 5550 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5551 return Error(UO); 5552 5553 if (!this->Visit(UO->getSubExpr())) 5554 return false; 5555 5556 return handleIncDec( 5557 this->Info, UO, Result, UO->getSubExpr()->getType(), 5558 UO->isIncrementOp(), nullptr); 5559 } 5560 5561 bool LValueExprEvaluator::VisitCompoundAssignOperator( 5562 const CompoundAssignOperator *CAO) { 5563 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5564 return Error(CAO); 5565 5566 APValue RHS; 5567 5568 // The overall lvalue result is the result of evaluating the LHS. 5569 if (!this->Visit(CAO->getLHS())) { 5570 if (Info.noteFailure()) 5571 Evaluate(RHS, this->Info, CAO->getRHS()); 5572 return false; 5573 } 5574 5575 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 5576 return false; 5577 5578 return handleCompoundAssignment( 5579 this->Info, CAO, 5580 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 5581 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 5582 } 5583 5584 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 5585 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5586 return Error(E); 5587 5588 APValue NewVal; 5589 5590 if (!this->Visit(E->getLHS())) { 5591 if (Info.noteFailure()) 5592 Evaluate(NewVal, this->Info, E->getRHS()); 5593 return false; 5594 } 5595 5596 if (!Evaluate(NewVal, this->Info, E->getRHS())) 5597 return false; 5598 5599 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 5600 NewVal); 5601 } 5602 5603 //===----------------------------------------------------------------------===// 5604 // Pointer Evaluation 5605 //===----------------------------------------------------------------------===// 5606 5607 /// Attempts to compute the number of bytes available at the pointer 5608 /// returned by a function with the alloc_size attribute. Returns true if we 5609 /// were successful. Places an unsigned number into `Result`. 5610 /// 5611 /// This expects the given CallExpr to be a call to a function with an 5612 /// alloc_size attribute. 5613 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5614 const CallExpr *Call, 5615 llvm::APInt &Result) { 5616 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 5617 5618 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 5619 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 5620 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 5621 if (Call->getNumArgs() <= SizeArgNo) 5622 return false; 5623 5624 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 5625 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects)) 5626 return false; 5627 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 5628 return false; 5629 Into = Into.zextOrSelf(BitsInSizeT); 5630 return true; 5631 }; 5632 5633 APSInt SizeOfElem; 5634 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 5635 return false; 5636 5637 if (!AllocSize->getNumElemsParam().isValid()) { 5638 Result = std::move(SizeOfElem); 5639 return true; 5640 } 5641 5642 APSInt NumberOfElems; 5643 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 5644 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 5645 return false; 5646 5647 bool Overflow; 5648 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 5649 if (Overflow) 5650 return false; 5651 5652 Result = std::move(BytesAvailable); 5653 return true; 5654 } 5655 5656 /// Convenience function. LVal's base must be a call to an alloc_size 5657 /// function. 5658 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 5659 const LValue &LVal, 5660 llvm::APInt &Result) { 5661 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 5662 "Can't get the size of a non alloc_size function"); 5663 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 5664 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 5665 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 5666 } 5667 5668 /// Attempts to evaluate the given LValueBase as the result of a call to 5669 /// a function with the alloc_size attribute. If it was possible to do so, this 5670 /// function will return true, make Result's Base point to said function call, 5671 /// and mark Result's Base as invalid. 5672 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 5673 LValue &Result) { 5674 if (Base.isNull()) 5675 return false; 5676 5677 // Because we do no form of static analysis, we only support const variables. 5678 // 5679 // Additionally, we can't support parameters, nor can we support static 5680 // variables (in the latter case, use-before-assign isn't UB; in the former, 5681 // we have no clue what they'll be assigned to). 5682 const auto *VD = 5683 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 5684 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 5685 return false; 5686 5687 const Expr *Init = VD->getAnyInitializer(); 5688 if (!Init) 5689 return false; 5690 5691 const Expr *E = Init->IgnoreParens(); 5692 if (!tryUnwrapAllocSizeCall(E)) 5693 return false; 5694 5695 // Store E instead of E unwrapped so that the type of the LValue's base is 5696 // what the user wanted. 5697 Result.setInvalid(E); 5698 5699 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 5700 Result.addUnsizedArray(Info, E, Pointee); 5701 return true; 5702 } 5703 5704 namespace { 5705 class PointerExprEvaluator 5706 : public ExprEvaluatorBase<PointerExprEvaluator> { 5707 LValue &Result; 5708 bool InvalidBaseOK; 5709 5710 bool Success(const Expr *E) { 5711 Result.set(E); 5712 return true; 5713 } 5714 5715 bool evaluateLValue(const Expr *E, LValue &Result) { 5716 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 5717 } 5718 5719 bool evaluatePointer(const Expr *E, LValue &Result) { 5720 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 5721 } 5722 5723 bool visitNonBuiltinCallExpr(const CallExpr *E); 5724 public: 5725 5726 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 5727 : ExprEvaluatorBaseTy(info), Result(Result), 5728 InvalidBaseOK(InvalidBaseOK) {} 5729 5730 bool Success(const APValue &V, const Expr *E) { 5731 Result.setFrom(Info.Ctx, V); 5732 return true; 5733 } 5734 bool ZeroInitialization(const Expr *E) { 5735 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 5736 Result.setNull(E->getType(), TargetVal); 5737 return true; 5738 } 5739 5740 bool VisitBinaryOperator(const BinaryOperator *E); 5741 bool VisitCastExpr(const CastExpr* E); 5742 bool VisitUnaryAddrOf(const UnaryOperator *E); 5743 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 5744 { return Success(E); } 5745 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 5746 if (Info.noteFailure()) 5747 EvaluateIgnoredValue(Info, E->getSubExpr()); 5748 return Error(E); 5749 } 5750 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 5751 { return Success(E); } 5752 bool VisitCallExpr(const CallExpr *E); 5753 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 5754 bool VisitBlockExpr(const BlockExpr *E) { 5755 if (!E->getBlockDecl()->hasCaptures()) 5756 return Success(E); 5757 return Error(E); 5758 } 5759 bool VisitCXXThisExpr(const CXXThisExpr *E) { 5760 // Can't look at 'this' when checking a potential constant expression. 5761 if (Info.checkingPotentialConstantExpression()) 5762 return false; 5763 if (!Info.CurrentCall->This) { 5764 if (Info.getLangOpts().CPlusPlus11) 5765 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 5766 else 5767 Info.FFDiag(E); 5768 return false; 5769 } 5770 Result = *Info.CurrentCall->This; 5771 // If we are inside a lambda's call operator, the 'this' expression refers 5772 // to the enclosing '*this' object (either by value or reference) which is 5773 // either copied into the closure object's field that represents the '*this' 5774 // or refers to '*this'. 5775 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 5776 // Update 'Result' to refer to the data member/field of the closure object 5777 // that represents the '*this' capture. 5778 if (!HandleLValueMember(Info, E, Result, 5779 Info.CurrentCall->LambdaThisCaptureField)) 5780 return false; 5781 // If we captured '*this' by reference, replace the field with its referent. 5782 if (Info.CurrentCall->LambdaThisCaptureField->getType() 5783 ->isPointerType()) { 5784 APValue RVal; 5785 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 5786 RVal)) 5787 return false; 5788 5789 Result.setFrom(Info.Ctx, RVal); 5790 } 5791 } 5792 return true; 5793 } 5794 5795 // FIXME: Missing: @protocol, @selector 5796 }; 5797 } // end anonymous namespace 5798 5799 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 5800 bool InvalidBaseOK) { 5801 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 5802 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 5803 } 5804 5805 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 5806 if (E->getOpcode() != BO_Add && 5807 E->getOpcode() != BO_Sub) 5808 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5809 5810 const Expr *PExp = E->getLHS(); 5811 const Expr *IExp = E->getRHS(); 5812 if (IExp->getType()->isPointerType()) 5813 std::swap(PExp, IExp); 5814 5815 bool EvalPtrOK = evaluatePointer(PExp, Result); 5816 if (!EvalPtrOK && !Info.noteFailure()) 5817 return false; 5818 5819 llvm::APSInt Offset; 5820 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 5821 return false; 5822 5823 if (E->getOpcode() == BO_Sub) 5824 negateAsSigned(Offset); 5825 5826 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 5827 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 5828 } 5829 5830 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 5831 return evaluateLValue(E->getSubExpr(), Result); 5832 } 5833 5834 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 5835 const Expr *SubExpr = E->getSubExpr(); 5836 5837 switch (E->getCastKind()) { 5838 default: 5839 break; 5840 5841 case CK_BitCast: 5842 case CK_CPointerToObjCPointerCast: 5843 case CK_BlockPointerToObjCPointerCast: 5844 case CK_AnyPointerToBlockPointerCast: 5845 case CK_AddressSpaceConversion: 5846 if (!Visit(SubExpr)) 5847 return false; 5848 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 5849 // permitted in constant expressions in C++11. Bitcasts from cv void* are 5850 // also static_casts, but we disallow them as a resolution to DR1312. 5851 if (!E->getType()->isVoidPointerType()) { 5852 Result.Designator.setInvalid(); 5853 if (SubExpr->getType()->isVoidPointerType()) 5854 CCEDiag(E, diag::note_constexpr_invalid_cast) 5855 << 3 << SubExpr->getType(); 5856 else 5857 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5858 } 5859 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 5860 ZeroInitialization(E); 5861 return true; 5862 5863 case CK_DerivedToBase: 5864 case CK_UncheckedDerivedToBase: 5865 if (!evaluatePointer(E->getSubExpr(), Result)) 5866 return false; 5867 if (!Result.Base && Result.Offset.isZero()) 5868 return true; 5869 5870 // Now figure out the necessary offset to add to the base LV to get from 5871 // the derived class to the base class. 5872 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 5873 castAs<PointerType>()->getPointeeType(), 5874 Result); 5875 5876 case CK_BaseToDerived: 5877 if (!Visit(E->getSubExpr())) 5878 return false; 5879 if (!Result.Base && Result.Offset.isZero()) 5880 return true; 5881 return HandleBaseToDerivedCast(Info, E, Result); 5882 5883 case CK_NullToPointer: 5884 VisitIgnoredValue(E->getSubExpr()); 5885 return ZeroInitialization(E); 5886 5887 case CK_IntegralToPointer: { 5888 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 5889 5890 APValue Value; 5891 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 5892 break; 5893 5894 if (Value.isInt()) { 5895 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 5896 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 5897 Result.Base = (Expr*)nullptr; 5898 Result.InvalidBase = false; 5899 Result.Offset = CharUnits::fromQuantity(N); 5900 Result.Designator.setInvalid(); 5901 Result.IsNullPtr = false; 5902 return true; 5903 } else { 5904 // Cast is of an lvalue, no need to change value. 5905 Result.setFrom(Info.Ctx, Value); 5906 return true; 5907 } 5908 } 5909 5910 case CK_ArrayToPointerDecay: { 5911 if (SubExpr->isGLValue()) { 5912 if (!evaluateLValue(SubExpr, Result)) 5913 return false; 5914 } else { 5915 APValue &Value = createTemporary(SubExpr, false, Result, 5916 *Info.CurrentCall); 5917 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 5918 return false; 5919 } 5920 // The result is a pointer to the first element of the array. 5921 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 5922 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 5923 Result.addArray(Info, E, CAT); 5924 else 5925 Result.addUnsizedArray(Info, E, AT->getElementType()); 5926 return true; 5927 } 5928 5929 case CK_FunctionToPointerDecay: 5930 return evaluateLValue(SubExpr, Result); 5931 5932 case CK_LValueToRValue: { 5933 LValue LVal; 5934 if (!evaluateLValue(E->getSubExpr(), LVal)) 5935 return false; 5936 5937 APValue RVal; 5938 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5939 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5940 LVal, RVal)) 5941 return InvalidBaseOK && 5942 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 5943 return Success(RVal, E); 5944 } 5945 } 5946 5947 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5948 } 5949 5950 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 5951 UnaryExprOrTypeTrait ExprKind) { 5952 // C++ [expr.alignof]p3: 5953 // When alignof is applied to a reference type, the result is the 5954 // alignment of the referenced type. 5955 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 5956 T = Ref->getPointeeType(); 5957 5958 if (T.getQualifiers().hasUnaligned()) 5959 return CharUnits::One(); 5960 5961 const bool AlignOfReturnsPreferred = 5962 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 5963 5964 // __alignof is defined to return the preferred alignment. 5965 // Before 8, clang returned the preferred alignment for alignof and _Alignof 5966 // as well. 5967 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 5968 return Info.Ctx.toCharUnitsFromBits( 5969 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 5970 // alignof and _Alignof are defined to return the ABI alignment. 5971 else if (ExprKind == UETT_AlignOf) 5972 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 5973 else 5974 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 5975 } 5976 5977 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 5978 UnaryExprOrTypeTrait ExprKind) { 5979 E = E->IgnoreParens(); 5980 5981 // The kinds of expressions that we have special-case logic here for 5982 // should be kept up to date with the special checks for those 5983 // expressions in Sema. 5984 5985 // alignof decl is always accepted, even if it doesn't make sense: we default 5986 // to 1 in those cases. 5987 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 5988 return Info.Ctx.getDeclAlign(DRE->getDecl(), 5989 /*RefAsPointee*/true); 5990 5991 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 5992 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 5993 /*RefAsPointee*/true); 5994 5995 return GetAlignOfType(Info, E->getType(), ExprKind); 5996 } 5997 5998 // To be clear: this happily visits unsupported builtins. Better name welcomed. 5999 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 6000 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 6001 return true; 6002 6003 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 6004 return false; 6005 6006 Result.setInvalid(E); 6007 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 6008 Result.addUnsizedArray(Info, E, PointeeTy); 6009 return true; 6010 } 6011 6012 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 6013 if (IsStringLiteralCall(E)) 6014 return Success(E); 6015 6016 if (unsigned BuiltinOp = E->getBuiltinCallee()) 6017 return VisitBuiltinCallExpr(E, BuiltinOp); 6018 6019 return visitNonBuiltinCallExpr(E); 6020 } 6021 6022 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 6023 unsigned BuiltinOp) { 6024 switch (BuiltinOp) { 6025 case Builtin::BI__builtin_addressof: 6026 return evaluateLValue(E->getArg(0), Result); 6027 case Builtin::BI__builtin_assume_aligned: { 6028 // We need to be very careful here because: if the pointer does not have the 6029 // asserted alignment, then the behavior is undefined, and undefined 6030 // behavior is non-constant. 6031 if (!evaluatePointer(E->getArg(0), Result)) 6032 return false; 6033 6034 LValue OffsetResult(Result); 6035 APSInt Alignment; 6036 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 6037 return false; 6038 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 6039 6040 if (E->getNumArgs() > 2) { 6041 APSInt Offset; 6042 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 6043 return false; 6044 6045 int64_t AdditionalOffset = -Offset.getZExtValue(); 6046 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 6047 } 6048 6049 // If there is a base object, then it must have the correct alignment. 6050 if (OffsetResult.Base) { 6051 CharUnits BaseAlignment; 6052 if (const ValueDecl *VD = 6053 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 6054 BaseAlignment = Info.Ctx.getDeclAlign(VD); 6055 } else { 6056 BaseAlignment = GetAlignOfExpr( 6057 Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf); 6058 } 6059 6060 if (BaseAlignment < Align) { 6061 Result.Designator.setInvalid(); 6062 // FIXME: Add support to Diagnostic for long / long long. 6063 CCEDiag(E->getArg(0), 6064 diag::note_constexpr_baa_insufficient_alignment) << 0 6065 << (unsigned)BaseAlignment.getQuantity() 6066 << (unsigned)Align.getQuantity(); 6067 return false; 6068 } 6069 } 6070 6071 // The offset must also have the correct alignment. 6072 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 6073 Result.Designator.setInvalid(); 6074 6075 (OffsetResult.Base 6076 ? CCEDiag(E->getArg(0), 6077 diag::note_constexpr_baa_insufficient_alignment) << 1 6078 : CCEDiag(E->getArg(0), 6079 diag::note_constexpr_baa_value_insufficient_alignment)) 6080 << (int)OffsetResult.Offset.getQuantity() 6081 << (unsigned)Align.getQuantity(); 6082 return false; 6083 } 6084 6085 return true; 6086 } 6087 6088 case Builtin::BIstrchr: 6089 case Builtin::BIwcschr: 6090 case Builtin::BImemchr: 6091 case Builtin::BIwmemchr: 6092 if (Info.getLangOpts().CPlusPlus11) 6093 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6094 << /*isConstexpr*/0 << /*isConstructor*/0 6095 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 6096 else 6097 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6098 LLVM_FALLTHROUGH; 6099 case Builtin::BI__builtin_strchr: 6100 case Builtin::BI__builtin_wcschr: 6101 case Builtin::BI__builtin_memchr: 6102 case Builtin::BI__builtin_char_memchr: 6103 case Builtin::BI__builtin_wmemchr: { 6104 if (!Visit(E->getArg(0))) 6105 return false; 6106 APSInt Desired; 6107 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 6108 return false; 6109 uint64_t MaxLength = uint64_t(-1); 6110 if (BuiltinOp != Builtin::BIstrchr && 6111 BuiltinOp != Builtin::BIwcschr && 6112 BuiltinOp != Builtin::BI__builtin_strchr && 6113 BuiltinOp != Builtin::BI__builtin_wcschr) { 6114 APSInt N; 6115 if (!EvaluateInteger(E->getArg(2), N, Info)) 6116 return false; 6117 MaxLength = N.getExtValue(); 6118 } 6119 6120 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 6121 6122 // Figure out what value we're actually looking for (after converting to 6123 // the corresponding unsigned type if necessary). 6124 uint64_t DesiredVal; 6125 bool StopAtNull = false; 6126 switch (BuiltinOp) { 6127 case Builtin::BIstrchr: 6128 case Builtin::BI__builtin_strchr: 6129 // strchr compares directly to the passed integer, and therefore 6130 // always fails if given an int that is not a char. 6131 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 6132 E->getArg(1)->getType(), 6133 Desired), 6134 Desired)) 6135 return ZeroInitialization(E); 6136 StopAtNull = true; 6137 LLVM_FALLTHROUGH; 6138 case Builtin::BImemchr: 6139 case Builtin::BI__builtin_memchr: 6140 case Builtin::BI__builtin_char_memchr: 6141 // memchr compares by converting both sides to unsigned char. That's also 6142 // correct for strchr if we get this far (to cope with plain char being 6143 // unsigned in the strchr case). 6144 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 6145 break; 6146 6147 case Builtin::BIwcschr: 6148 case Builtin::BI__builtin_wcschr: 6149 StopAtNull = true; 6150 LLVM_FALLTHROUGH; 6151 case Builtin::BIwmemchr: 6152 case Builtin::BI__builtin_wmemchr: 6153 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 6154 DesiredVal = Desired.getZExtValue(); 6155 break; 6156 } 6157 6158 for (; MaxLength; --MaxLength) { 6159 APValue Char; 6160 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 6161 !Char.isInt()) 6162 return false; 6163 if (Char.getInt().getZExtValue() == DesiredVal) 6164 return true; 6165 if (StopAtNull && !Char.getInt()) 6166 break; 6167 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 6168 return false; 6169 } 6170 // Not found: return nullptr. 6171 return ZeroInitialization(E); 6172 } 6173 6174 case Builtin::BImemcpy: 6175 case Builtin::BImemmove: 6176 case Builtin::BIwmemcpy: 6177 case Builtin::BIwmemmove: 6178 if (Info.getLangOpts().CPlusPlus11) 6179 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6180 << /*isConstexpr*/0 << /*isConstructor*/0 6181 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 6182 else 6183 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6184 LLVM_FALLTHROUGH; 6185 case Builtin::BI__builtin_memcpy: 6186 case Builtin::BI__builtin_memmove: 6187 case Builtin::BI__builtin_wmemcpy: 6188 case Builtin::BI__builtin_wmemmove: { 6189 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 6190 BuiltinOp == Builtin::BIwmemmove || 6191 BuiltinOp == Builtin::BI__builtin_wmemcpy || 6192 BuiltinOp == Builtin::BI__builtin_wmemmove; 6193 bool Move = BuiltinOp == Builtin::BImemmove || 6194 BuiltinOp == Builtin::BIwmemmove || 6195 BuiltinOp == Builtin::BI__builtin_memmove || 6196 BuiltinOp == Builtin::BI__builtin_wmemmove; 6197 6198 // The result of mem* is the first argument. 6199 if (!Visit(E->getArg(0))) 6200 return false; 6201 LValue Dest = Result; 6202 6203 LValue Src; 6204 if (!EvaluatePointer(E->getArg(1), Src, Info)) 6205 return false; 6206 6207 APSInt N; 6208 if (!EvaluateInteger(E->getArg(2), N, Info)) 6209 return false; 6210 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 6211 6212 // If the size is zero, we treat this as always being a valid no-op. 6213 // (Even if one of the src and dest pointers is null.) 6214 if (!N) 6215 return true; 6216 6217 // Otherwise, if either of the operands is null, we can't proceed. Don't 6218 // try to determine the type of the copied objects, because there aren't 6219 // any. 6220 if (!Src.Base || !Dest.Base) { 6221 APValue Val; 6222 (!Src.Base ? Src : Dest).moveInto(Val); 6223 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 6224 << Move << WChar << !!Src.Base 6225 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 6226 return false; 6227 } 6228 if (Src.Designator.Invalid || Dest.Designator.Invalid) 6229 return false; 6230 6231 // We require that Src and Dest are both pointers to arrays of 6232 // trivially-copyable type. (For the wide version, the designator will be 6233 // invalid if the designated object is not a wchar_t.) 6234 QualType T = Dest.Designator.getType(Info.Ctx); 6235 QualType SrcT = Src.Designator.getType(Info.Ctx); 6236 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 6237 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 6238 return false; 6239 } 6240 if (T->isIncompleteType()) { 6241 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 6242 return false; 6243 } 6244 if (!T.isTriviallyCopyableType(Info.Ctx)) { 6245 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 6246 return false; 6247 } 6248 6249 // Figure out how many T's we're copying. 6250 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 6251 if (!WChar) { 6252 uint64_t Remainder; 6253 llvm::APInt OrigN = N; 6254 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 6255 if (Remainder) { 6256 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 6257 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 6258 << (unsigned)TSize; 6259 return false; 6260 } 6261 } 6262 6263 // Check that the copying will remain within the arrays, just so that we 6264 // can give a more meaningful diagnostic. This implicitly also checks that 6265 // N fits into 64 bits. 6266 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 6267 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 6268 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 6269 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 6270 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 6271 << N.toString(10, /*Signed*/false); 6272 return false; 6273 } 6274 uint64_t NElems = N.getZExtValue(); 6275 uint64_t NBytes = NElems * TSize; 6276 6277 // Check for overlap. 6278 int Direction = 1; 6279 if (HasSameBase(Src, Dest)) { 6280 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 6281 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 6282 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 6283 // Dest is inside the source region. 6284 if (!Move) { 6285 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 6286 return false; 6287 } 6288 // For memmove and friends, copy backwards. 6289 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 6290 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 6291 return false; 6292 Direction = -1; 6293 } else if (!Move && SrcOffset >= DestOffset && 6294 SrcOffset - DestOffset < NBytes) { 6295 // Src is inside the destination region for memcpy: invalid. 6296 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 6297 return false; 6298 } 6299 } 6300 6301 while (true) { 6302 APValue Val; 6303 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 6304 !handleAssignment(Info, E, Dest, T, Val)) 6305 return false; 6306 // Do not iterate past the last element; if we're copying backwards, that 6307 // might take us off the start of the array. 6308 if (--NElems == 0) 6309 return true; 6310 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 6311 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 6312 return false; 6313 } 6314 } 6315 6316 default: 6317 return visitNonBuiltinCallExpr(E); 6318 } 6319 } 6320 6321 //===----------------------------------------------------------------------===// 6322 // Member Pointer Evaluation 6323 //===----------------------------------------------------------------------===// 6324 6325 namespace { 6326 class MemberPointerExprEvaluator 6327 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 6328 MemberPtr &Result; 6329 6330 bool Success(const ValueDecl *D) { 6331 Result = MemberPtr(D); 6332 return true; 6333 } 6334 public: 6335 6336 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 6337 : ExprEvaluatorBaseTy(Info), Result(Result) {} 6338 6339 bool Success(const APValue &V, const Expr *E) { 6340 Result.setFrom(V); 6341 return true; 6342 } 6343 bool ZeroInitialization(const Expr *E) { 6344 return Success((const ValueDecl*)nullptr); 6345 } 6346 6347 bool VisitCastExpr(const CastExpr *E); 6348 bool VisitUnaryAddrOf(const UnaryOperator *E); 6349 }; 6350 } // end anonymous namespace 6351 6352 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 6353 EvalInfo &Info) { 6354 assert(E->isRValue() && E->getType()->isMemberPointerType()); 6355 return MemberPointerExprEvaluator(Info, Result).Visit(E); 6356 } 6357 6358 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 6359 switch (E->getCastKind()) { 6360 default: 6361 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6362 6363 case CK_NullToMemberPointer: 6364 VisitIgnoredValue(E->getSubExpr()); 6365 return ZeroInitialization(E); 6366 6367 case CK_BaseToDerivedMemberPointer: { 6368 if (!Visit(E->getSubExpr())) 6369 return false; 6370 if (E->path_empty()) 6371 return true; 6372 // Base-to-derived member pointer casts store the path in derived-to-base 6373 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 6374 // the wrong end of the derived->base arc, so stagger the path by one class. 6375 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 6376 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 6377 PathI != PathE; ++PathI) { 6378 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6379 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 6380 if (!Result.castToDerived(Derived)) 6381 return Error(E); 6382 } 6383 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 6384 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 6385 return Error(E); 6386 return true; 6387 } 6388 6389 case CK_DerivedToBaseMemberPointer: 6390 if (!Visit(E->getSubExpr())) 6391 return false; 6392 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6393 PathE = E->path_end(); PathI != PathE; ++PathI) { 6394 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 6395 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6396 if (!Result.castToBase(Base)) 6397 return Error(E); 6398 } 6399 return true; 6400 } 6401 } 6402 6403 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 6404 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 6405 // member can be formed. 6406 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 6407 } 6408 6409 //===----------------------------------------------------------------------===// 6410 // Record Evaluation 6411 //===----------------------------------------------------------------------===// 6412 6413 namespace { 6414 class RecordExprEvaluator 6415 : public ExprEvaluatorBase<RecordExprEvaluator> { 6416 const LValue &This; 6417 APValue &Result; 6418 public: 6419 6420 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 6421 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 6422 6423 bool Success(const APValue &V, const Expr *E) { 6424 Result = V; 6425 return true; 6426 } 6427 bool ZeroInitialization(const Expr *E) { 6428 return ZeroInitialization(E, E->getType()); 6429 } 6430 bool ZeroInitialization(const Expr *E, QualType T); 6431 6432 bool VisitCallExpr(const CallExpr *E) { 6433 return handleCallExpr(E, Result, &This); 6434 } 6435 bool VisitCastExpr(const CastExpr *E); 6436 bool VisitInitListExpr(const InitListExpr *E); 6437 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6438 return VisitCXXConstructExpr(E, E->getType()); 6439 } 6440 bool VisitLambdaExpr(const LambdaExpr *E); 6441 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 6442 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 6443 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 6444 6445 bool VisitBinCmp(const BinaryOperator *E); 6446 }; 6447 } 6448 6449 /// Perform zero-initialization on an object of non-union class type. 6450 /// C++11 [dcl.init]p5: 6451 /// To zero-initialize an object or reference of type T means: 6452 /// [...] 6453 /// -- if T is a (possibly cv-qualified) non-union class type, 6454 /// each non-static data member and each base-class subobject is 6455 /// zero-initialized 6456 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 6457 const RecordDecl *RD, 6458 const LValue &This, APValue &Result) { 6459 assert(!RD->isUnion() && "Expected non-union class type"); 6460 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 6461 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 6462 std::distance(RD->field_begin(), RD->field_end())); 6463 6464 if (RD->isInvalidDecl()) return false; 6465 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6466 6467 if (CD) { 6468 unsigned Index = 0; 6469 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 6470 End = CD->bases_end(); I != End; ++I, ++Index) { 6471 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 6472 LValue Subobject = This; 6473 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 6474 return false; 6475 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 6476 Result.getStructBase(Index))) 6477 return false; 6478 } 6479 } 6480 6481 for (const auto *I : RD->fields()) { 6482 // -- if T is a reference type, no initialization is performed. 6483 if (I->getType()->isReferenceType()) 6484 continue; 6485 6486 LValue Subobject = This; 6487 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 6488 return false; 6489 6490 ImplicitValueInitExpr VIE(I->getType()); 6491 if (!EvaluateInPlace( 6492 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 6493 return false; 6494 } 6495 6496 return true; 6497 } 6498 6499 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 6500 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 6501 if (RD->isInvalidDecl()) return false; 6502 if (RD->isUnion()) { 6503 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 6504 // object's first non-static named data member is zero-initialized 6505 RecordDecl::field_iterator I = RD->field_begin(); 6506 if (I == RD->field_end()) { 6507 Result = APValue((const FieldDecl*)nullptr); 6508 return true; 6509 } 6510 6511 LValue Subobject = This; 6512 if (!HandleLValueMember(Info, E, Subobject, *I)) 6513 return false; 6514 Result = APValue(*I); 6515 ImplicitValueInitExpr VIE(I->getType()); 6516 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 6517 } 6518 6519 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 6520 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 6521 return false; 6522 } 6523 6524 return HandleClassZeroInitialization(Info, E, RD, This, Result); 6525 } 6526 6527 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 6528 switch (E->getCastKind()) { 6529 default: 6530 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6531 6532 case CK_ConstructorConversion: 6533 return Visit(E->getSubExpr()); 6534 6535 case CK_DerivedToBase: 6536 case CK_UncheckedDerivedToBase: { 6537 APValue DerivedObject; 6538 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 6539 return false; 6540 if (!DerivedObject.isStruct()) 6541 return Error(E->getSubExpr()); 6542 6543 // Derived-to-base rvalue conversion: just slice off the derived part. 6544 APValue *Value = &DerivedObject; 6545 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 6546 for (CastExpr::path_const_iterator PathI = E->path_begin(), 6547 PathE = E->path_end(); PathI != PathE; ++PathI) { 6548 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 6549 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 6550 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 6551 RD = Base; 6552 } 6553 Result = *Value; 6554 return true; 6555 } 6556 } 6557 } 6558 6559 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6560 if (E->isTransparent()) 6561 return Visit(E->getInit(0)); 6562 6563 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 6564 if (RD->isInvalidDecl()) return false; 6565 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6566 6567 if (RD->isUnion()) { 6568 const FieldDecl *Field = E->getInitializedFieldInUnion(); 6569 Result = APValue(Field); 6570 if (!Field) 6571 return true; 6572 6573 // If the initializer list for a union does not contain any elements, the 6574 // first element of the union is value-initialized. 6575 // FIXME: The element should be initialized from an initializer list. 6576 // Is this difference ever observable for initializer lists which 6577 // we don't build? 6578 ImplicitValueInitExpr VIE(Field->getType()); 6579 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 6580 6581 LValue Subobject = This; 6582 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 6583 return false; 6584 6585 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6586 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6587 isa<CXXDefaultInitExpr>(InitExpr)); 6588 6589 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 6590 } 6591 6592 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 6593 if (Result.isUninit()) 6594 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 6595 std::distance(RD->field_begin(), RD->field_end())); 6596 unsigned ElementNo = 0; 6597 bool Success = true; 6598 6599 // Initialize base classes. 6600 if (CXXRD) { 6601 for (const auto &Base : CXXRD->bases()) { 6602 assert(ElementNo < E->getNumInits() && "missing init for base class"); 6603 const Expr *Init = E->getInit(ElementNo); 6604 6605 LValue Subobject = This; 6606 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 6607 return false; 6608 6609 APValue &FieldVal = Result.getStructBase(ElementNo); 6610 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 6611 if (!Info.noteFailure()) 6612 return false; 6613 Success = false; 6614 } 6615 ++ElementNo; 6616 } 6617 } 6618 6619 // Initialize members. 6620 for (const auto *Field : RD->fields()) { 6621 // Anonymous bit-fields are not considered members of the class for 6622 // purposes of aggregate initialization. 6623 if (Field->isUnnamedBitfield()) 6624 continue; 6625 6626 LValue Subobject = This; 6627 6628 bool HaveInit = ElementNo < E->getNumInits(); 6629 6630 // FIXME: Diagnostics here should point to the end of the initializer 6631 // list, not the start. 6632 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 6633 Subobject, Field, &Layout)) 6634 return false; 6635 6636 // Perform an implicit value-initialization for members beyond the end of 6637 // the initializer list. 6638 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 6639 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 6640 6641 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 6642 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 6643 isa<CXXDefaultInitExpr>(Init)); 6644 6645 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6646 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 6647 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 6648 FieldVal, Field))) { 6649 if (!Info.noteFailure()) 6650 return false; 6651 Success = false; 6652 } 6653 } 6654 6655 return Success; 6656 } 6657 6658 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 6659 QualType T) { 6660 // Note that E's type is not necessarily the type of our class here; we might 6661 // be initializing an array element instead. 6662 const CXXConstructorDecl *FD = E->getConstructor(); 6663 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 6664 6665 bool ZeroInit = E->requiresZeroInitialization(); 6666 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 6667 // If we've already performed zero-initialization, we're already done. 6668 if (!Result.isUninit()) 6669 return true; 6670 6671 // We can get here in two different ways: 6672 // 1) We're performing value-initialization, and should zero-initialize 6673 // the object, or 6674 // 2) We're performing default-initialization of an object with a trivial 6675 // constexpr default constructor, in which case we should start the 6676 // lifetimes of all the base subobjects (there can be no data member 6677 // subobjects in this case) per [basic.life]p1. 6678 // Either way, ZeroInitialization is appropriate. 6679 return ZeroInitialization(E, T); 6680 } 6681 6682 const FunctionDecl *Definition = nullptr; 6683 auto Body = FD->getBody(Definition); 6684 6685 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6686 return false; 6687 6688 // Avoid materializing a temporary for an elidable copy/move constructor. 6689 if (E->isElidable() && !ZeroInit) 6690 if (const MaterializeTemporaryExpr *ME 6691 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 6692 return Visit(ME->GetTemporaryExpr()); 6693 6694 if (ZeroInit && !ZeroInitialization(E, T)) 6695 return false; 6696 6697 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 6698 return HandleConstructorCall(E, This, Args, 6699 cast<CXXConstructorDecl>(Definition), Info, 6700 Result); 6701 } 6702 6703 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 6704 const CXXInheritedCtorInitExpr *E) { 6705 if (!Info.CurrentCall) { 6706 assert(Info.checkingPotentialConstantExpression()); 6707 return false; 6708 } 6709 6710 const CXXConstructorDecl *FD = E->getConstructor(); 6711 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 6712 return false; 6713 6714 const FunctionDecl *Definition = nullptr; 6715 auto Body = FD->getBody(Definition); 6716 6717 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 6718 return false; 6719 6720 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 6721 cast<CXXConstructorDecl>(Definition), Info, 6722 Result); 6723 } 6724 6725 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 6726 const CXXStdInitializerListExpr *E) { 6727 const ConstantArrayType *ArrayType = 6728 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 6729 6730 LValue Array; 6731 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 6732 return false; 6733 6734 // Get a pointer to the first element of the array. 6735 Array.addArray(Info, E, ArrayType); 6736 6737 // FIXME: Perform the checks on the field types in SemaInit. 6738 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 6739 RecordDecl::field_iterator Field = Record->field_begin(); 6740 if (Field == Record->field_end()) 6741 return Error(E); 6742 6743 // Start pointer. 6744 if (!Field->getType()->isPointerType() || 6745 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6746 ArrayType->getElementType())) 6747 return Error(E); 6748 6749 // FIXME: What if the initializer_list type has base classes, etc? 6750 Result = APValue(APValue::UninitStruct(), 0, 2); 6751 Array.moveInto(Result.getStructField(0)); 6752 6753 if (++Field == Record->field_end()) 6754 return Error(E); 6755 6756 if (Field->getType()->isPointerType() && 6757 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 6758 ArrayType->getElementType())) { 6759 // End pointer. 6760 if (!HandleLValueArrayAdjustment(Info, E, Array, 6761 ArrayType->getElementType(), 6762 ArrayType->getSize().getZExtValue())) 6763 return false; 6764 Array.moveInto(Result.getStructField(1)); 6765 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 6766 // Length. 6767 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 6768 else 6769 return Error(E); 6770 6771 if (++Field != Record->field_end()) 6772 return Error(E); 6773 6774 return true; 6775 } 6776 6777 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 6778 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 6779 if (ClosureClass->isInvalidDecl()) return false; 6780 6781 if (Info.checkingPotentialConstantExpression()) return true; 6782 6783 const size_t NumFields = 6784 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 6785 6786 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 6787 E->capture_init_end()) && 6788 "The number of lambda capture initializers should equal the number of " 6789 "fields within the closure type"); 6790 6791 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 6792 // Iterate through all the lambda's closure object's fields and initialize 6793 // them. 6794 auto *CaptureInitIt = E->capture_init_begin(); 6795 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 6796 bool Success = true; 6797 for (const auto *Field : ClosureClass->fields()) { 6798 assert(CaptureInitIt != E->capture_init_end()); 6799 // Get the initializer for this field 6800 Expr *const CurFieldInit = *CaptureInitIt++; 6801 6802 // If there is no initializer, either this is a VLA or an error has 6803 // occurred. 6804 if (!CurFieldInit) 6805 return Error(E); 6806 6807 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 6808 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 6809 if (!Info.keepEvaluatingAfterFailure()) 6810 return false; 6811 Success = false; 6812 } 6813 ++CaptureIt; 6814 } 6815 return Success; 6816 } 6817 6818 static bool EvaluateRecord(const Expr *E, const LValue &This, 6819 APValue &Result, EvalInfo &Info) { 6820 assert(E->isRValue() && E->getType()->isRecordType() && 6821 "can't evaluate expression as a record rvalue"); 6822 return RecordExprEvaluator(Info, This, Result).Visit(E); 6823 } 6824 6825 //===----------------------------------------------------------------------===// 6826 // Temporary Evaluation 6827 // 6828 // Temporaries are represented in the AST as rvalues, but generally behave like 6829 // lvalues. The full-object of which the temporary is a subobject is implicitly 6830 // materialized so that a reference can bind to it. 6831 //===----------------------------------------------------------------------===// 6832 namespace { 6833 class TemporaryExprEvaluator 6834 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 6835 public: 6836 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 6837 LValueExprEvaluatorBaseTy(Info, Result, false) {} 6838 6839 /// Visit an expression which constructs the value of this temporary. 6840 bool VisitConstructExpr(const Expr *E) { 6841 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall); 6842 return EvaluateInPlace(Value, Info, Result, E); 6843 } 6844 6845 bool VisitCastExpr(const CastExpr *E) { 6846 switch (E->getCastKind()) { 6847 default: 6848 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 6849 6850 case CK_ConstructorConversion: 6851 return VisitConstructExpr(E->getSubExpr()); 6852 } 6853 } 6854 bool VisitInitListExpr(const InitListExpr *E) { 6855 return VisitConstructExpr(E); 6856 } 6857 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 6858 return VisitConstructExpr(E); 6859 } 6860 bool VisitCallExpr(const CallExpr *E) { 6861 return VisitConstructExpr(E); 6862 } 6863 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 6864 return VisitConstructExpr(E); 6865 } 6866 bool VisitLambdaExpr(const LambdaExpr *E) { 6867 return VisitConstructExpr(E); 6868 } 6869 }; 6870 } // end anonymous namespace 6871 6872 /// Evaluate an expression of record type as a temporary. 6873 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 6874 assert(E->isRValue() && E->getType()->isRecordType()); 6875 return TemporaryExprEvaluator(Info, Result).Visit(E); 6876 } 6877 6878 //===----------------------------------------------------------------------===// 6879 // Vector Evaluation 6880 //===----------------------------------------------------------------------===// 6881 6882 namespace { 6883 class VectorExprEvaluator 6884 : public ExprEvaluatorBase<VectorExprEvaluator> { 6885 APValue &Result; 6886 public: 6887 6888 VectorExprEvaluator(EvalInfo &info, APValue &Result) 6889 : ExprEvaluatorBaseTy(info), Result(Result) {} 6890 6891 bool Success(ArrayRef<APValue> V, const Expr *E) { 6892 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 6893 // FIXME: remove this APValue copy. 6894 Result = APValue(V.data(), V.size()); 6895 return true; 6896 } 6897 bool Success(const APValue &V, const Expr *E) { 6898 assert(V.isVector()); 6899 Result = V; 6900 return true; 6901 } 6902 bool ZeroInitialization(const Expr *E); 6903 6904 bool VisitUnaryReal(const UnaryOperator *E) 6905 { return Visit(E->getSubExpr()); } 6906 bool VisitCastExpr(const CastExpr* E); 6907 bool VisitInitListExpr(const InitListExpr *E); 6908 bool VisitUnaryImag(const UnaryOperator *E); 6909 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 6910 // binary comparisons, binary and/or/xor, 6911 // shufflevector, ExtVectorElementExpr 6912 }; 6913 } // end anonymous namespace 6914 6915 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 6916 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 6917 return VectorExprEvaluator(Info, Result).Visit(E); 6918 } 6919 6920 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 6921 const VectorType *VTy = E->getType()->castAs<VectorType>(); 6922 unsigned NElts = VTy->getNumElements(); 6923 6924 const Expr *SE = E->getSubExpr(); 6925 QualType SETy = SE->getType(); 6926 6927 switch (E->getCastKind()) { 6928 case CK_VectorSplat: { 6929 APValue Val = APValue(); 6930 if (SETy->isIntegerType()) { 6931 APSInt IntResult; 6932 if (!EvaluateInteger(SE, IntResult, Info)) 6933 return false; 6934 Val = APValue(std::move(IntResult)); 6935 } else if (SETy->isRealFloatingType()) { 6936 APFloat FloatResult(0.0); 6937 if (!EvaluateFloat(SE, FloatResult, Info)) 6938 return false; 6939 Val = APValue(std::move(FloatResult)); 6940 } else { 6941 return Error(E); 6942 } 6943 6944 // Splat and create vector APValue. 6945 SmallVector<APValue, 4> Elts(NElts, Val); 6946 return Success(Elts, E); 6947 } 6948 case CK_BitCast: { 6949 // Evaluate the operand into an APInt we can extract from. 6950 llvm::APInt SValInt; 6951 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 6952 return false; 6953 // Extract the elements 6954 QualType EltTy = VTy->getElementType(); 6955 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 6956 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 6957 SmallVector<APValue, 4> Elts; 6958 if (EltTy->isRealFloatingType()) { 6959 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 6960 unsigned FloatEltSize = EltSize; 6961 if (&Sem == &APFloat::x87DoubleExtended()) 6962 FloatEltSize = 80; 6963 for (unsigned i = 0; i < NElts; i++) { 6964 llvm::APInt Elt; 6965 if (BigEndian) 6966 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 6967 else 6968 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 6969 Elts.push_back(APValue(APFloat(Sem, Elt))); 6970 } 6971 } else if (EltTy->isIntegerType()) { 6972 for (unsigned i = 0; i < NElts; i++) { 6973 llvm::APInt Elt; 6974 if (BigEndian) 6975 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 6976 else 6977 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 6978 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 6979 } 6980 } else { 6981 return Error(E); 6982 } 6983 return Success(Elts, E); 6984 } 6985 default: 6986 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6987 } 6988 } 6989 6990 bool 6991 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 6992 const VectorType *VT = E->getType()->castAs<VectorType>(); 6993 unsigned NumInits = E->getNumInits(); 6994 unsigned NumElements = VT->getNumElements(); 6995 6996 QualType EltTy = VT->getElementType(); 6997 SmallVector<APValue, 4> Elements; 6998 6999 // The number of initializers can be less than the number of 7000 // vector elements. For OpenCL, this can be due to nested vector 7001 // initialization. For GCC compatibility, missing trailing elements 7002 // should be initialized with zeroes. 7003 unsigned CountInits = 0, CountElts = 0; 7004 while (CountElts < NumElements) { 7005 // Handle nested vector initialization. 7006 if (CountInits < NumInits 7007 && E->getInit(CountInits)->getType()->isVectorType()) { 7008 APValue v; 7009 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 7010 return Error(E); 7011 unsigned vlen = v.getVectorLength(); 7012 for (unsigned j = 0; j < vlen; j++) 7013 Elements.push_back(v.getVectorElt(j)); 7014 CountElts += vlen; 7015 } else if (EltTy->isIntegerType()) { 7016 llvm::APSInt sInt(32); 7017 if (CountInits < NumInits) { 7018 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 7019 return false; 7020 } else // trailing integer zero. 7021 sInt = Info.Ctx.MakeIntValue(0, EltTy); 7022 Elements.push_back(APValue(sInt)); 7023 CountElts++; 7024 } else { 7025 llvm::APFloat f(0.0); 7026 if (CountInits < NumInits) { 7027 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 7028 return false; 7029 } else // trailing float zero. 7030 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 7031 Elements.push_back(APValue(f)); 7032 CountElts++; 7033 } 7034 CountInits++; 7035 } 7036 return Success(Elements, E); 7037 } 7038 7039 bool 7040 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 7041 const VectorType *VT = E->getType()->getAs<VectorType>(); 7042 QualType EltTy = VT->getElementType(); 7043 APValue ZeroElement; 7044 if (EltTy->isIntegerType()) 7045 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 7046 else 7047 ZeroElement = 7048 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 7049 7050 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 7051 return Success(Elements, E); 7052 } 7053 7054 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 7055 VisitIgnoredValue(E->getSubExpr()); 7056 return ZeroInitialization(E); 7057 } 7058 7059 //===----------------------------------------------------------------------===// 7060 // Array Evaluation 7061 //===----------------------------------------------------------------------===// 7062 7063 namespace { 7064 class ArrayExprEvaluator 7065 : public ExprEvaluatorBase<ArrayExprEvaluator> { 7066 const LValue &This; 7067 APValue &Result; 7068 public: 7069 7070 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 7071 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 7072 7073 bool Success(const APValue &V, const Expr *E) { 7074 assert((V.isArray() || V.isLValue()) && 7075 "expected array or string literal"); 7076 Result = V; 7077 return true; 7078 } 7079 7080 bool ZeroInitialization(const Expr *E) { 7081 const ConstantArrayType *CAT = 7082 Info.Ctx.getAsConstantArrayType(E->getType()); 7083 if (!CAT) 7084 return Error(E); 7085 7086 Result = APValue(APValue::UninitArray(), 0, 7087 CAT->getSize().getZExtValue()); 7088 if (!Result.hasArrayFiller()) return true; 7089 7090 // Zero-initialize all elements. 7091 LValue Subobject = This; 7092 Subobject.addArray(Info, E, CAT); 7093 ImplicitValueInitExpr VIE(CAT->getElementType()); 7094 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 7095 } 7096 7097 bool VisitCallExpr(const CallExpr *E) { 7098 return handleCallExpr(E, Result, &This); 7099 } 7100 bool VisitInitListExpr(const InitListExpr *E); 7101 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 7102 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 7103 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 7104 const LValue &Subobject, 7105 APValue *Value, QualType Type); 7106 }; 7107 } // end anonymous namespace 7108 7109 static bool EvaluateArray(const Expr *E, const LValue &This, 7110 APValue &Result, EvalInfo &Info) { 7111 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 7112 return ArrayExprEvaluator(Info, This, Result).Visit(E); 7113 } 7114 7115 // Return true iff the given array filler may depend on the element index. 7116 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 7117 // For now, just whitelist non-class value-initialization and initialization 7118 // lists comprised of them. 7119 if (isa<ImplicitValueInitExpr>(FillerExpr)) 7120 return false; 7121 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 7122 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 7123 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 7124 return true; 7125 } 7126 return false; 7127 } 7128 return true; 7129 } 7130 7131 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7132 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 7133 if (!CAT) 7134 return Error(E); 7135 7136 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 7137 // an appropriately-typed string literal enclosed in braces. 7138 if (E->isStringLiteralInit()) { 7139 LValue LV; 7140 if (!EvaluateLValue(E->getInit(0), LV, Info)) 7141 return false; 7142 APValue Val; 7143 LV.moveInto(Val); 7144 return Success(Val, E); 7145 } 7146 7147 bool Success = true; 7148 7149 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 7150 "zero-initialized array shouldn't have any initialized elts"); 7151 APValue Filler; 7152 if (Result.isArray() && Result.hasArrayFiller()) 7153 Filler = Result.getArrayFiller(); 7154 7155 unsigned NumEltsToInit = E->getNumInits(); 7156 unsigned NumElts = CAT->getSize().getZExtValue(); 7157 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 7158 7159 // If the initializer might depend on the array index, run it for each 7160 // array element. 7161 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 7162 NumEltsToInit = NumElts; 7163 7164 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 7165 << NumEltsToInit << ".\n"); 7166 7167 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 7168 7169 // If the array was previously zero-initialized, preserve the 7170 // zero-initialized values. 7171 if (!Filler.isUninit()) { 7172 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 7173 Result.getArrayInitializedElt(I) = Filler; 7174 if (Result.hasArrayFiller()) 7175 Result.getArrayFiller() = Filler; 7176 } 7177 7178 LValue Subobject = This; 7179 Subobject.addArray(Info, E, CAT); 7180 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 7181 const Expr *Init = 7182 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 7183 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 7184 Info, Subobject, Init) || 7185 !HandleLValueArrayAdjustment(Info, Init, Subobject, 7186 CAT->getElementType(), 1)) { 7187 if (!Info.noteFailure()) 7188 return false; 7189 Success = false; 7190 } 7191 } 7192 7193 if (!Result.hasArrayFiller()) 7194 return Success; 7195 7196 // If we get here, we have a trivial filler, which we can just evaluate 7197 // once and splat over the rest of the array elements. 7198 assert(FillerExpr && "no array filler for incomplete init list"); 7199 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 7200 FillerExpr) && Success; 7201 } 7202 7203 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 7204 if (E->getCommonExpr() && 7205 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false), 7206 Info, E->getCommonExpr()->getSourceExpr())) 7207 return false; 7208 7209 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 7210 7211 uint64_t Elements = CAT->getSize().getZExtValue(); 7212 Result = APValue(APValue::UninitArray(), Elements, Elements); 7213 7214 LValue Subobject = This; 7215 Subobject.addArray(Info, E, CAT); 7216 7217 bool Success = true; 7218 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 7219 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 7220 Info, Subobject, E->getSubExpr()) || 7221 !HandleLValueArrayAdjustment(Info, E, Subobject, 7222 CAT->getElementType(), 1)) { 7223 if (!Info.noteFailure()) 7224 return false; 7225 Success = false; 7226 } 7227 } 7228 7229 return Success; 7230 } 7231 7232 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 7233 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 7234 } 7235 7236 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 7237 const LValue &Subobject, 7238 APValue *Value, 7239 QualType Type) { 7240 bool HadZeroInit = !Value->isUninit(); 7241 7242 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 7243 unsigned N = CAT->getSize().getZExtValue(); 7244 7245 // Preserve the array filler if we had prior zero-initialization. 7246 APValue Filler = 7247 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 7248 : APValue(); 7249 7250 *Value = APValue(APValue::UninitArray(), N, N); 7251 7252 if (HadZeroInit) 7253 for (unsigned I = 0; I != N; ++I) 7254 Value->getArrayInitializedElt(I) = Filler; 7255 7256 // Initialize the elements. 7257 LValue ArrayElt = Subobject; 7258 ArrayElt.addArray(Info, E, CAT); 7259 for (unsigned I = 0; I != N; ++I) 7260 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 7261 CAT->getElementType()) || 7262 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 7263 CAT->getElementType(), 1)) 7264 return false; 7265 7266 return true; 7267 } 7268 7269 if (!Type->isRecordType()) 7270 return Error(E); 7271 7272 return RecordExprEvaluator(Info, Subobject, *Value) 7273 .VisitCXXConstructExpr(E, Type); 7274 } 7275 7276 //===----------------------------------------------------------------------===// 7277 // Integer Evaluation 7278 // 7279 // As a GNU extension, we support casting pointers to sufficiently-wide integer 7280 // types and back in constant folding. Integer values are thus represented 7281 // either as an integer-valued APValue, or as an lvalue-valued APValue. 7282 //===----------------------------------------------------------------------===// 7283 7284 namespace { 7285 class IntExprEvaluator 7286 : public ExprEvaluatorBase<IntExprEvaluator> { 7287 APValue &Result; 7288 public: 7289 IntExprEvaluator(EvalInfo &info, APValue &result) 7290 : ExprEvaluatorBaseTy(info), Result(result) {} 7291 7292 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 7293 assert(E->getType()->isIntegralOrEnumerationType() && 7294 "Invalid evaluation result."); 7295 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 7296 "Invalid evaluation result."); 7297 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7298 "Invalid evaluation result."); 7299 Result = APValue(SI); 7300 return true; 7301 } 7302 bool Success(const llvm::APSInt &SI, const Expr *E) { 7303 return Success(SI, E, Result); 7304 } 7305 7306 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 7307 assert(E->getType()->isIntegralOrEnumerationType() && 7308 "Invalid evaluation result."); 7309 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7310 "Invalid evaluation result."); 7311 Result = APValue(APSInt(I)); 7312 Result.getInt().setIsUnsigned( 7313 E->getType()->isUnsignedIntegerOrEnumerationType()); 7314 return true; 7315 } 7316 bool Success(const llvm::APInt &I, const Expr *E) { 7317 return Success(I, E, Result); 7318 } 7319 7320 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 7321 assert(E->getType()->isIntegralOrEnumerationType() && 7322 "Invalid evaluation result."); 7323 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 7324 return true; 7325 } 7326 bool Success(uint64_t Value, const Expr *E) { 7327 return Success(Value, E, Result); 7328 } 7329 7330 bool Success(CharUnits Size, const Expr *E) { 7331 return Success(Size.getQuantity(), E); 7332 } 7333 7334 bool Success(const APValue &V, const Expr *E) { 7335 if (V.isLValue() || V.isAddrLabelDiff()) { 7336 Result = V; 7337 return true; 7338 } 7339 return Success(V.getInt(), E); 7340 } 7341 7342 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 7343 7344 //===--------------------------------------------------------------------===// 7345 // Visitor Methods 7346 //===--------------------------------------------------------------------===// 7347 7348 bool VisitIntegerLiteral(const IntegerLiteral *E) { 7349 return Success(E->getValue(), E); 7350 } 7351 bool VisitCharacterLiteral(const CharacterLiteral *E) { 7352 return Success(E->getValue(), E); 7353 } 7354 7355 bool CheckReferencedDecl(const Expr *E, const Decl *D); 7356 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7357 if (CheckReferencedDecl(E, E->getDecl())) 7358 return true; 7359 7360 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 7361 } 7362 bool VisitMemberExpr(const MemberExpr *E) { 7363 if (CheckReferencedDecl(E, E->getMemberDecl())) { 7364 VisitIgnoredBaseExpression(E->getBase()); 7365 return true; 7366 } 7367 7368 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 7369 } 7370 7371 bool VisitCallExpr(const CallExpr *E); 7372 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 7373 bool VisitBinaryOperator(const BinaryOperator *E); 7374 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 7375 bool VisitUnaryOperator(const UnaryOperator *E); 7376 7377 bool VisitCastExpr(const CastExpr* E); 7378 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 7379 7380 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 7381 return Success(E->getValue(), E); 7382 } 7383 7384 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 7385 return Success(E->getValue(), E); 7386 } 7387 7388 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 7389 if (Info.ArrayInitIndex == uint64_t(-1)) { 7390 // We were asked to evaluate this subexpression independent of the 7391 // enclosing ArrayInitLoopExpr. We can't do that. 7392 Info.FFDiag(E); 7393 return false; 7394 } 7395 return Success(Info.ArrayInitIndex, E); 7396 } 7397 7398 // Note, GNU defines __null as an integer, not a pointer. 7399 bool VisitGNUNullExpr(const GNUNullExpr *E) { 7400 return ZeroInitialization(E); 7401 } 7402 7403 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 7404 return Success(E->getValue(), E); 7405 } 7406 7407 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 7408 return Success(E->getValue(), E); 7409 } 7410 7411 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 7412 return Success(E->getValue(), E); 7413 } 7414 7415 bool VisitUnaryReal(const UnaryOperator *E); 7416 bool VisitUnaryImag(const UnaryOperator *E); 7417 7418 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 7419 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 7420 7421 // FIXME: Missing: array subscript of vector, member of vector 7422 }; 7423 7424 class FixedPointExprEvaluator 7425 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 7426 APValue &Result; 7427 7428 public: 7429 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 7430 : ExprEvaluatorBaseTy(info), Result(result) {} 7431 7432 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 7433 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7434 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() && 7435 "Invalid evaluation result."); 7436 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7437 "Invalid evaluation result."); 7438 Result = APValue(SI); 7439 return true; 7440 } 7441 bool Success(const llvm::APSInt &SI, const Expr *E) { 7442 return Success(SI, E, Result); 7443 } 7444 7445 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 7446 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7447 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 7448 "Invalid evaluation result."); 7449 Result = APValue(APSInt(I)); 7450 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType()); 7451 return true; 7452 } 7453 bool Success(const llvm::APInt &I, const Expr *E) { 7454 return Success(I, E, Result); 7455 } 7456 7457 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 7458 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 7459 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 7460 return true; 7461 } 7462 bool Success(uint64_t Value, const Expr *E) { 7463 return Success(Value, E, Result); 7464 } 7465 7466 bool Success(CharUnits Size, const Expr *E) { 7467 return Success(Size.getQuantity(), E); 7468 } 7469 7470 bool Success(const APValue &V, const Expr *E) { 7471 if (V.isLValue() || V.isAddrLabelDiff()) { 7472 Result = V; 7473 return true; 7474 } 7475 return Success(V.getInt(), E); 7476 } 7477 7478 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 7479 7480 //===--------------------------------------------------------------------===// 7481 // Visitor Methods 7482 //===--------------------------------------------------------------------===// 7483 7484 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 7485 return Success(E->getValue(), E); 7486 } 7487 7488 bool VisitUnaryOperator(const UnaryOperator *E); 7489 }; 7490 } // end anonymous namespace 7491 7492 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 7493 /// produce either the integer value or a pointer. 7494 /// 7495 /// GCC has a heinous extension which folds casts between pointer types and 7496 /// pointer-sized integral types. We support this by allowing the evaluation of 7497 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 7498 /// Some simple arithmetic on such values is supported (they are treated much 7499 /// like char*). 7500 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 7501 EvalInfo &Info) { 7502 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 7503 return IntExprEvaluator(Info, Result).Visit(E); 7504 } 7505 7506 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 7507 APValue Val; 7508 if (!EvaluateIntegerOrLValue(E, Val, Info)) 7509 return false; 7510 if (!Val.isInt()) { 7511 // FIXME: It would be better to produce the diagnostic for casting 7512 // a pointer to an integer. 7513 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 7514 return false; 7515 } 7516 Result = Val.getInt(); 7517 return true; 7518 } 7519 7520 /// Check whether the given declaration can be directly converted to an integral 7521 /// rvalue. If not, no diagnostic is produced; there are other things we can 7522 /// try. 7523 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 7524 // Enums are integer constant exprs. 7525 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 7526 // Check for signedness/width mismatches between E type and ECD value. 7527 bool SameSign = (ECD->getInitVal().isSigned() 7528 == E->getType()->isSignedIntegerOrEnumerationType()); 7529 bool SameWidth = (ECD->getInitVal().getBitWidth() 7530 == Info.Ctx.getIntWidth(E->getType())); 7531 if (SameSign && SameWidth) 7532 return Success(ECD->getInitVal(), E); 7533 else { 7534 // Get rid of mismatch (otherwise Success assertions will fail) 7535 // by computing a new value matching the type of E. 7536 llvm::APSInt Val = ECD->getInitVal(); 7537 if (!SameSign) 7538 Val.setIsSigned(!ECD->getInitVal().isSigned()); 7539 if (!SameWidth) 7540 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 7541 return Success(Val, E); 7542 } 7543 } 7544 return false; 7545 } 7546 7547 /// Values returned by __builtin_classify_type, chosen to match the values 7548 /// produced by GCC's builtin. 7549 enum class GCCTypeClass { 7550 None = -1, 7551 Void = 0, 7552 Integer = 1, 7553 // GCC reserves 2 for character types, but instead classifies them as 7554 // integers. 7555 Enum = 3, 7556 Bool = 4, 7557 Pointer = 5, 7558 // GCC reserves 6 for references, but appears to never use it (because 7559 // expressions never have reference type, presumably). 7560 PointerToDataMember = 7, 7561 RealFloat = 8, 7562 Complex = 9, 7563 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 7564 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 7565 // GCC claims to reserve 11 for pointers to member functions, but *actually* 7566 // uses 12 for that purpose, same as for a class or struct. Maybe it 7567 // internally implements a pointer to member as a struct? Who knows. 7568 PointerToMemberFunction = 12, // Not a bug, see above. 7569 ClassOrStruct = 12, 7570 Union = 13, 7571 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 7572 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 7573 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 7574 // literals. 7575 }; 7576 7577 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 7578 /// as GCC. 7579 static GCCTypeClass 7580 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 7581 assert(!T->isDependentType() && "unexpected dependent type"); 7582 7583 QualType CanTy = T.getCanonicalType(); 7584 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 7585 7586 switch (CanTy->getTypeClass()) { 7587 #define TYPE(ID, BASE) 7588 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 7589 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 7590 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 7591 #include "clang/AST/TypeNodes.def" 7592 case Type::Auto: 7593 case Type::DeducedTemplateSpecialization: 7594 llvm_unreachable("unexpected non-canonical or dependent type"); 7595 7596 case Type::Builtin: 7597 switch (BT->getKind()) { 7598 #define BUILTIN_TYPE(ID, SINGLETON_ID) 7599 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 7600 case BuiltinType::ID: return GCCTypeClass::Integer; 7601 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 7602 case BuiltinType::ID: return GCCTypeClass::RealFloat; 7603 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 7604 case BuiltinType::ID: break; 7605 #include "clang/AST/BuiltinTypes.def" 7606 case BuiltinType::Void: 7607 return GCCTypeClass::Void; 7608 7609 case BuiltinType::Bool: 7610 return GCCTypeClass::Bool; 7611 7612 case BuiltinType::Char_U: 7613 case BuiltinType::UChar: 7614 case BuiltinType::WChar_U: 7615 case BuiltinType::Char8: 7616 case BuiltinType::Char16: 7617 case BuiltinType::Char32: 7618 case BuiltinType::UShort: 7619 case BuiltinType::UInt: 7620 case BuiltinType::ULong: 7621 case BuiltinType::ULongLong: 7622 case BuiltinType::UInt128: 7623 return GCCTypeClass::Integer; 7624 7625 case BuiltinType::UShortAccum: 7626 case BuiltinType::UAccum: 7627 case BuiltinType::ULongAccum: 7628 case BuiltinType::UShortFract: 7629 case BuiltinType::UFract: 7630 case BuiltinType::ULongFract: 7631 case BuiltinType::SatUShortAccum: 7632 case BuiltinType::SatUAccum: 7633 case BuiltinType::SatULongAccum: 7634 case BuiltinType::SatUShortFract: 7635 case BuiltinType::SatUFract: 7636 case BuiltinType::SatULongFract: 7637 return GCCTypeClass::None; 7638 7639 case BuiltinType::NullPtr: 7640 7641 case BuiltinType::ObjCId: 7642 case BuiltinType::ObjCClass: 7643 case BuiltinType::ObjCSel: 7644 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 7645 case BuiltinType::Id: 7646 #include "clang/Basic/OpenCLImageTypes.def" 7647 case BuiltinType::OCLSampler: 7648 case BuiltinType::OCLEvent: 7649 case BuiltinType::OCLClkEvent: 7650 case BuiltinType::OCLQueue: 7651 case BuiltinType::OCLReserveID: 7652 return GCCTypeClass::None; 7653 7654 case BuiltinType::Dependent: 7655 llvm_unreachable("unexpected dependent type"); 7656 }; 7657 llvm_unreachable("unexpected placeholder type"); 7658 7659 case Type::Enum: 7660 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 7661 7662 case Type::Pointer: 7663 case Type::ConstantArray: 7664 case Type::VariableArray: 7665 case Type::IncompleteArray: 7666 case Type::FunctionNoProto: 7667 case Type::FunctionProto: 7668 return GCCTypeClass::Pointer; 7669 7670 case Type::MemberPointer: 7671 return CanTy->isMemberDataPointerType() 7672 ? GCCTypeClass::PointerToDataMember 7673 : GCCTypeClass::PointerToMemberFunction; 7674 7675 case Type::Complex: 7676 return GCCTypeClass::Complex; 7677 7678 case Type::Record: 7679 return CanTy->isUnionType() ? GCCTypeClass::Union 7680 : GCCTypeClass::ClassOrStruct; 7681 7682 case Type::Atomic: 7683 // GCC classifies _Atomic T the same as T. 7684 return EvaluateBuiltinClassifyType( 7685 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 7686 7687 case Type::BlockPointer: 7688 case Type::Vector: 7689 case Type::ExtVector: 7690 case Type::ObjCObject: 7691 case Type::ObjCInterface: 7692 case Type::ObjCObjectPointer: 7693 case Type::Pipe: 7694 // GCC classifies vectors as None. We follow its lead and classify all 7695 // other types that don't fit into the regular classification the same way. 7696 return GCCTypeClass::None; 7697 7698 case Type::LValueReference: 7699 case Type::RValueReference: 7700 llvm_unreachable("invalid type for expression"); 7701 } 7702 7703 llvm_unreachable("unexpected type class"); 7704 } 7705 7706 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 7707 /// as GCC. 7708 static GCCTypeClass 7709 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 7710 // If no argument was supplied, default to None. This isn't 7711 // ideal, however it is what gcc does. 7712 if (E->getNumArgs() == 0) 7713 return GCCTypeClass::None; 7714 7715 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 7716 // being an ICE, but still folds it to a constant using the type of the first 7717 // argument. 7718 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 7719 } 7720 7721 /// EvaluateBuiltinConstantPForLValue - Determine the result of 7722 /// __builtin_constant_p when applied to the given lvalue. 7723 /// 7724 /// An lvalue is only "constant" if it is a pointer or reference to the first 7725 /// character of a string literal. 7726 template<typename LValue> 7727 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) { 7728 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>(); 7729 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero(); 7730 } 7731 7732 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 7733 /// GCC as we can manage. 7734 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) { 7735 QualType ArgType = Arg->getType(); 7736 7737 // __builtin_constant_p always has one operand. The rules which gcc follows 7738 // are not precisely documented, but are as follows: 7739 // 7740 // - If the operand is of integral, floating, complex or enumeration type, 7741 // and can be folded to a known value of that type, it returns 1. 7742 // - If the operand and can be folded to a pointer to the first character 7743 // of a string literal (or such a pointer cast to an integral type), it 7744 // returns 1. 7745 // 7746 // Otherwise, it returns 0. 7747 // 7748 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 7749 // its support for this does not currently work. 7750 if (ArgType->isIntegralOrEnumerationType()) { 7751 Expr::EvalResult Result; 7752 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects) 7753 return false; 7754 7755 APValue &V = Result.Val; 7756 if (V.getKind() == APValue::Int) 7757 return true; 7758 if (V.getKind() == APValue::LValue) 7759 return EvaluateBuiltinConstantPForLValue(V); 7760 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) { 7761 return Arg->isEvaluatable(Ctx); 7762 } else if (ArgType->isPointerType() || Arg->isGLValue()) { 7763 LValue LV; 7764 Expr::EvalStatus Status; 7765 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 7766 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info) 7767 : EvaluatePointer(Arg, LV, Info)) && 7768 !Status.HasSideEffects) 7769 return EvaluateBuiltinConstantPForLValue(LV); 7770 } 7771 7772 // Anything else isn't considered to be sufficiently constant. 7773 return false; 7774 } 7775 7776 /// Retrieves the "underlying object type" of the given expression, 7777 /// as used by __builtin_object_size. 7778 static QualType getObjectType(APValue::LValueBase B) { 7779 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 7780 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 7781 return VD->getType(); 7782 } else if (const Expr *E = B.get<const Expr*>()) { 7783 if (isa<CompoundLiteralExpr>(E)) 7784 return E->getType(); 7785 } 7786 7787 return QualType(); 7788 } 7789 7790 /// A more selective version of E->IgnoreParenCasts for 7791 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 7792 /// to change the type of E. 7793 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 7794 /// 7795 /// Always returns an RValue with a pointer representation. 7796 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 7797 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 7798 7799 auto *NoParens = E->IgnoreParens(); 7800 auto *Cast = dyn_cast<CastExpr>(NoParens); 7801 if (Cast == nullptr) 7802 return NoParens; 7803 7804 // We only conservatively allow a few kinds of casts, because this code is 7805 // inherently a simple solution that seeks to support the common case. 7806 auto CastKind = Cast->getCastKind(); 7807 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 7808 CastKind != CK_AddressSpaceConversion) 7809 return NoParens; 7810 7811 auto *SubExpr = Cast->getSubExpr(); 7812 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 7813 return NoParens; 7814 return ignorePointerCastsAndParens(SubExpr); 7815 } 7816 7817 /// Checks to see if the given LValue's Designator is at the end of the LValue's 7818 /// record layout. e.g. 7819 /// struct { struct { int a, b; } fst, snd; } obj; 7820 /// obj.fst // no 7821 /// obj.snd // yes 7822 /// obj.fst.a // no 7823 /// obj.fst.b // no 7824 /// obj.snd.a // no 7825 /// obj.snd.b // yes 7826 /// 7827 /// Please note: this function is specialized for how __builtin_object_size 7828 /// views "objects". 7829 /// 7830 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 7831 /// correct result, it will always return true. 7832 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 7833 assert(!LVal.Designator.Invalid); 7834 7835 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 7836 const RecordDecl *Parent = FD->getParent(); 7837 Invalid = Parent->isInvalidDecl(); 7838 if (Invalid || Parent->isUnion()) 7839 return true; 7840 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 7841 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 7842 }; 7843 7844 auto &Base = LVal.getLValueBase(); 7845 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 7846 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 7847 bool Invalid; 7848 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7849 return Invalid; 7850 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 7851 for (auto *FD : IFD->chain()) { 7852 bool Invalid; 7853 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 7854 return Invalid; 7855 } 7856 } 7857 } 7858 7859 unsigned I = 0; 7860 QualType BaseType = getType(Base); 7861 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 7862 // If we don't know the array bound, conservatively assume we're looking at 7863 // the final array element. 7864 ++I; 7865 if (BaseType->isIncompleteArrayType()) 7866 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 7867 else 7868 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 7869 } 7870 7871 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 7872 const auto &Entry = LVal.Designator.Entries[I]; 7873 if (BaseType->isArrayType()) { 7874 // Because __builtin_object_size treats arrays as objects, we can ignore 7875 // the index iff this is the last array in the Designator. 7876 if (I + 1 == E) 7877 return true; 7878 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 7879 uint64_t Index = Entry.ArrayIndex; 7880 if (Index + 1 != CAT->getSize()) 7881 return false; 7882 BaseType = CAT->getElementType(); 7883 } else if (BaseType->isAnyComplexType()) { 7884 const auto *CT = BaseType->castAs<ComplexType>(); 7885 uint64_t Index = Entry.ArrayIndex; 7886 if (Index != 1) 7887 return false; 7888 BaseType = CT->getElementType(); 7889 } else if (auto *FD = getAsField(Entry)) { 7890 bool Invalid; 7891 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 7892 return Invalid; 7893 BaseType = FD->getType(); 7894 } else { 7895 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 7896 return false; 7897 } 7898 } 7899 return true; 7900 } 7901 7902 /// Tests to see if the LValue has a user-specified designator (that isn't 7903 /// necessarily valid). Note that this always returns 'true' if the LValue has 7904 /// an unsized array as its first designator entry, because there's currently no 7905 /// way to tell if the user typed *foo or foo[0]. 7906 static bool refersToCompleteObject(const LValue &LVal) { 7907 if (LVal.Designator.Invalid) 7908 return false; 7909 7910 if (!LVal.Designator.Entries.empty()) 7911 return LVal.Designator.isMostDerivedAnUnsizedArray(); 7912 7913 if (!LVal.InvalidBase) 7914 return true; 7915 7916 // If `E` is a MemberExpr, then the first part of the designator is hiding in 7917 // the LValueBase. 7918 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 7919 return !E || !isa<MemberExpr>(E); 7920 } 7921 7922 /// Attempts to detect a user writing into a piece of memory that's impossible 7923 /// to figure out the size of by just using types. 7924 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 7925 const SubobjectDesignator &Designator = LVal.Designator; 7926 // Notes: 7927 // - Users can only write off of the end when we have an invalid base. Invalid 7928 // bases imply we don't know where the memory came from. 7929 // - We used to be a bit more aggressive here; we'd only be conservative if 7930 // the array at the end was flexible, or if it had 0 or 1 elements. This 7931 // broke some common standard library extensions (PR30346), but was 7932 // otherwise seemingly fine. It may be useful to reintroduce this behavior 7933 // with some sort of whitelist. OTOH, it seems that GCC is always 7934 // conservative with the last element in structs (if it's an array), so our 7935 // current behavior is more compatible than a whitelisting approach would 7936 // be. 7937 return LVal.InvalidBase && 7938 Designator.Entries.size() == Designator.MostDerivedPathLength && 7939 Designator.MostDerivedIsArrayElement && 7940 isDesignatorAtObjectEnd(Ctx, LVal); 7941 } 7942 7943 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 7944 /// Fails if the conversion would cause loss of precision. 7945 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 7946 CharUnits &Result) { 7947 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 7948 if (Int.ugt(CharUnitsMax)) 7949 return false; 7950 Result = CharUnits::fromQuantity(Int.getZExtValue()); 7951 return true; 7952 } 7953 7954 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 7955 /// determine how many bytes exist from the beginning of the object to either 7956 /// the end of the current subobject, or the end of the object itself, depending 7957 /// on what the LValue looks like + the value of Type. 7958 /// 7959 /// If this returns false, the value of Result is undefined. 7960 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 7961 unsigned Type, const LValue &LVal, 7962 CharUnits &EndOffset) { 7963 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 7964 7965 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 7966 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 7967 return false; 7968 return HandleSizeof(Info, ExprLoc, Ty, Result); 7969 }; 7970 7971 // We want to evaluate the size of the entire object. This is a valid fallback 7972 // for when Type=1 and the designator is invalid, because we're asked for an 7973 // upper-bound. 7974 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 7975 // Type=3 wants a lower bound, so we can't fall back to this. 7976 if (Type == 3 && !DetermineForCompleteObject) 7977 return false; 7978 7979 llvm::APInt APEndOffset; 7980 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7981 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 7982 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 7983 7984 if (LVal.InvalidBase) 7985 return false; 7986 7987 QualType BaseTy = getObjectType(LVal.getLValueBase()); 7988 return CheckedHandleSizeof(BaseTy, EndOffset); 7989 } 7990 7991 // We want to evaluate the size of a subobject. 7992 const SubobjectDesignator &Designator = LVal.Designator; 7993 7994 // The following is a moderately common idiom in C: 7995 // 7996 // struct Foo { int a; char c[1]; }; 7997 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 7998 // strcpy(&F->c[0], Bar); 7999 // 8000 // In order to not break too much legacy code, we need to support it. 8001 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 8002 // If we can resolve this to an alloc_size call, we can hand that back, 8003 // because we know for certain how many bytes there are to write to. 8004 llvm::APInt APEndOffset; 8005 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8006 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 8007 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 8008 8009 // If we cannot determine the size of the initial allocation, then we can't 8010 // given an accurate upper-bound. However, we are still able to give 8011 // conservative lower-bounds for Type=3. 8012 if (Type == 1) 8013 return false; 8014 } 8015 8016 CharUnits BytesPerElem; 8017 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 8018 return false; 8019 8020 // According to the GCC documentation, we want the size of the subobject 8021 // denoted by the pointer. But that's not quite right -- what we actually 8022 // want is the size of the immediately-enclosing array, if there is one. 8023 int64_t ElemsRemaining; 8024 if (Designator.MostDerivedIsArrayElement && 8025 Designator.Entries.size() == Designator.MostDerivedPathLength) { 8026 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 8027 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex; 8028 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 8029 } else { 8030 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 8031 } 8032 8033 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 8034 return true; 8035 } 8036 8037 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 8038 /// returns true and stores the result in @p Size. 8039 /// 8040 /// If @p WasError is non-null, this will report whether the failure to evaluate 8041 /// is to be treated as an Error in IntExprEvaluator. 8042 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 8043 EvalInfo &Info, uint64_t &Size) { 8044 // Determine the denoted object. 8045 LValue LVal; 8046 { 8047 // The operand of __builtin_object_size is never evaluated for side-effects. 8048 // If there are any, but we can determine the pointed-to object anyway, then 8049 // ignore the side-effects. 8050 SpeculativeEvaluationRAII SpeculativeEval(Info); 8051 IgnoreSideEffectsRAII Fold(Info); 8052 8053 if (E->isGLValue()) { 8054 // It's possible for us to be given GLValues if we're called via 8055 // Expr::tryEvaluateObjectSize. 8056 APValue RVal; 8057 if (!EvaluateAsRValue(Info, E, RVal)) 8058 return false; 8059 LVal.setFrom(Info.Ctx, RVal); 8060 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 8061 /*InvalidBaseOK=*/true)) 8062 return false; 8063 } 8064 8065 // If we point to before the start of the object, there are no accessible 8066 // bytes. 8067 if (LVal.getLValueOffset().isNegative()) { 8068 Size = 0; 8069 return true; 8070 } 8071 8072 CharUnits EndOffset; 8073 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 8074 return false; 8075 8076 // If we've fallen outside of the end offset, just pretend there's nothing to 8077 // write to/read from. 8078 if (EndOffset <= LVal.getLValueOffset()) 8079 Size = 0; 8080 else 8081 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 8082 return true; 8083 } 8084 8085 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 8086 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8087 return VisitBuiltinCallExpr(E, BuiltinOp); 8088 8089 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8090 } 8091 8092 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8093 unsigned BuiltinOp) { 8094 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 8095 default: 8096 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8097 8098 case Builtin::BI__builtin_object_size: { 8099 // The type was checked when we built the expression. 8100 unsigned Type = 8101 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 8102 assert(Type <= 3 && "unexpected type"); 8103 8104 uint64_t Size; 8105 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 8106 return Success(Size, E); 8107 8108 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 8109 return Success((Type & 2) ? 0 : -1, E); 8110 8111 // Expression had no side effects, but we couldn't statically determine the 8112 // size of the referenced object. 8113 switch (Info.EvalMode) { 8114 case EvalInfo::EM_ConstantExpression: 8115 case EvalInfo::EM_PotentialConstantExpression: 8116 case EvalInfo::EM_ConstantFold: 8117 case EvalInfo::EM_EvaluateForOverflow: 8118 case EvalInfo::EM_IgnoreSideEffects: 8119 // Leave it to IR generation. 8120 return Error(E); 8121 case EvalInfo::EM_ConstantExpressionUnevaluated: 8122 case EvalInfo::EM_PotentialConstantExpressionUnevaluated: 8123 // Reduce it to a constant now. 8124 return Success((Type & 2) ? 0 : -1, E); 8125 } 8126 8127 llvm_unreachable("unexpected EvalMode"); 8128 } 8129 8130 case Builtin::BI__builtin_os_log_format_buffer_size: { 8131 analyze_os_log::OSLogBufferLayout Layout; 8132 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 8133 return Success(Layout.size().getQuantity(), E); 8134 } 8135 8136 case Builtin::BI__builtin_bswap16: 8137 case Builtin::BI__builtin_bswap32: 8138 case Builtin::BI__builtin_bswap64: { 8139 APSInt Val; 8140 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8141 return false; 8142 8143 return Success(Val.byteSwap(), E); 8144 } 8145 8146 case Builtin::BI__builtin_classify_type: 8147 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 8148 8149 case Builtin::BI__builtin_clrsb: 8150 case Builtin::BI__builtin_clrsbl: 8151 case Builtin::BI__builtin_clrsbll: { 8152 APSInt Val; 8153 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8154 return false; 8155 8156 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 8157 } 8158 8159 case Builtin::BI__builtin_clz: 8160 case Builtin::BI__builtin_clzl: 8161 case Builtin::BI__builtin_clzll: 8162 case Builtin::BI__builtin_clzs: { 8163 APSInt Val; 8164 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8165 return false; 8166 if (!Val) 8167 return Error(E); 8168 8169 return Success(Val.countLeadingZeros(), E); 8170 } 8171 8172 case Builtin::BI__builtin_constant_p: 8173 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E); 8174 8175 case Builtin::BI__builtin_ctz: 8176 case Builtin::BI__builtin_ctzl: 8177 case Builtin::BI__builtin_ctzll: 8178 case Builtin::BI__builtin_ctzs: { 8179 APSInt Val; 8180 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8181 return false; 8182 if (!Val) 8183 return Error(E); 8184 8185 return Success(Val.countTrailingZeros(), E); 8186 } 8187 8188 case Builtin::BI__builtin_eh_return_data_regno: { 8189 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 8190 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 8191 return Success(Operand, E); 8192 } 8193 8194 case Builtin::BI__builtin_expect: 8195 return Visit(E->getArg(0)); 8196 8197 case Builtin::BI__builtin_ffs: 8198 case Builtin::BI__builtin_ffsl: 8199 case Builtin::BI__builtin_ffsll: { 8200 APSInt Val; 8201 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8202 return false; 8203 8204 unsigned N = Val.countTrailingZeros(); 8205 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 8206 } 8207 8208 case Builtin::BI__builtin_fpclassify: { 8209 APFloat Val(0.0); 8210 if (!EvaluateFloat(E->getArg(5), Val, Info)) 8211 return false; 8212 unsigned Arg; 8213 switch (Val.getCategory()) { 8214 case APFloat::fcNaN: Arg = 0; break; 8215 case APFloat::fcInfinity: Arg = 1; break; 8216 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 8217 case APFloat::fcZero: Arg = 4; break; 8218 } 8219 return Visit(E->getArg(Arg)); 8220 } 8221 8222 case Builtin::BI__builtin_isinf_sign: { 8223 APFloat Val(0.0); 8224 return EvaluateFloat(E->getArg(0), Val, Info) && 8225 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 8226 } 8227 8228 case Builtin::BI__builtin_isinf: { 8229 APFloat Val(0.0); 8230 return EvaluateFloat(E->getArg(0), Val, Info) && 8231 Success(Val.isInfinity() ? 1 : 0, E); 8232 } 8233 8234 case Builtin::BI__builtin_isfinite: { 8235 APFloat Val(0.0); 8236 return EvaluateFloat(E->getArg(0), Val, Info) && 8237 Success(Val.isFinite() ? 1 : 0, E); 8238 } 8239 8240 case Builtin::BI__builtin_isnan: { 8241 APFloat Val(0.0); 8242 return EvaluateFloat(E->getArg(0), Val, Info) && 8243 Success(Val.isNaN() ? 1 : 0, E); 8244 } 8245 8246 case Builtin::BI__builtin_isnormal: { 8247 APFloat Val(0.0); 8248 return EvaluateFloat(E->getArg(0), Val, Info) && 8249 Success(Val.isNormal() ? 1 : 0, E); 8250 } 8251 8252 case Builtin::BI__builtin_parity: 8253 case Builtin::BI__builtin_parityl: 8254 case Builtin::BI__builtin_parityll: { 8255 APSInt Val; 8256 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8257 return false; 8258 8259 return Success(Val.countPopulation() % 2, E); 8260 } 8261 8262 case Builtin::BI__builtin_popcount: 8263 case Builtin::BI__builtin_popcountl: 8264 case Builtin::BI__builtin_popcountll: { 8265 APSInt Val; 8266 if (!EvaluateInteger(E->getArg(0), Val, Info)) 8267 return false; 8268 8269 return Success(Val.countPopulation(), E); 8270 } 8271 8272 case Builtin::BIstrlen: 8273 case Builtin::BIwcslen: 8274 // A call to strlen is not a constant expression. 8275 if (Info.getLangOpts().CPlusPlus11) 8276 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8277 << /*isConstexpr*/0 << /*isConstructor*/0 8278 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8279 else 8280 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8281 LLVM_FALLTHROUGH; 8282 case Builtin::BI__builtin_strlen: 8283 case Builtin::BI__builtin_wcslen: { 8284 // As an extension, we support __builtin_strlen() as a constant expression, 8285 // and support folding strlen() to a constant. 8286 LValue String; 8287 if (!EvaluatePointer(E->getArg(0), String, Info)) 8288 return false; 8289 8290 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 8291 8292 // Fast path: if it's a string literal, search the string value. 8293 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 8294 String.getLValueBase().dyn_cast<const Expr *>())) { 8295 // The string literal may have embedded null characters. Find the first 8296 // one and truncate there. 8297 StringRef Str = S->getBytes(); 8298 int64_t Off = String.Offset.getQuantity(); 8299 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 8300 S->getCharByteWidth() == 1 && 8301 // FIXME: Add fast-path for wchar_t too. 8302 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 8303 Str = Str.substr(Off); 8304 8305 StringRef::size_type Pos = Str.find(0); 8306 if (Pos != StringRef::npos) 8307 Str = Str.substr(0, Pos); 8308 8309 return Success(Str.size(), E); 8310 } 8311 8312 // Fall through to slow path to issue appropriate diagnostic. 8313 } 8314 8315 // Slow path: scan the bytes of the string looking for the terminating 0. 8316 for (uint64_t Strlen = 0; /**/; ++Strlen) { 8317 APValue Char; 8318 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 8319 !Char.isInt()) 8320 return false; 8321 if (!Char.getInt()) 8322 return Success(Strlen, E); 8323 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 8324 return false; 8325 } 8326 } 8327 8328 case Builtin::BIstrcmp: 8329 case Builtin::BIwcscmp: 8330 case Builtin::BIstrncmp: 8331 case Builtin::BIwcsncmp: 8332 case Builtin::BImemcmp: 8333 case Builtin::BIwmemcmp: 8334 // A call to strlen is not a constant expression. 8335 if (Info.getLangOpts().CPlusPlus11) 8336 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8337 << /*isConstexpr*/0 << /*isConstructor*/0 8338 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8339 else 8340 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8341 LLVM_FALLTHROUGH; 8342 case Builtin::BI__builtin_strcmp: 8343 case Builtin::BI__builtin_wcscmp: 8344 case Builtin::BI__builtin_strncmp: 8345 case Builtin::BI__builtin_wcsncmp: 8346 case Builtin::BI__builtin_memcmp: 8347 case Builtin::BI__builtin_wmemcmp: { 8348 LValue String1, String2; 8349 if (!EvaluatePointer(E->getArg(0), String1, Info) || 8350 !EvaluatePointer(E->getArg(1), String2, Info)) 8351 return false; 8352 8353 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 8354 8355 uint64_t MaxLength = uint64_t(-1); 8356 if (BuiltinOp != Builtin::BIstrcmp && 8357 BuiltinOp != Builtin::BIwcscmp && 8358 BuiltinOp != Builtin::BI__builtin_strcmp && 8359 BuiltinOp != Builtin::BI__builtin_wcscmp) { 8360 APSInt N; 8361 if (!EvaluateInteger(E->getArg(2), N, Info)) 8362 return false; 8363 MaxLength = N.getExtValue(); 8364 } 8365 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp && 8366 BuiltinOp != Builtin::BIwmemcmp && 8367 BuiltinOp != Builtin::BI__builtin_memcmp && 8368 BuiltinOp != Builtin::BI__builtin_wmemcmp); 8369 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 8370 BuiltinOp == Builtin::BIwcsncmp || 8371 BuiltinOp == Builtin::BIwmemcmp || 8372 BuiltinOp == Builtin::BI__builtin_wcscmp || 8373 BuiltinOp == Builtin::BI__builtin_wcsncmp || 8374 BuiltinOp == Builtin::BI__builtin_wmemcmp; 8375 for (; MaxLength; --MaxLength) { 8376 APValue Char1, Char2; 8377 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) || 8378 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) || 8379 !Char1.isInt() || !Char2.isInt()) 8380 return false; 8381 if (Char1.getInt() != Char2.getInt()) { 8382 if (IsWide) // wmemcmp compares with wchar_t signedness. 8383 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 8384 // memcmp always compares unsigned chars. 8385 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 8386 } 8387 if (StopAtNull && !Char1.getInt()) 8388 return Success(0, E); 8389 assert(!(StopAtNull && !Char2.getInt())); 8390 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) || 8391 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1)) 8392 return false; 8393 } 8394 // We hit the strncmp / memcmp limit. 8395 return Success(0, E); 8396 } 8397 8398 case Builtin::BI__atomic_always_lock_free: 8399 case Builtin::BI__atomic_is_lock_free: 8400 case Builtin::BI__c11_atomic_is_lock_free: { 8401 APSInt SizeVal; 8402 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 8403 return false; 8404 8405 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 8406 // of two less than the maximum inline atomic width, we know it is 8407 // lock-free. If the size isn't a power of two, or greater than the 8408 // maximum alignment where we promote atomics, we know it is not lock-free 8409 // (at least not in the sense of atomic_is_lock_free). Otherwise, 8410 // the answer can only be determined at runtime; for example, 16-byte 8411 // atomics have lock-free implementations on some, but not all, 8412 // x86-64 processors. 8413 8414 // Check power-of-two. 8415 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 8416 if (Size.isPowerOfTwo()) { 8417 // Check against inlining width. 8418 unsigned InlineWidthBits = 8419 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 8420 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 8421 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 8422 Size == CharUnits::One() || 8423 E->getArg(1)->isNullPointerConstant(Info.Ctx, 8424 Expr::NPC_NeverValueDependent)) 8425 // OK, we will inline appropriately-aligned operations of this size, 8426 // and _Atomic(T) is appropriately-aligned. 8427 return Success(1, E); 8428 8429 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 8430 castAs<PointerType>()->getPointeeType(); 8431 if (!PointeeType->isIncompleteType() && 8432 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 8433 // OK, we will inline operations on this object. 8434 return Success(1, E); 8435 } 8436 } 8437 } 8438 8439 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 8440 Success(0, E) : Error(E); 8441 } 8442 case Builtin::BIomp_is_initial_device: 8443 // We can decide statically which value the runtime would return if called. 8444 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 8445 case Builtin::BI__builtin_add_overflow: 8446 case Builtin::BI__builtin_sub_overflow: 8447 case Builtin::BI__builtin_mul_overflow: 8448 case Builtin::BI__builtin_sadd_overflow: 8449 case Builtin::BI__builtin_uadd_overflow: 8450 case Builtin::BI__builtin_uaddl_overflow: 8451 case Builtin::BI__builtin_uaddll_overflow: 8452 case Builtin::BI__builtin_usub_overflow: 8453 case Builtin::BI__builtin_usubl_overflow: 8454 case Builtin::BI__builtin_usubll_overflow: 8455 case Builtin::BI__builtin_umul_overflow: 8456 case Builtin::BI__builtin_umull_overflow: 8457 case Builtin::BI__builtin_umulll_overflow: 8458 case Builtin::BI__builtin_saddl_overflow: 8459 case Builtin::BI__builtin_saddll_overflow: 8460 case Builtin::BI__builtin_ssub_overflow: 8461 case Builtin::BI__builtin_ssubl_overflow: 8462 case Builtin::BI__builtin_ssubll_overflow: 8463 case Builtin::BI__builtin_smul_overflow: 8464 case Builtin::BI__builtin_smull_overflow: 8465 case Builtin::BI__builtin_smulll_overflow: { 8466 LValue ResultLValue; 8467 APSInt LHS, RHS; 8468 8469 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 8470 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 8471 !EvaluateInteger(E->getArg(1), RHS, Info) || 8472 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 8473 return false; 8474 8475 APSInt Result; 8476 bool DidOverflow = false; 8477 8478 // If the types don't have to match, enlarge all 3 to the largest of them. 8479 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 8480 BuiltinOp == Builtin::BI__builtin_sub_overflow || 8481 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 8482 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 8483 ResultType->isSignedIntegerOrEnumerationType(); 8484 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 8485 ResultType->isSignedIntegerOrEnumerationType(); 8486 uint64_t LHSSize = LHS.getBitWidth(); 8487 uint64_t RHSSize = RHS.getBitWidth(); 8488 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 8489 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 8490 8491 // Add an additional bit if the signedness isn't uniformly agreed to. We 8492 // could do this ONLY if there is a signed and an unsigned that both have 8493 // MaxBits, but the code to check that is pretty nasty. The issue will be 8494 // caught in the shrink-to-result later anyway. 8495 if (IsSigned && !AllSigned) 8496 ++MaxBits; 8497 8498 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits), 8499 !IsSigned); 8500 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits), 8501 !IsSigned); 8502 Result = APSInt(MaxBits, !IsSigned); 8503 } 8504 8505 // Find largest int. 8506 switch (BuiltinOp) { 8507 default: 8508 llvm_unreachable("Invalid value for BuiltinOp"); 8509 case Builtin::BI__builtin_add_overflow: 8510 case Builtin::BI__builtin_sadd_overflow: 8511 case Builtin::BI__builtin_saddl_overflow: 8512 case Builtin::BI__builtin_saddll_overflow: 8513 case Builtin::BI__builtin_uadd_overflow: 8514 case Builtin::BI__builtin_uaddl_overflow: 8515 case Builtin::BI__builtin_uaddll_overflow: 8516 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 8517 : LHS.uadd_ov(RHS, DidOverflow); 8518 break; 8519 case Builtin::BI__builtin_sub_overflow: 8520 case Builtin::BI__builtin_ssub_overflow: 8521 case Builtin::BI__builtin_ssubl_overflow: 8522 case Builtin::BI__builtin_ssubll_overflow: 8523 case Builtin::BI__builtin_usub_overflow: 8524 case Builtin::BI__builtin_usubl_overflow: 8525 case Builtin::BI__builtin_usubll_overflow: 8526 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 8527 : LHS.usub_ov(RHS, DidOverflow); 8528 break; 8529 case Builtin::BI__builtin_mul_overflow: 8530 case Builtin::BI__builtin_smul_overflow: 8531 case Builtin::BI__builtin_smull_overflow: 8532 case Builtin::BI__builtin_smulll_overflow: 8533 case Builtin::BI__builtin_umul_overflow: 8534 case Builtin::BI__builtin_umull_overflow: 8535 case Builtin::BI__builtin_umulll_overflow: 8536 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 8537 : LHS.umul_ov(RHS, DidOverflow); 8538 break; 8539 } 8540 8541 // In the case where multiple sizes are allowed, truncate and see if 8542 // the values are the same. 8543 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 8544 BuiltinOp == Builtin::BI__builtin_sub_overflow || 8545 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 8546 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 8547 // since it will give us the behavior of a TruncOrSelf in the case where 8548 // its parameter <= its size. We previously set Result to be at least the 8549 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 8550 // will work exactly like TruncOrSelf. 8551 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 8552 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 8553 8554 if (!APSInt::isSameValue(Temp, Result)) 8555 DidOverflow = true; 8556 Result = Temp; 8557 } 8558 8559 APValue APV{Result}; 8560 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 8561 return false; 8562 return Success(DidOverflow, E); 8563 } 8564 } 8565 } 8566 8567 /// Determine whether this is a pointer past the end of the complete 8568 /// object referred to by the lvalue. 8569 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 8570 const LValue &LV) { 8571 // A null pointer can be viewed as being "past the end" but we don't 8572 // choose to look at it that way here. 8573 if (!LV.getLValueBase()) 8574 return false; 8575 8576 // If the designator is valid and refers to a subobject, we're not pointing 8577 // past the end. 8578 if (!LV.getLValueDesignator().Invalid && 8579 !LV.getLValueDesignator().isOnePastTheEnd()) 8580 return false; 8581 8582 // A pointer to an incomplete type might be past-the-end if the type's size is 8583 // zero. We cannot tell because the type is incomplete. 8584 QualType Ty = getType(LV.getLValueBase()); 8585 if (Ty->isIncompleteType()) 8586 return true; 8587 8588 // We're a past-the-end pointer if we point to the byte after the object, 8589 // no matter what our type or path is. 8590 auto Size = Ctx.getTypeSizeInChars(Ty); 8591 return LV.getLValueOffset() == Size; 8592 } 8593 8594 namespace { 8595 8596 /// Data recursive integer evaluator of certain binary operators. 8597 /// 8598 /// We use a data recursive algorithm for binary operators so that we are able 8599 /// to handle extreme cases of chained binary operators without causing stack 8600 /// overflow. 8601 class DataRecursiveIntBinOpEvaluator { 8602 struct EvalResult { 8603 APValue Val; 8604 bool Failed; 8605 8606 EvalResult() : Failed(false) { } 8607 8608 void swap(EvalResult &RHS) { 8609 Val.swap(RHS.Val); 8610 Failed = RHS.Failed; 8611 RHS.Failed = false; 8612 } 8613 }; 8614 8615 struct Job { 8616 const Expr *E; 8617 EvalResult LHSResult; // meaningful only for binary operator expression. 8618 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 8619 8620 Job() = default; 8621 Job(Job &&) = default; 8622 8623 void startSpeculativeEval(EvalInfo &Info) { 8624 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 8625 } 8626 8627 private: 8628 SpeculativeEvaluationRAII SpecEvalRAII; 8629 }; 8630 8631 SmallVector<Job, 16> Queue; 8632 8633 IntExprEvaluator &IntEval; 8634 EvalInfo &Info; 8635 APValue &FinalResult; 8636 8637 public: 8638 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 8639 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 8640 8641 /// True if \param E is a binary operator that we are going to handle 8642 /// data recursively. 8643 /// We handle binary operators that are comma, logical, or that have operands 8644 /// with integral or enumeration type. 8645 static bool shouldEnqueue(const BinaryOperator *E) { 8646 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 8647 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 8648 E->getLHS()->getType()->isIntegralOrEnumerationType() && 8649 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8650 } 8651 8652 bool Traverse(const BinaryOperator *E) { 8653 enqueue(E); 8654 EvalResult PrevResult; 8655 while (!Queue.empty()) 8656 process(PrevResult); 8657 8658 if (PrevResult.Failed) return false; 8659 8660 FinalResult.swap(PrevResult.Val); 8661 return true; 8662 } 8663 8664 private: 8665 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 8666 return IntEval.Success(Value, E, Result); 8667 } 8668 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 8669 return IntEval.Success(Value, E, Result); 8670 } 8671 bool Error(const Expr *E) { 8672 return IntEval.Error(E); 8673 } 8674 bool Error(const Expr *E, diag::kind D) { 8675 return IntEval.Error(E, D); 8676 } 8677 8678 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 8679 return Info.CCEDiag(E, D); 8680 } 8681 8682 // Returns true if visiting the RHS is necessary, false otherwise. 8683 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8684 bool &SuppressRHSDiags); 8685 8686 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8687 const BinaryOperator *E, APValue &Result); 8688 8689 void EvaluateExpr(const Expr *E, EvalResult &Result) { 8690 Result.Failed = !Evaluate(Result.Val, Info, E); 8691 if (Result.Failed) 8692 Result.Val = APValue(); 8693 } 8694 8695 void process(EvalResult &Result); 8696 8697 void enqueue(const Expr *E) { 8698 E = E->IgnoreParens(); 8699 Queue.resize(Queue.size()+1); 8700 Queue.back().E = E; 8701 Queue.back().Kind = Job::AnyExprKind; 8702 } 8703 }; 8704 8705 } 8706 8707 bool DataRecursiveIntBinOpEvaluator:: 8708 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 8709 bool &SuppressRHSDiags) { 8710 if (E->getOpcode() == BO_Comma) { 8711 // Ignore LHS but note if we could not evaluate it. 8712 if (LHSResult.Failed) 8713 return Info.noteSideEffect(); 8714 return true; 8715 } 8716 8717 if (E->isLogicalOp()) { 8718 bool LHSAsBool; 8719 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 8720 // We were able to evaluate the LHS, see if we can get away with not 8721 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 8722 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 8723 Success(LHSAsBool, E, LHSResult.Val); 8724 return false; // Ignore RHS 8725 } 8726 } else { 8727 LHSResult.Failed = true; 8728 8729 // Since we weren't able to evaluate the left hand side, it 8730 // might have had side effects. 8731 if (!Info.noteSideEffect()) 8732 return false; 8733 8734 // We can't evaluate the LHS; however, sometimes the result 8735 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8736 // Don't ignore RHS and suppress diagnostics from this arm. 8737 SuppressRHSDiags = true; 8738 } 8739 8740 return true; 8741 } 8742 8743 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8744 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8745 8746 if (LHSResult.Failed && !Info.noteFailure()) 8747 return false; // Ignore RHS; 8748 8749 return true; 8750 } 8751 8752 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 8753 bool IsSub) { 8754 // Compute the new offset in the appropriate width, wrapping at 64 bits. 8755 // FIXME: When compiling for a 32-bit target, we should use 32-bit 8756 // offsets. 8757 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 8758 CharUnits &Offset = LVal.getLValueOffset(); 8759 uint64_t Offset64 = Offset.getQuantity(); 8760 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 8761 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 8762 : Offset64 + Index64); 8763 } 8764 8765 bool DataRecursiveIntBinOpEvaluator:: 8766 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 8767 const BinaryOperator *E, APValue &Result) { 8768 if (E->getOpcode() == BO_Comma) { 8769 if (RHSResult.Failed) 8770 return false; 8771 Result = RHSResult.Val; 8772 return true; 8773 } 8774 8775 if (E->isLogicalOp()) { 8776 bool lhsResult, rhsResult; 8777 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 8778 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 8779 8780 if (LHSIsOK) { 8781 if (RHSIsOK) { 8782 if (E->getOpcode() == BO_LOr) 8783 return Success(lhsResult || rhsResult, E, Result); 8784 else 8785 return Success(lhsResult && rhsResult, E, Result); 8786 } 8787 } else { 8788 if (RHSIsOK) { 8789 // We can't evaluate the LHS; however, sometimes the result 8790 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 8791 if (rhsResult == (E->getOpcode() == BO_LOr)) 8792 return Success(rhsResult, E, Result); 8793 } 8794 } 8795 8796 return false; 8797 } 8798 8799 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 8800 E->getRHS()->getType()->isIntegralOrEnumerationType()); 8801 8802 if (LHSResult.Failed || RHSResult.Failed) 8803 return false; 8804 8805 const APValue &LHSVal = LHSResult.Val; 8806 const APValue &RHSVal = RHSResult.Val; 8807 8808 // Handle cases like (unsigned long)&a + 4. 8809 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 8810 Result = LHSVal; 8811 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 8812 return true; 8813 } 8814 8815 // Handle cases like 4 + (unsigned long)&a 8816 if (E->getOpcode() == BO_Add && 8817 RHSVal.isLValue() && LHSVal.isInt()) { 8818 Result = RHSVal; 8819 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 8820 return true; 8821 } 8822 8823 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 8824 // Handle (intptr_t)&&A - (intptr_t)&&B. 8825 if (!LHSVal.getLValueOffset().isZero() || 8826 !RHSVal.getLValueOffset().isZero()) 8827 return false; 8828 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 8829 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 8830 if (!LHSExpr || !RHSExpr) 8831 return false; 8832 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 8833 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 8834 if (!LHSAddrExpr || !RHSAddrExpr) 8835 return false; 8836 // Make sure both labels come from the same function. 8837 if (LHSAddrExpr->getLabel()->getDeclContext() != 8838 RHSAddrExpr->getLabel()->getDeclContext()) 8839 return false; 8840 Result = APValue(LHSAddrExpr, RHSAddrExpr); 8841 return true; 8842 } 8843 8844 // All the remaining cases expect both operands to be an integer 8845 if (!LHSVal.isInt() || !RHSVal.isInt()) 8846 return Error(E); 8847 8848 // Set up the width and signedness manually, in case it can't be deduced 8849 // from the operation we're performing. 8850 // FIXME: Don't do this in the cases where we can deduce it. 8851 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 8852 E->getType()->isUnsignedIntegerOrEnumerationType()); 8853 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 8854 RHSVal.getInt(), Value)) 8855 return false; 8856 return Success(Value, E, Result); 8857 } 8858 8859 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 8860 Job &job = Queue.back(); 8861 8862 switch (job.Kind) { 8863 case Job::AnyExprKind: { 8864 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 8865 if (shouldEnqueue(Bop)) { 8866 job.Kind = Job::BinOpKind; 8867 enqueue(Bop->getLHS()); 8868 return; 8869 } 8870 } 8871 8872 EvaluateExpr(job.E, Result); 8873 Queue.pop_back(); 8874 return; 8875 } 8876 8877 case Job::BinOpKind: { 8878 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8879 bool SuppressRHSDiags = false; 8880 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 8881 Queue.pop_back(); 8882 return; 8883 } 8884 if (SuppressRHSDiags) 8885 job.startSpeculativeEval(Info); 8886 job.LHSResult.swap(Result); 8887 job.Kind = Job::BinOpVisitedLHSKind; 8888 enqueue(Bop->getRHS()); 8889 return; 8890 } 8891 8892 case Job::BinOpVisitedLHSKind: { 8893 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 8894 EvalResult RHS; 8895 RHS.swap(Result); 8896 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 8897 Queue.pop_back(); 8898 return; 8899 } 8900 } 8901 8902 llvm_unreachable("Invalid Job::Kind!"); 8903 } 8904 8905 namespace { 8906 /// Used when we determine that we should fail, but can keep evaluating prior to 8907 /// noting that we had a failure. 8908 class DelayedNoteFailureRAII { 8909 EvalInfo &Info; 8910 bool NoteFailure; 8911 8912 public: 8913 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 8914 : Info(Info), NoteFailure(NoteFailure) {} 8915 ~DelayedNoteFailureRAII() { 8916 if (NoteFailure) { 8917 bool ContinueAfterFailure = Info.noteFailure(); 8918 (void)ContinueAfterFailure; 8919 assert(ContinueAfterFailure && 8920 "Shouldn't have kept evaluating on failure."); 8921 } 8922 } 8923 }; 8924 } 8925 8926 template <class SuccessCB, class AfterCB> 8927 static bool 8928 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 8929 SuccessCB &&Success, AfterCB &&DoAfter) { 8930 assert(E->isComparisonOp() && "expected comparison operator"); 8931 assert((E->getOpcode() == BO_Cmp || 8932 E->getType()->isIntegralOrEnumerationType()) && 8933 "unsupported binary expression evaluation"); 8934 auto Error = [&](const Expr *E) { 8935 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 8936 return false; 8937 }; 8938 8939 using CCR = ComparisonCategoryResult; 8940 bool IsRelational = E->isRelationalOp(); 8941 bool IsEquality = E->isEqualityOp(); 8942 if (E->getOpcode() == BO_Cmp) { 8943 const ComparisonCategoryInfo &CmpInfo = 8944 Info.Ctx.CompCategories.getInfoForType(E->getType()); 8945 IsRelational = CmpInfo.isOrdered(); 8946 IsEquality = CmpInfo.isEquality(); 8947 } 8948 8949 QualType LHSTy = E->getLHS()->getType(); 8950 QualType RHSTy = E->getRHS()->getType(); 8951 8952 if (LHSTy->isIntegralOrEnumerationType() && 8953 RHSTy->isIntegralOrEnumerationType()) { 8954 APSInt LHS, RHS; 8955 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 8956 if (!LHSOK && !Info.noteFailure()) 8957 return false; 8958 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 8959 return false; 8960 if (LHS < RHS) 8961 return Success(CCR::Less, E); 8962 if (LHS > RHS) 8963 return Success(CCR::Greater, E); 8964 return Success(CCR::Equal, E); 8965 } 8966 8967 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 8968 ComplexValue LHS, RHS; 8969 bool LHSOK; 8970 if (E->isAssignmentOp()) { 8971 LValue LV; 8972 EvaluateLValue(E->getLHS(), LV, Info); 8973 LHSOK = false; 8974 } else if (LHSTy->isRealFloatingType()) { 8975 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 8976 if (LHSOK) { 8977 LHS.makeComplexFloat(); 8978 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 8979 } 8980 } else { 8981 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 8982 } 8983 if (!LHSOK && !Info.noteFailure()) 8984 return false; 8985 8986 if (E->getRHS()->getType()->isRealFloatingType()) { 8987 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 8988 return false; 8989 RHS.makeComplexFloat(); 8990 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 8991 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 8992 return false; 8993 8994 if (LHS.isComplexFloat()) { 8995 APFloat::cmpResult CR_r = 8996 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 8997 APFloat::cmpResult CR_i = 8998 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 8999 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 9000 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 9001 } else { 9002 assert(IsEquality && "invalid complex comparison"); 9003 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 9004 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 9005 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 9006 } 9007 } 9008 9009 if (LHSTy->isRealFloatingType() && 9010 RHSTy->isRealFloatingType()) { 9011 APFloat RHS(0.0), LHS(0.0); 9012 9013 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 9014 if (!LHSOK && !Info.noteFailure()) 9015 return false; 9016 9017 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 9018 return false; 9019 9020 assert(E->isComparisonOp() && "Invalid binary operator!"); 9021 auto GetCmpRes = [&]() { 9022 switch (LHS.compare(RHS)) { 9023 case APFloat::cmpEqual: 9024 return CCR::Equal; 9025 case APFloat::cmpLessThan: 9026 return CCR::Less; 9027 case APFloat::cmpGreaterThan: 9028 return CCR::Greater; 9029 case APFloat::cmpUnordered: 9030 return CCR::Unordered; 9031 } 9032 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 9033 }; 9034 return Success(GetCmpRes(), E); 9035 } 9036 9037 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 9038 LValue LHSValue, RHSValue; 9039 9040 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 9041 if (!LHSOK && !Info.noteFailure()) 9042 return false; 9043 9044 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9045 return false; 9046 9047 // Reject differing bases from the normal codepath; we special-case 9048 // comparisons to null. 9049 if (!HasSameBase(LHSValue, RHSValue)) { 9050 // Inequalities and subtractions between unrelated pointers have 9051 // unspecified or undefined behavior. 9052 if (!IsEquality) 9053 return Error(E); 9054 // A constant address may compare equal to the address of a symbol. 9055 // The one exception is that address of an object cannot compare equal 9056 // to a null pointer constant. 9057 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 9058 (!RHSValue.Base && !RHSValue.Offset.isZero())) 9059 return Error(E); 9060 // It's implementation-defined whether distinct literals will have 9061 // distinct addresses. In clang, the result of such a comparison is 9062 // unspecified, so it is not a constant expression. However, we do know 9063 // that the address of a literal will be non-null. 9064 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 9065 LHSValue.Base && RHSValue.Base) 9066 return Error(E); 9067 // We can't tell whether weak symbols will end up pointing to the same 9068 // object. 9069 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 9070 return Error(E); 9071 // We can't compare the address of the start of one object with the 9072 // past-the-end address of another object, per C++ DR1652. 9073 if ((LHSValue.Base && LHSValue.Offset.isZero() && 9074 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 9075 (RHSValue.Base && RHSValue.Offset.isZero() && 9076 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 9077 return Error(E); 9078 // We can't tell whether an object is at the same address as another 9079 // zero sized object. 9080 if ((RHSValue.Base && isZeroSized(LHSValue)) || 9081 (LHSValue.Base && isZeroSized(RHSValue))) 9082 return Error(E); 9083 return Success(CCR::Nonequal, E); 9084 } 9085 9086 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 9087 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 9088 9089 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 9090 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 9091 9092 // C++11 [expr.rel]p3: 9093 // Pointers to void (after pointer conversions) can be compared, with a 9094 // result defined as follows: If both pointers represent the same 9095 // address or are both the null pointer value, the result is true if the 9096 // operator is <= or >= and false otherwise; otherwise the result is 9097 // unspecified. 9098 // We interpret this as applying to pointers to *cv* void. 9099 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 9100 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 9101 9102 // C++11 [expr.rel]p2: 9103 // - If two pointers point to non-static data members of the same object, 9104 // or to subobjects or array elements fo such members, recursively, the 9105 // pointer to the later declared member compares greater provided the 9106 // two members have the same access control and provided their class is 9107 // not a union. 9108 // [...] 9109 // - Otherwise pointer comparisons are unspecified. 9110 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 9111 bool WasArrayIndex; 9112 unsigned Mismatch = FindDesignatorMismatch( 9113 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 9114 // At the point where the designators diverge, the comparison has a 9115 // specified value if: 9116 // - we are comparing array indices 9117 // - we are comparing fields of a union, or fields with the same access 9118 // Otherwise, the result is unspecified and thus the comparison is not a 9119 // constant expression. 9120 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 9121 Mismatch < RHSDesignator.Entries.size()) { 9122 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 9123 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 9124 if (!LF && !RF) 9125 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 9126 else if (!LF) 9127 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 9128 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 9129 << RF->getParent() << RF; 9130 else if (!RF) 9131 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 9132 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 9133 << LF->getParent() << LF; 9134 else if (!LF->getParent()->isUnion() && 9135 LF->getAccess() != RF->getAccess()) 9136 Info.CCEDiag(E, 9137 diag::note_constexpr_pointer_comparison_differing_access) 9138 << LF << LF->getAccess() << RF << RF->getAccess() 9139 << LF->getParent(); 9140 } 9141 } 9142 9143 // The comparison here must be unsigned, and performed with the same 9144 // width as the pointer. 9145 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 9146 uint64_t CompareLHS = LHSOffset.getQuantity(); 9147 uint64_t CompareRHS = RHSOffset.getQuantity(); 9148 assert(PtrSize <= 64 && "Unexpected pointer width"); 9149 uint64_t Mask = ~0ULL >> (64 - PtrSize); 9150 CompareLHS &= Mask; 9151 CompareRHS &= Mask; 9152 9153 // If there is a base and this is a relational operator, we can only 9154 // compare pointers within the object in question; otherwise, the result 9155 // depends on where the object is located in memory. 9156 if (!LHSValue.Base.isNull() && IsRelational) { 9157 QualType BaseTy = getType(LHSValue.Base); 9158 if (BaseTy->isIncompleteType()) 9159 return Error(E); 9160 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 9161 uint64_t OffsetLimit = Size.getQuantity(); 9162 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 9163 return Error(E); 9164 } 9165 9166 if (CompareLHS < CompareRHS) 9167 return Success(CCR::Less, E); 9168 if (CompareLHS > CompareRHS) 9169 return Success(CCR::Greater, E); 9170 return Success(CCR::Equal, E); 9171 } 9172 9173 if (LHSTy->isMemberPointerType()) { 9174 assert(IsEquality && "unexpected member pointer operation"); 9175 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 9176 9177 MemberPtr LHSValue, RHSValue; 9178 9179 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 9180 if (!LHSOK && !Info.noteFailure()) 9181 return false; 9182 9183 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9184 return false; 9185 9186 // C++11 [expr.eq]p2: 9187 // If both operands are null, they compare equal. Otherwise if only one is 9188 // null, they compare unequal. 9189 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 9190 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 9191 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 9192 } 9193 9194 // Otherwise if either is a pointer to a virtual member function, the 9195 // result is unspecified. 9196 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 9197 if (MD->isVirtual()) 9198 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 9199 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 9200 if (MD->isVirtual()) 9201 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 9202 9203 // Otherwise they compare equal if and only if they would refer to the 9204 // same member of the same most derived object or the same subobject if 9205 // they were dereferenced with a hypothetical object of the associated 9206 // class type. 9207 bool Equal = LHSValue == RHSValue; 9208 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 9209 } 9210 9211 if (LHSTy->isNullPtrType()) { 9212 assert(E->isComparisonOp() && "unexpected nullptr operation"); 9213 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 9214 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 9215 // are compared, the result is true of the operator is <=, >= or ==, and 9216 // false otherwise. 9217 return Success(CCR::Equal, E); 9218 } 9219 9220 return DoAfter(); 9221 } 9222 9223 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 9224 if (!CheckLiteralType(Info, E)) 9225 return false; 9226 9227 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 9228 const BinaryOperator *E) { 9229 // Evaluation succeeded. Lookup the information for the comparison category 9230 // type and fetch the VarDecl for the result. 9231 const ComparisonCategoryInfo &CmpInfo = 9232 Info.Ctx.CompCategories.getInfoForType(E->getType()); 9233 const VarDecl *VD = 9234 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; 9235 // Check and evaluate the result as a constant expression. 9236 LValue LV; 9237 LV.set(VD); 9238 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 9239 return false; 9240 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 9241 }; 9242 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 9243 return ExprEvaluatorBaseTy::VisitBinCmp(E); 9244 }); 9245 } 9246 9247 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9248 // We don't call noteFailure immediately because the assignment happens after 9249 // we evaluate LHS and RHS. 9250 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 9251 return Error(E); 9252 9253 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 9254 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 9255 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 9256 9257 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 9258 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 9259 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 9260 9261 if (E->isComparisonOp()) { 9262 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way 9263 // comparisons and then translating the result. 9264 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 9265 const BinaryOperator *E) { 9266 using CCR = ComparisonCategoryResult; 9267 bool IsEqual = ResKind == CCR::Equal, 9268 IsLess = ResKind == CCR::Less, 9269 IsGreater = ResKind == CCR::Greater; 9270 auto Op = E->getOpcode(); 9271 switch (Op) { 9272 default: 9273 llvm_unreachable("unsupported binary operator"); 9274 case BO_EQ: 9275 case BO_NE: 9276 return Success(IsEqual == (Op == BO_EQ), E); 9277 case BO_LT: return Success(IsLess, E); 9278 case BO_GT: return Success(IsGreater, E); 9279 case BO_LE: return Success(IsEqual || IsLess, E); 9280 case BO_GE: return Success(IsEqual || IsGreater, E); 9281 } 9282 }; 9283 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 9284 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9285 }); 9286 } 9287 9288 QualType LHSTy = E->getLHS()->getType(); 9289 QualType RHSTy = E->getRHS()->getType(); 9290 9291 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 9292 E->getOpcode() == BO_Sub) { 9293 LValue LHSValue, RHSValue; 9294 9295 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 9296 if (!LHSOK && !Info.noteFailure()) 9297 return false; 9298 9299 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 9300 return false; 9301 9302 // Reject differing bases from the normal codepath; we special-case 9303 // comparisons to null. 9304 if (!HasSameBase(LHSValue, RHSValue)) { 9305 // Handle &&A - &&B. 9306 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 9307 return Error(E); 9308 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 9309 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 9310 if (!LHSExpr || !RHSExpr) 9311 return Error(E); 9312 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 9313 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 9314 if (!LHSAddrExpr || !RHSAddrExpr) 9315 return Error(E); 9316 // Make sure both labels come from the same function. 9317 if (LHSAddrExpr->getLabel()->getDeclContext() != 9318 RHSAddrExpr->getLabel()->getDeclContext()) 9319 return Error(E); 9320 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 9321 } 9322 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 9323 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 9324 9325 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 9326 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 9327 9328 // C++11 [expr.add]p6: 9329 // Unless both pointers point to elements of the same array object, or 9330 // one past the last element of the array object, the behavior is 9331 // undefined. 9332 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 9333 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 9334 RHSDesignator)) 9335 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 9336 9337 QualType Type = E->getLHS()->getType(); 9338 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 9339 9340 CharUnits ElementSize; 9341 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 9342 return false; 9343 9344 // As an extension, a type may have zero size (empty struct or union in 9345 // C, array of zero length). Pointer subtraction in such cases has 9346 // undefined behavior, so is not constant. 9347 if (ElementSize.isZero()) { 9348 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 9349 << ElementType; 9350 return false; 9351 } 9352 9353 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 9354 // and produce incorrect results when it overflows. Such behavior 9355 // appears to be non-conforming, but is common, so perhaps we should 9356 // assume the standard intended for such cases to be undefined behavior 9357 // and check for them. 9358 9359 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 9360 // overflow in the final conversion to ptrdiff_t. 9361 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 9362 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 9363 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 9364 false); 9365 APSInt TrueResult = (LHS - RHS) / ElemSize; 9366 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 9367 9368 if (Result.extend(65) != TrueResult && 9369 !HandleOverflow(Info, E, TrueResult, E->getType())) 9370 return false; 9371 return Success(Result, E); 9372 } 9373 9374 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9375 } 9376 9377 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 9378 /// a result as the expression's type. 9379 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 9380 const UnaryExprOrTypeTraitExpr *E) { 9381 switch(E->getKind()) { 9382 case UETT_PreferredAlignOf: 9383 case UETT_AlignOf: { 9384 if (E->isArgumentType()) 9385 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 9386 E); 9387 else 9388 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 9389 E); 9390 } 9391 9392 case UETT_VecStep: { 9393 QualType Ty = E->getTypeOfArgument(); 9394 9395 if (Ty->isVectorType()) { 9396 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 9397 9398 // The vec_step built-in functions that take a 3-component 9399 // vector return 4. (OpenCL 1.1 spec 6.11.12) 9400 if (n == 3) 9401 n = 4; 9402 9403 return Success(n, E); 9404 } else 9405 return Success(1, E); 9406 } 9407 9408 case UETT_SizeOf: { 9409 QualType SrcTy = E->getTypeOfArgument(); 9410 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 9411 // the result is the size of the referenced type." 9412 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 9413 SrcTy = Ref->getPointeeType(); 9414 9415 CharUnits Sizeof; 9416 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 9417 return false; 9418 return Success(Sizeof, E); 9419 } 9420 case UETT_OpenMPRequiredSimdAlign: 9421 assert(E->isArgumentType()); 9422 return Success( 9423 Info.Ctx.toCharUnitsFromBits( 9424 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 9425 .getQuantity(), 9426 E); 9427 } 9428 9429 llvm_unreachable("unknown expr/type trait"); 9430 } 9431 9432 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 9433 CharUnits Result; 9434 unsigned n = OOE->getNumComponents(); 9435 if (n == 0) 9436 return Error(OOE); 9437 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 9438 for (unsigned i = 0; i != n; ++i) { 9439 OffsetOfNode ON = OOE->getComponent(i); 9440 switch (ON.getKind()) { 9441 case OffsetOfNode::Array: { 9442 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 9443 APSInt IdxResult; 9444 if (!EvaluateInteger(Idx, IdxResult, Info)) 9445 return false; 9446 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 9447 if (!AT) 9448 return Error(OOE); 9449 CurrentType = AT->getElementType(); 9450 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 9451 Result += IdxResult.getSExtValue() * ElementSize; 9452 break; 9453 } 9454 9455 case OffsetOfNode::Field: { 9456 FieldDecl *MemberDecl = ON.getField(); 9457 const RecordType *RT = CurrentType->getAs<RecordType>(); 9458 if (!RT) 9459 return Error(OOE); 9460 RecordDecl *RD = RT->getDecl(); 9461 if (RD->isInvalidDecl()) return false; 9462 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 9463 unsigned i = MemberDecl->getFieldIndex(); 9464 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 9465 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 9466 CurrentType = MemberDecl->getType().getNonReferenceType(); 9467 break; 9468 } 9469 9470 case OffsetOfNode::Identifier: 9471 llvm_unreachable("dependent __builtin_offsetof"); 9472 9473 case OffsetOfNode::Base: { 9474 CXXBaseSpecifier *BaseSpec = ON.getBase(); 9475 if (BaseSpec->isVirtual()) 9476 return Error(OOE); 9477 9478 // Find the layout of the class whose base we are looking into. 9479 const RecordType *RT = CurrentType->getAs<RecordType>(); 9480 if (!RT) 9481 return Error(OOE); 9482 RecordDecl *RD = RT->getDecl(); 9483 if (RD->isInvalidDecl()) return false; 9484 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 9485 9486 // Find the base class itself. 9487 CurrentType = BaseSpec->getType(); 9488 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 9489 if (!BaseRT) 9490 return Error(OOE); 9491 9492 // Add the offset to the base. 9493 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 9494 break; 9495 } 9496 } 9497 } 9498 return Success(Result, OOE); 9499 } 9500 9501 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9502 switch (E->getOpcode()) { 9503 default: 9504 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 9505 // See C99 6.6p3. 9506 return Error(E); 9507 case UO_Extension: 9508 // FIXME: Should extension allow i-c-e extension expressions in its scope? 9509 // If so, we could clear the diagnostic ID. 9510 return Visit(E->getSubExpr()); 9511 case UO_Plus: 9512 // The result is just the value. 9513 return Visit(E->getSubExpr()); 9514 case UO_Minus: { 9515 if (!Visit(E->getSubExpr())) 9516 return false; 9517 if (!Result.isInt()) return Error(E); 9518 const APSInt &Value = Result.getInt(); 9519 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 9520 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 9521 E->getType())) 9522 return false; 9523 return Success(-Value, E); 9524 } 9525 case UO_Not: { 9526 if (!Visit(E->getSubExpr())) 9527 return false; 9528 if (!Result.isInt()) return Error(E); 9529 return Success(~Result.getInt(), E); 9530 } 9531 case UO_LNot: { 9532 bool bres; 9533 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 9534 return false; 9535 return Success(!bres, E); 9536 } 9537 } 9538 } 9539 9540 /// HandleCast - This is used to evaluate implicit or explicit casts where the 9541 /// result type is integer. 9542 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 9543 const Expr *SubExpr = E->getSubExpr(); 9544 QualType DestType = E->getType(); 9545 QualType SrcType = SubExpr->getType(); 9546 9547 switch (E->getCastKind()) { 9548 case CK_BaseToDerived: 9549 case CK_DerivedToBase: 9550 case CK_UncheckedDerivedToBase: 9551 case CK_Dynamic: 9552 case CK_ToUnion: 9553 case CK_ArrayToPointerDecay: 9554 case CK_FunctionToPointerDecay: 9555 case CK_NullToPointer: 9556 case CK_NullToMemberPointer: 9557 case CK_BaseToDerivedMemberPointer: 9558 case CK_DerivedToBaseMemberPointer: 9559 case CK_ReinterpretMemberPointer: 9560 case CK_ConstructorConversion: 9561 case CK_IntegralToPointer: 9562 case CK_ToVoid: 9563 case CK_VectorSplat: 9564 case CK_IntegralToFloating: 9565 case CK_FloatingCast: 9566 case CK_CPointerToObjCPointerCast: 9567 case CK_BlockPointerToObjCPointerCast: 9568 case CK_AnyPointerToBlockPointerCast: 9569 case CK_ObjCObjectLValueCast: 9570 case CK_FloatingRealToComplex: 9571 case CK_FloatingComplexToReal: 9572 case CK_FloatingComplexCast: 9573 case CK_FloatingComplexToIntegralComplex: 9574 case CK_IntegralRealToComplex: 9575 case CK_IntegralComplexCast: 9576 case CK_IntegralComplexToFloatingComplex: 9577 case CK_BuiltinFnToFnPtr: 9578 case CK_ZeroToOCLOpaqueType: 9579 case CK_NonAtomicToAtomic: 9580 case CK_AddressSpaceConversion: 9581 case CK_IntToOCLSampler: 9582 case CK_FixedPointCast: 9583 llvm_unreachable("invalid cast kind for integral value"); 9584 9585 case CK_BitCast: 9586 case CK_Dependent: 9587 case CK_LValueBitCast: 9588 case CK_ARCProduceObject: 9589 case CK_ARCConsumeObject: 9590 case CK_ARCReclaimReturnedObject: 9591 case CK_ARCExtendBlockObject: 9592 case CK_CopyAndAutoreleaseBlockObject: 9593 return Error(E); 9594 9595 case CK_UserDefinedConversion: 9596 case CK_LValueToRValue: 9597 case CK_AtomicToNonAtomic: 9598 case CK_NoOp: 9599 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9600 9601 case CK_MemberPointerToBoolean: 9602 case CK_PointerToBoolean: 9603 case CK_IntegralToBoolean: 9604 case CK_FloatingToBoolean: 9605 case CK_BooleanToSignedIntegral: 9606 case CK_FloatingComplexToBoolean: 9607 case CK_IntegralComplexToBoolean: { 9608 bool BoolResult; 9609 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 9610 return false; 9611 uint64_t IntResult = BoolResult; 9612 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 9613 IntResult = (uint64_t)-1; 9614 return Success(IntResult, E); 9615 } 9616 9617 case CK_FixedPointToBoolean: { 9618 // Unsigned padding does not affect this. 9619 APValue Val; 9620 if (!Evaluate(Val, Info, SubExpr)) 9621 return false; 9622 return Success(Val.getInt().getBoolValue(), E); 9623 } 9624 9625 case CK_IntegralCast: { 9626 if (!Visit(SubExpr)) 9627 return false; 9628 9629 if (!Result.isInt()) { 9630 // Allow casts of address-of-label differences if they are no-ops 9631 // or narrowing. (The narrowing case isn't actually guaranteed to 9632 // be constant-evaluatable except in some narrow cases which are hard 9633 // to detect here. We let it through on the assumption the user knows 9634 // what they are doing.) 9635 if (Result.isAddrLabelDiff()) 9636 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 9637 // Only allow casts of lvalues if they are lossless. 9638 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 9639 } 9640 9641 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 9642 Result.getInt()), E); 9643 } 9644 9645 case CK_PointerToIntegral: { 9646 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 9647 9648 LValue LV; 9649 if (!EvaluatePointer(SubExpr, LV, Info)) 9650 return false; 9651 9652 if (LV.getLValueBase()) { 9653 // Only allow based lvalue casts if they are lossless. 9654 // FIXME: Allow a larger integer size than the pointer size, and allow 9655 // narrowing back down to pointer width in subsequent integral casts. 9656 // FIXME: Check integer type's active bits, not its type size. 9657 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 9658 return Error(E); 9659 9660 LV.Designator.setInvalid(); 9661 LV.moveInto(Result); 9662 return true; 9663 } 9664 9665 uint64_t V; 9666 if (LV.isNullPointer()) 9667 V = Info.Ctx.getTargetNullPointerValue(SrcType); 9668 else 9669 V = LV.getLValueOffset().getQuantity(); 9670 9671 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType); 9672 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 9673 } 9674 9675 case CK_IntegralComplexToReal: { 9676 ComplexValue C; 9677 if (!EvaluateComplex(SubExpr, C, Info)) 9678 return false; 9679 return Success(C.getComplexIntReal(), E); 9680 } 9681 9682 case CK_FloatingToIntegral: { 9683 APFloat F(0.0); 9684 if (!EvaluateFloat(SubExpr, F, Info)) 9685 return false; 9686 9687 APSInt Value; 9688 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 9689 return false; 9690 return Success(Value, E); 9691 } 9692 } 9693 9694 llvm_unreachable("unknown cast resulting in integral value"); 9695 } 9696 9697 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9698 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9699 ComplexValue LV; 9700 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9701 return false; 9702 if (!LV.isComplexInt()) 9703 return Error(E); 9704 return Success(LV.getComplexIntReal(), E); 9705 } 9706 9707 return Visit(E->getSubExpr()); 9708 } 9709 9710 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9711 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 9712 ComplexValue LV; 9713 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 9714 return false; 9715 if (!LV.isComplexInt()) 9716 return Error(E); 9717 return Success(LV.getComplexIntImag(), E); 9718 } 9719 9720 VisitIgnoredValue(E->getSubExpr()); 9721 return Success(0, E); 9722 } 9723 9724 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 9725 return Success(E->getPackLength(), E); 9726 } 9727 9728 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 9729 return Success(E->getValue(), E); 9730 } 9731 9732 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9733 switch (E->getOpcode()) { 9734 default: 9735 // Invalid unary operators 9736 return Error(E); 9737 case UO_Plus: 9738 // The result is just the value. 9739 return Visit(E->getSubExpr()); 9740 case UO_Minus: { 9741 if (!Visit(E->getSubExpr())) return false; 9742 if (!Result.isInt()) return Error(E); 9743 const APSInt &Value = Result.getInt(); 9744 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) { 9745 SmallString<64> S; 9746 FixedPointValueToString(S, Value, 9747 Info.Ctx.getTypeInfo(E->getType()).Width); 9748 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType(); 9749 if (Info.noteUndefinedBehavior()) return false; 9750 } 9751 return Success(-Value, E); 9752 } 9753 case UO_LNot: { 9754 bool bres; 9755 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 9756 return false; 9757 return Success(!bres, E); 9758 } 9759 } 9760 } 9761 9762 //===----------------------------------------------------------------------===// 9763 // Float Evaluation 9764 //===----------------------------------------------------------------------===// 9765 9766 namespace { 9767 class FloatExprEvaluator 9768 : public ExprEvaluatorBase<FloatExprEvaluator> { 9769 APFloat &Result; 9770 public: 9771 FloatExprEvaluator(EvalInfo &info, APFloat &result) 9772 : ExprEvaluatorBaseTy(info), Result(result) {} 9773 9774 bool Success(const APValue &V, const Expr *e) { 9775 Result = V.getFloat(); 9776 return true; 9777 } 9778 9779 bool ZeroInitialization(const Expr *E) { 9780 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 9781 return true; 9782 } 9783 9784 bool VisitCallExpr(const CallExpr *E); 9785 9786 bool VisitUnaryOperator(const UnaryOperator *E); 9787 bool VisitBinaryOperator(const BinaryOperator *E); 9788 bool VisitFloatingLiteral(const FloatingLiteral *E); 9789 bool VisitCastExpr(const CastExpr *E); 9790 9791 bool VisitUnaryReal(const UnaryOperator *E); 9792 bool VisitUnaryImag(const UnaryOperator *E); 9793 9794 // FIXME: Missing: array subscript of vector, member of vector 9795 }; 9796 } // end anonymous namespace 9797 9798 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 9799 assert(E->isRValue() && E->getType()->isRealFloatingType()); 9800 return FloatExprEvaluator(Info, Result).Visit(E); 9801 } 9802 9803 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 9804 QualType ResultTy, 9805 const Expr *Arg, 9806 bool SNaN, 9807 llvm::APFloat &Result) { 9808 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 9809 if (!S) return false; 9810 9811 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 9812 9813 llvm::APInt fill; 9814 9815 // Treat empty strings as if they were zero. 9816 if (S->getString().empty()) 9817 fill = llvm::APInt(32, 0); 9818 else if (S->getString().getAsInteger(0, fill)) 9819 return false; 9820 9821 if (Context.getTargetInfo().isNan2008()) { 9822 if (SNaN) 9823 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9824 else 9825 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9826 } else { 9827 // Prior to IEEE 754-2008, architectures were allowed to choose whether 9828 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 9829 // a different encoding to what became a standard in 2008, and for pre- 9830 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 9831 // sNaN. This is now known as "legacy NaN" encoding. 9832 if (SNaN) 9833 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 9834 else 9835 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 9836 } 9837 9838 return true; 9839 } 9840 9841 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 9842 switch (E->getBuiltinCallee()) { 9843 default: 9844 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9845 9846 case Builtin::BI__builtin_huge_val: 9847 case Builtin::BI__builtin_huge_valf: 9848 case Builtin::BI__builtin_huge_vall: 9849 case Builtin::BI__builtin_huge_valf128: 9850 case Builtin::BI__builtin_inf: 9851 case Builtin::BI__builtin_inff: 9852 case Builtin::BI__builtin_infl: 9853 case Builtin::BI__builtin_inff128: { 9854 const llvm::fltSemantics &Sem = 9855 Info.Ctx.getFloatTypeSemantics(E->getType()); 9856 Result = llvm::APFloat::getInf(Sem); 9857 return true; 9858 } 9859 9860 case Builtin::BI__builtin_nans: 9861 case Builtin::BI__builtin_nansf: 9862 case Builtin::BI__builtin_nansl: 9863 case Builtin::BI__builtin_nansf128: 9864 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9865 true, Result)) 9866 return Error(E); 9867 return true; 9868 9869 case Builtin::BI__builtin_nan: 9870 case Builtin::BI__builtin_nanf: 9871 case Builtin::BI__builtin_nanl: 9872 case Builtin::BI__builtin_nanf128: 9873 // If this is __builtin_nan() turn this into a nan, otherwise we 9874 // can't constant fold it. 9875 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 9876 false, Result)) 9877 return Error(E); 9878 return true; 9879 9880 case Builtin::BI__builtin_fabs: 9881 case Builtin::BI__builtin_fabsf: 9882 case Builtin::BI__builtin_fabsl: 9883 case Builtin::BI__builtin_fabsf128: 9884 if (!EvaluateFloat(E->getArg(0), Result, Info)) 9885 return false; 9886 9887 if (Result.isNegative()) 9888 Result.changeSign(); 9889 return true; 9890 9891 // FIXME: Builtin::BI__builtin_powi 9892 // FIXME: Builtin::BI__builtin_powif 9893 // FIXME: Builtin::BI__builtin_powil 9894 9895 case Builtin::BI__builtin_copysign: 9896 case Builtin::BI__builtin_copysignf: 9897 case Builtin::BI__builtin_copysignl: 9898 case Builtin::BI__builtin_copysignf128: { 9899 APFloat RHS(0.); 9900 if (!EvaluateFloat(E->getArg(0), Result, Info) || 9901 !EvaluateFloat(E->getArg(1), RHS, Info)) 9902 return false; 9903 Result.copySign(RHS); 9904 return true; 9905 } 9906 } 9907 } 9908 9909 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 9910 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9911 ComplexValue CV; 9912 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9913 return false; 9914 Result = CV.FloatReal; 9915 return true; 9916 } 9917 9918 return Visit(E->getSubExpr()); 9919 } 9920 9921 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9922 if (E->getSubExpr()->getType()->isAnyComplexType()) { 9923 ComplexValue CV; 9924 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 9925 return false; 9926 Result = CV.FloatImag; 9927 return true; 9928 } 9929 9930 VisitIgnoredValue(E->getSubExpr()); 9931 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 9932 Result = llvm::APFloat::getZero(Sem); 9933 return true; 9934 } 9935 9936 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 9937 switch (E->getOpcode()) { 9938 default: return Error(E); 9939 case UO_Plus: 9940 return EvaluateFloat(E->getSubExpr(), Result, Info); 9941 case UO_Minus: 9942 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 9943 return false; 9944 Result.changeSign(); 9945 return true; 9946 } 9947 } 9948 9949 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 9950 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 9951 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 9952 9953 APFloat RHS(0.0); 9954 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 9955 if (!LHSOK && !Info.noteFailure()) 9956 return false; 9957 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 9958 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 9959 } 9960 9961 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 9962 Result = E->getValue(); 9963 return true; 9964 } 9965 9966 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 9967 const Expr* SubExpr = E->getSubExpr(); 9968 9969 switch (E->getCastKind()) { 9970 default: 9971 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9972 9973 case CK_IntegralToFloating: { 9974 APSInt IntResult; 9975 return EvaluateInteger(SubExpr, IntResult, Info) && 9976 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 9977 E->getType(), Result); 9978 } 9979 9980 case CK_FloatingCast: { 9981 if (!Visit(SubExpr)) 9982 return false; 9983 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 9984 Result); 9985 } 9986 9987 case CK_FloatingComplexToReal: { 9988 ComplexValue V; 9989 if (!EvaluateComplex(SubExpr, V, Info)) 9990 return false; 9991 Result = V.getComplexFloatReal(); 9992 return true; 9993 } 9994 } 9995 } 9996 9997 //===----------------------------------------------------------------------===// 9998 // Complex Evaluation (for float and integer) 9999 //===----------------------------------------------------------------------===// 10000 10001 namespace { 10002 class ComplexExprEvaluator 10003 : public ExprEvaluatorBase<ComplexExprEvaluator> { 10004 ComplexValue &Result; 10005 10006 public: 10007 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 10008 : ExprEvaluatorBaseTy(info), Result(Result) {} 10009 10010 bool Success(const APValue &V, const Expr *e) { 10011 Result.setFrom(V); 10012 return true; 10013 } 10014 10015 bool ZeroInitialization(const Expr *E); 10016 10017 //===--------------------------------------------------------------------===// 10018 // Visitor Methods 10019 //===--------------------------------------------------------------------===// 10020 10021 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 10022 bool VisitCastExpr(const CastExpr *E); 10023 bool VisitBinaryOperator(const BinaryOperator *E); 10024 bool VisitUnaryOperator(const UnaryOperator *E); 10025 bool VisitInitListExpr(const InitListExpr *E); 10026 }; 10027 } // end anonymous namespace 10028 10029 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 10030 EvalInfo &Info) { 10031 assert(E->isRValue() && E->getType()->isAnyComplexType()); 10032 return ComplexExprEvaluator(Info, Result).Visit(E); 10033 } 10034 10035 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 10036 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 10037 if (ElemTy->isRealFloatingType()) { 10038 Result.makeComplexFloat(); 10039 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 10040 Result.FloatReal = Zero; 10041 Result.FloatImag = Zero; 10042 } else { 10043 Result.makeComplexInt(); 10044 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 10045 Result.IntReal = Zero; 10046 Result.IntImag = Zero; 10047 } 10048 return true; 10049 } 10050 10051 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 10052 const Expr* SubExpr = E->getSubExpr(); 10053 10054 if (SubExpr->getType()->isRealFloatingType()) { 10055 Result.makeComplexFloat(); 10056 APFloat &Imag = Result.FloatImag; 10057 if (!EvaluateFloat(SubExpr, Imag, Info)) 10058 return false; 10059 10060 Result.FloatReal = APFloat(Imag.getSemantics()); 10061 return true; 10062 } else { 10063 assert(SubExpr->getType()->isIntegerType() && 10064 "Unexpected imaginary literal."); 10065 10066 Result.makeComplexInt(); 10067 APSInt &Imag = Result.IntImag; 10068 if (!EvaluateInteger(SubExpr, Imag, Info)) 10069 return false; 10070 10071 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 10072 return true; 10073 } 10074 } 10075 10076 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 10077 10078 switch (E->getCastKind()) { 10079 case CK_BitCast: 10080 case CK_BaseToDerived: 10081 case CK_DerivedToBase: 10082 case CK_UncheckedDerivedToBase: 10083 case CK_Dynamic: 10084 case CK_ToUnion: 10085 case CK_ArrayToPointerDecay: 10086 case CK_FunctionToPointerDecay: 10087 case CK_NullToPointer: 10088 case CK_NullToMemberPointer: 10089 case CK_BaseToDerivedMemberPointer: 10090 case CK_DerivedToBaseMemberPointer: 10091 case CK_MemberPointerToBoolean: 10092 case CK_ReinterpretMemberPointer: 10093 case CK_ConstructorConversion: 10094 case CK_IntegralToPointer: 10095 case CK_PointerToIntegral: 10096 case CK_PointerToBoolean: 10097 case CK_ToVoid: 10098 case CK_VectorSplat: 10099 case CK_IntegralCast: 10100 case CK_BooleanToSignedIntegral: 10101 case CK_IntegralToBoolean: 10102 case CK_IntegralToFloating: 10103 case CK_FloatingToIntegral: 10104 case CK_FloatingToBoolean: 10105 case CK_FloatingCast: 10106 case CK_CPointerToObjCPointerCast: 10107 case CK_BlockPointerToObjCPointerCast: 10108 case CK_AnyPointerToBlockPointerCast: 10109 case CK_ObjCObjectLValueCast: 10110 case CK_FloatingComplexToReal: 10111 case CK_FloatingComplexToBoolean: 10112 case CK_IntegralComplexToReal: 10113 case CK_IntegralComplexToBoolean: 10114 case CK_ARCProduceObject: 10115 case CK_ARCConsumeObject: 10116 case CK_ARCReclaimReturnedObject: 10117 case CK_ARCExtendBlockObject: 10118 case CK_CopyAndAutoreleaseBlockObject: 10119 case CK_BuiltinFnToFnPtr: 10120 case CK_ZeroToOCLOpaqueType: 10121 case CK_NonAtomicToAtomic: 10122 case CK_AddressSpaceConversion: 10123 case CK_IntToOCLSampler: 10124 case CK_FixedPointCast: 10125 case CK_FixedPointToBoolean: 10126 llvm_unreachable("invalid cast kind for complex value"); 10127 10128 case CK_LValueToRValue: 10129 case CK_AtomicToNonAtomic: 10130 case CK_NoOp: 10131 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10132 10133 case CK_Dependent: 10134 case CK_LValueBitCast: 10135 case CK_UserDefinedConversion: 10136 return Error(E); 10137 10138 case CK_FloatingRealToComplex: { 10139 APFloat &Real = Result.FloatReal; 10140 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 10141 return false; 10142 10143 Result.makeComplexFloat(); 10144 Result.FloatImag = APFloat(Real.getSemantics()); 10145 return true; 10146 } 10147 10148 case CK_FloatingComplexCast: { 10149 if (!Visit(E->getSubExpr())) 10150 return false; 10151 10152 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10153 QualType From 10154 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10155 10156 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 10157 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 10158 } 10159 10160 case CK_FloatingComplexToIntegralComplex: { 10161 if (!Visit(E->getSubExpr())) 10162 return false; 10163 10164 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10165 QualType From 10166 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10167 Result.makeComplexInt(); 10168 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 10169 To, Result.IntReal) && 10170 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 10171 To, Result.IntImag); 10172 } 10173 10174 case CK_IntegralRealToComplex: { 10175 APSInt &Real = Result.IntReal; 10176 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 10177 return false; 10178 10179 Result.makeComplexInt(); 10180 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 10181 return true; 10182 } 10183 10184 case CK_IntegralComplexCast: { 10185 if (!Visit(E->getSubExpr())) 10186 return false; 10187 10188 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 10189 QualType From 10190 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 10191 10192 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 10193 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 10194 return true; 10195 } 10196 10197 case CK_IntegralComplexToFloatingComplex: { 10198 if (!Visit(E->getSubExpr())) 10199 return false; 10200 10201 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 10202 QualType From 10203 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 10204 Result.makeComplexFloat(); 10205 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 10206 To, Result.FloatReal) && 10207 HandleIntToFloatCast(Info, E, From, Result.IntImag, 10208 To, Result.FloatImag); 10209 } 10210 } 10211 10212 llvm_unreachable("unknown cast resulting in complex value"); 10213 } 10214 10215 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10216 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 10217 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10218 10219 // Track whether the LHS or RHS is real at the type system level. When this is 10220 // the case we can simplify our evaluation strategy. 10221 bool LHSReal = false, RHSReal = false; 10222 10223 bool LHSOK; 10224 if (E->getLHS()->getType()->isRealFloatingType()) { 10225 LHSReal = true; 10226 APFloat &Real = Result.FloatReal; 10227 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 10228 if (LHSOK) { 10229 Result.makeComplexFloat(); 10230 Result.FloatImag = APFloat(Real.getSemantics()); 10231 } 10232 } else { 10233 LHSOK = Visit(E->getLHS()); 10234 } 10235 if (!LHSOK && !Info.noteFailure()) 10236 return false; 10237 10238 ComplexValue RHS; 10239 if (E->getRHS()->getType()->isRealFloatingType()) { 10240 RHSReal = true; 10241 APFloat &Real = RHS.FloatReal; 10242 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 10243 return false; 10244 RHS.makeComplexFloat(); 10245 RHS.FloatImag = APFloat(Real.getSemantics()); 10246 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 10247 return false; 10248 10249 assert(!(LHSReal && RHSReal) && 10250 "Cannot have both operands of a complex operation be real."); 10251 switch (E->getOpcode()) { 10252 default: return Error(E); 10253 case BO_Add: 10254 if (Result.isComplexFloat()) { 10255 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 10256 APFloat::rmNearestTiesToEven); 10257 if (LHSReal) 10258 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 10259 else if (!RHSReal) 10260 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 10261 APFloat::rmNearestTiesToEven); 10262 } else { 10263 Result.getComplexIntReal() += RHS.getComplexIntReal(); 10264 Result.getComplexIntImag() += RHS.getComplexIntImag(); 10265 } 10266 break; 10267 case BO_Sub: 10268 if (Result.isComplexFloat()) { 10269 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 10270 APFloat::rmNearestTiesToEven); 10271 if (LHSReal) { 10272 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 10273 Result.getComplexFloatImag().changeSign(); 10274 } else if (!RHSReal) { 10275 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 10276 APFloat::rmNearestTiesToEven); 10277 } 10278 } else { 10279 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 10280 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 10281 } 10282 break; 10283 case BO_Mul: 10284 if (Result.isComplexFloat()) { 10285 // This is an implementation of complex multiplication according to the 10286 // constraints laid out in C11 Annex G. The implemention uses the 10287 // following naming scheme: 10288 // (a + ib) * (c + id) 10289 ComplexValue LHS = Result; 10290 APFloat &A = LHS.getComplexFloatReal(); 10291 APFloat &B = LHS.getComplexFloatImag(); 10292 APFloat &C = RHS.getComplexFloatReal(); 10293 APFloat &D = RHS.getComplexFloatImag(); 10294 APFloat &ResR = Result.getComplexFloatReal(); 10295 APFloat &ResI = Result.getComplexFloatImag(); 10296 if (LHSReal) { 10297 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 10298 ResR = A * C; 10299 ResI = A * D; 10300 } else if (RHSReal) { 10301 ResR = C * A; 10302 ResI = C * B; 10303 } else { 10304 // In the fully general case, we need to handle NaNs and infinities 10305 // robustly. 10306 APFloat AC = A * C; 10307 APFloat BD = B * D; 10308 APFloat AD = A * D; 10309 APFloat BC = B * C; 10310 ResR = AC - BD; 10311 ResI = AD + BC; 10312 if (ResR.isNaN() && ResI.isNaN()) { 10313 bool Recalc = false; 10314 if (A.isInfinity() || B.isInfinity()) { 10315 A = APFloat::copySign( 10316 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 10317 B = APFloat::copySign( 10318 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 10319 if (C.isNaN()) 10320 C = APFloat::copySign(APFloat(C.getSemantics()), C); 10321 if (D.isNaN()) 10322 D = APFloat::copySign(APFloat(D.getSemantics()), D); 10323 Recalc = true; 10324 } 10325 if (C.isInfinity() || D.isInfinity()) { 10326 C = APFloat::copySign( 10327 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 10328 D = APFloat::copySign( 10329 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 10330 if (A.isNaN()) 10331 A = APFloat::copySign(APFloat(A.getSemantics()), A); 10332 if (B.isNaN()) 10333 B = APFloat::copySign(APFloat(B.getSemantics()), B); 10334 Recalc = true; 10335 } 10336 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 10337 AD.isInfinity() || BC.isInfinity())) { 10338 if (A.isNaN()) 10339 A = APFloat::copySign(APFloat(A.getSemantics()), A); 10340 if (B.isNaN()) 10341 B = APFloat::copySign(APFloat(B.getSemantics()), B); 10342 if (C.isNaN()) 10343 C = APFloat::copySign(APFloat(C.getSemantics()), C); 10344 if (D.isNaN()) 10345 D = APFloat::copySign(APFloat(D.getSemantics()), D); 10346 Recalc = true; 10347 } 10348 if (Recalc) { 10349 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 10350 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 10351 } 10352 } 10353 } 10354 } else { 10355 ComplexValue LHS = Result; 10356 Result.getComplexIntReal() = 10357 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 10358 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 10359 Result.getComplexIntImag() = 10360 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 10361 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 10362 } 10363 break; 10364 case BO_Div: 10365 if (Result.isComplexFloat()) { 10366 // This is an implementation of complex division according to the 10367 // constraints laid out in C11 Annex G. The implemention uses the 10368 // following naming scheme: 10369 // (a + ib) / (c + id) 10370 ComplexValue LHS = Result; 10371 APFloat &A = LHS.getComplexFloatReal(); 10372 APFloat &B = LHS.getComplexFloatImag(); 10373 APFloat &C = RHS.getComplexFloatReal(); 10374 APFloat &D = RHS.getComplexFloatImag(); 10375 APFloat &ResR = Result.getComplexFloatReal(); 10376 APFloat &ResI = Result.getComplexFloatImag(); 10377 if (RHSReal) { 10378 ResR = A / C; 10379 ResI = B / C; 10380 } else { 10381 if (LHSReal) { 10382 // No real optimizations we can do here, stub out with zero. 10383 B = APFloat::getZero(A.getSemantics()); 10384 } 10385 int DenomLogB = 0; 10386 APFloat MaxCD = maxnum(abs(C), abs(D)); 10387 if (MaxCD.isFinite()) { 10388 DenomLogB = ilogb(MaxCD); 10389 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 10390 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 10391 } 10392 APFloat Denom = C * C + D * D; 10393 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 10394 APFloat::rmNearestTiesToEven); 10395 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 10396 APFloat::rmNearestTiesToEven); 10397 if (ResR.isNaN() && ResI.isNaN()) { 10398 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 10399 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 10400 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 10401 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 10402 D.isFinite()) { 10403 A = APFloat::copySign( 10404 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 10405 B = APFloat::copySign( 10406 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 10407 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 10408 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 10409 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 10410 C = APFloat::copySign( 10411 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 10412 D = APFloat::copySign( 10413 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 10414 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 10415 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 10416 } 10417 } 10418 } 10419 } else { 10420 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 10421 return Error(E, diag::note_expr_divide_by_zero); 10422 10423 ComplexValue LHS = Result; 10424 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 10425 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 10426 Result.getComplexIntReal() = 10427 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 10428 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 10429 Result.getComplexIntImag() = 10430 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 10431 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 10432 } 10433 break; 10434 } 10435 10436 return true; 10437 } 10438 10439 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10440 // Get the operand value into 'Result'. 10441 if (!Visit(E->getSubExpr())) 10442 return false; 10443 10444 switch (E->getOpcode()) { 10445 default: 10446 return Error(E); 10447 case UO_Extension: 10448 return true; 10449 case UO_Plus: 10450 // The result is always just the subexpr. 10451 return true; 10452 case UO_Minus: 10453 if (Result.isComplexFloat()) { 10454 Result.getComplexFloatReal().changeSign(); 10455 Result.getComplexFloatImag().changeSign(); 10456 } 10457 else { 10458 Result.getComplexIntReal() = -Result.getComplexIntReal(); 10459 Result.getComplexIntImag() = -Result.getComplexIntImag(); 10460 } 10461 return true; 10462 case UO_Not: 10463 if (Result.isComplexFloat()) 10464 Result.getComplexFloatImag().changeSign(); 10465 else 10466 Result.getComplexIntImag() = -Result.getComplexIntImag(); 10467 return true; 10468 } 10469 } 10470 10471 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 10472 if (E->getNumInits() == 2) { 10473 if (E->getType()->isComplexType()) { 10474 Result.makeComplexFloat(); 10475 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 10476 return false; 10477 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 10478 return false; 10479 } else { 10480 Result.makeComplexInt(); 10481 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 10482 return false; 10483 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 10484 return false; 10485 } 10486 return true; 10487 } 10488 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 10489 } 10490 10491 //===----------------------------------------------------------------------===// 10492 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 10493 // implicit conversion. 10494 //===----------------------------------------------------------------------===// 10495 10496 namespace { 10497 class AtomicExprEvaluator : 10498 public ExprEvaluatorBase<AtomicExprEvaluator> { 10499 const LValue *This; 10500 APValue &Result; 10501 public: 10502 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 10503 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 10504 10505 bool Success(const APValue &V, const Expr *E) { 10506 Result = V; 10507 return true; 10508 } 10509 10510 bool ZeroInitialization(const Expr *E) { 10511 ImplicitValueInitExpr VIE( 10512 E->getType()->castAs<AtomicType>()->getValueType()); 10513 // For atomic-qualified class (and array) types in C++, initialize the 10514 // _Atomic-wrapped subobject directly, in-place. 10515 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 10516 : Evaluate(Result, Info, &VIE); 10517 } 10518 10519 bool VisitCastExpr(const CastExpr *E) { 10520 switch (E->getCastKind()) { 10521 default: 10522 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10523 case CK_NonAtomicToAtomic: 10524 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 10525 : Evaluate(Result, Info, E->getSubExpr()); 10526 } 10527 } 10528 }; 10529 } // end anonymous namespace 10530 10531 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 10532 EvalInfo &Info) { 10533 assert(E->isRValue() && E->getType()->isAtomicType()); 10534 return AtomicExprEvaluator(Info, This, Result).Visit(E); 10535 } 10536 10537 //===----------------------------------------------------------------------===// 10538 // Void expression evaluation, primarily for a cast to void on the LHS of a 10539 // comma operator 10540 //===----------------------------------------------------------------------===// 10541 10542 namespace { 10543 class VoidExprEvaluator 10544 : public ExprEvaluatorBase<VoidExprEvaluator> { 10545 public: 10546 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 10547 10548 bool Success(const APValue &V, const Expr *e) { return true; } 10549 10550 bool ZeroInitialization(const Expr *E) { return true; } 10551 10552 bool VisitCastExpr(const CastExpr *E) { 10553 switch (E->getCastKind()) { 10554 default: 10555 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10556 case CK_ToVoid: 10557 VisitIgnoredValue(E->getSubExpr()); 10558 return true; 10559 } 10560 } 10561 10562 bool VisitCallExpr(const CallExpr *E) { 10563 switch (E->getBuiltinCallee()) { 10564 default: 10565 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10566 case Builtin::BI__assume: 10567 case Builtin::BI__builtin_assume: 10568 // The argument is not evaluated! 10569 return true; 10570 } 10571 } 10572 }; 10573 } // end anonymous namespace 10574 10575 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 10576 assert(E->isRValue() && E->getType()->isVoidType()); 10577 return VoidExprEvaluator(Info).Visit(E); 10578 } 10579 10580 //===----------------------------------------------------------------------===// 10581 // Top level Expr::EvaluateAsRValue method. 10582 //===----------------------------------------------------------------------===// 10583 10584 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 10585 // In C, function designators are not lvalues, but we evaluate them as if they 10586 // are. 10587 QualType T = E->getType(); 10588 if (E->isGLValue() || T->isFunctionType()) { 10589 LValue LV; 10590 if (!EvaluateLValue(E, LV, Info)) 10591 return false; 10592 LV.moveInto(Result); 10593 } else if (T->isVectorType()) { 10594 if (!EvaluateVector(E, Result, Info)) 10595 return false; 10596 } else if (T->isIntegralOrEnumerationType()) { 10597 if (!IntExprEvaluator(Info, Result).Visit(E)) 10598 return false; 10599 } else if (T->hasPointerRepresentation()) { 10600 LValue LV; 10601 if (!EvaluatePointer(E, LV, Info)) 10602 return false; 10603 LV.moveInto(Result); 10604 } else if (T->isRealFloatingType()) { 10605 llvm::APFloat F(0.0); 10606 if (!EvaluateFloat(E, F, Info)) 10607 return false; 10608 Result = APValue(F); 10609 } else if (T->isAnyComplexType()) { 10610 ComplexValue C; 10611 if (!EvaluateComplex(E, C, Info)) 10612 return false; 10613 C.moveInto(Result); 10614 } else if (T->isFixedPointType()) { 10615 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 10616 } else if (T->isMemberPointerType()) { 10617 MemberPtr P; 10618 if (!EvaluateMemberPointer(E, P, Info)) 10619 return false; 10620 P.moveInto(Result); 10621 return true; 10622 } else if (T->isArrayType()) { 10623 LValue LV; 10624 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10625 if (!EvaluateArray(E, LV, Value, Info)) 10626 return false; 10627 Result = Value; 10628 } else if (T->isRecordType()) { 10629 LValue LV; 10630 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10631 if (!EvaluateRecord(E, LV, Value, Info)) 10632 return false; 10633 Result = Value; 10634 } else if (T->isVoidType()) { 10635 if (!Info.getLangOpts().CPlusPlus11) 10636 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 10637 << E->getType(); 10638 if (!EvaluateVoid(E, Info)) 10639 return false; 10640 } else if (T->isAtomicType()) { 10641 QualType Unqual = T.getAtomicUnqualifiedType(); 10642 if (Unqual->isArrayType() || Unqual->isRecordType()) { 10643 LValue LV; 10644 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 10645 if (!EvaluateAtomic(E, &LV, Value, Info)) 10646 return false; 10647 } else { 10648 if (!EvaluateAtomic(E, nullptr, Result, Info)) 10649 return false; 10650 } 10651 } else if (Info.getLangOpts().CPlusPlus11) { 10652 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 10653 return false; 10654 } else { 10655 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10656 return false; 10657 } 10658 10659 return true; 10660 } 10661 10662 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 10663 /// cases, the in-place evaluation is essential, since later initializers for 10664 /// an object can indirectly refer to subobjects which were initialized earlier. 10665 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 10666 const Expr *E, bool AllowNonLiteralTypes) { 10667 assert(!E->isValueDependent()); 10668 10669 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 10670 return false; 10671 10672 if (E->isRValue()) { 10673 // Evaluate arrays and record types in-place, so that later initializers can 10674 // refer to earlier-initialized members of the object. 10675 QualType T = E->getType(); 10676 if (T->isArrayType()) 10677 return EvaluateArray(E, This, Result, Info); 10678 else if (T->isRecordType()) 10679 return EvaluateRecord(E, This, Result, Info); 10680 else if (T->isAtomicType()) { 10681 QualType Unqual = T.getAtomicUnqualifiedType(); 10682 if (Unqual->isArrayType() || Unqual->isRecordType()) 10683 return EvaluateAtomic(E, &This, Result, Info); 10684 } 10685 } 10686 10687 // For any other type, in-place evaluation is unimportant. 10688 return Evaluate(Result, Info, E); 10689 } 10690 10691 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 10692 /// lvalue-to-rvalue cast if it is an lvalue. 10693 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 10694 if (E->getType().isNull()) 10695 return false; 10696 10697 if (!CheckLiteralType(Info, E)) 10698 return false; 10699 10700 if (!::Evaluate(Result, Info, E)) 10701 return false; 10702 10703 if (E->isGLValue()) { 10704 LValue LV; 10705 LV.setFrom(Info.Ctx, Result); 10706 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 10707 return false; 10708 } 10709 10710 // Check this core constant expression is a constant expression. 10711 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 10712 } 10713 10714 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 10715 const ASTContext &Ctx, bool &IsConst) { 10716 // Fast-path evaluations of integer literals, since we sometimes see files 10717 // containing vast quantities of these. 10718 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 10719 Result.Val = APValue(APSInt(L->getValue(), 10720 L->getType()->isUnsignedIntegerType())); 10721 IsConst = true; 10722 return true; 10723 } 10724 10725 // This case should be rare, but we need to check it before we check on 10726 // the type below. 10727 if (Exp->getType().isNull()) { 10728 IsConst = false; 10729 return true; 10730 } 10731 10732 // FIXME: Evaluating values of large array and record types can cause 10733 // performance problems. Only do so in C++11 for now. 10734 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 10735 Exp->getType()->isRecordType()) && 10736 !Ctx.getLangOpts().CPlusPlus11) { 10737 IsConst = false; 10738 return true; 10739 } 10740 return false; 10741 } 10742 10743 10744 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 10745 /// any crazy technique (that has nothing to do with language standards) that 10746 /// we want to. If this function returns true, it returns the folded constant 10747 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 10748 /// will be applied to the result. 10749 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const { 10750 bool IsConst; 10751 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst)) 10752 return IsConst; 10753 10754 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 10755 return ::EvaluateAsRValue(Info, this, Result.Val); 10756 } 10757 10758 bool Expr::EvaluateAsBooleanCondition(bool &Result, 10759 const ASTContext &Ctx) const { 10760 EvalResult Scratch; 10761 return EvaluateAsRValue(Scratch, Ctx) && 10762 HandleConversionToBool(Scratch.Val, Result); 10763 } 10764 10765 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 10766 Expr::SideEffectsKind SEK) { 10767 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 10768 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 10769 } 10770 10771 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx, 10772 SideEffectsKind AllowSideEffects) const { 10773 if (!getType()->isIntegralOrEnumerationType()) 10774 return false; 10775 10776 EvalResult ExprResult; 10777 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() || 10778 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10779 return false; 10780 10781 Result = ExprResult.Val.getInt(); 10782 return true; 10783 } 10784 10785 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 10786 SideEffectsKind AllowSideEffects) const { 10787 if (!getType()->isRealFloatingType()) 10788 return false; 10789 10790 EvalResult ExprResult; 10791 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() || 10792 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 10793 return false; 10794 10795 Result = ExprResult.Val.getFloat(); 10796 return true; 10797 } 10798 10799 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 10800 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 10801 10802 LValue LV; 10803 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 10804 !CheckLValueConstantExpression(Info, getExprLoc(), 10805 Ctx.getLValueReferenceType(getType()), LV, 10806 Expr::EvaluateForCodeGen)) 10807 return false; 10808 10809 LV.moveInto(Result.Val); 10810 return true; 10811 } 10812 10813 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 10814 const ASTContext &Ctx) const { 10815 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 10816 EvalInfo Info(Ctx, Result, EM); 10817 if (!::Evaluate(Result.Val, Info, this)) 10818 return false; 10819 10820 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val, 10821 Usage); 10822 } 10823 10824 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 10825 const VarDecl *VD, 10826 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 10827 // FIXME: Evaluating initializers for large array and record types can cause 10828 // performance problems. Only do so in C++11 for now. 10829 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 10830 !Ctx.getLangOpts().CPlusPlus11) 10831 return false; 10832 10833 Expr::EvalStatus EStatus; 10834 EStatus.Diag = &Notes; 10835 10836 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr() 10837 ? EvalInfo::EM_ConstantExpression 10838 : EvalInfo::EM_ConstantFold); 10839 InitInfo.setEvaluatingDecl(VD, Value); 10840 10841 LValue LVal; 10842 LVal.set(VD); 10843 10844 // C++11 [basic.start.init]p2: 10845 // Variables with static storage duration or thread storage duration shall be 10846 // zero-initialized before any other initialization takes place. 10847 // This behavior is not present in C. 10848 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 10849 !VD->getType()->isReferenceType()) { 10850 ImplicitValueInitExpr VIE(VD->getType()); 10851 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, 10852 /*AllowNonLiteralTypes=*/true)) 10853 return false; 10854 } 10855 10856 if (!EvaluateInPlace(Value, InitInfo, LVal, this, 10857 /*AllowNonLiteralTypes=*/true) || 10858 EStatus.HasSideEffects) 10859 return false; 10860 10861 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 10862 Value); 10863 } 10864 10865 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 10866 /// constant folded, but discard the result. 10867 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 10868 EvalResult Result; 10869 return EvaluateAsRValue(Result, Ctx) && 10870 !hasUnacceptableSideEffect(Result, SEK); 10871 } 10872 10873 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 10874 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 10875 EvalResult EvalResult; 10876 EvalResult.Diag = Diag; 10877 bool Result = EvaluateAsRValue(EvalResult, Ctx); 10878 (void)Result; 10879 assert(Result && "Could not evaluate expression"); 10880 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 10881 10882 return EvalResult.Val.getInt(); 10883 } 10884 10885 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 10886 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 10887 EvalResult EvalResult; 10888 EvalResult.Diag = Diag; 10889 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow); 10890 bool Result = ::EvaluateAsRValue(Info, this, EvalResult.Val); 10891 (void)Result; 10892 assert(Result && "Could not evaluate expression"); 10893 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer"); 10894 10895 return EvalResult.Val.getInt(); 10896 } 10897 10898 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 10899 bool IsConst; 10900 EvalResult EvalResult; 10901 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) { 10902 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow); 10903 (void)::EvaluateAsRValue(Info, this, EvalResult.Val); 10904 } 10905 } 10906 10907 bool Expr::EvalResult::isGlobalLValue() const { 10908 assert(Val.isLValue()); 10909 return IsGlobalLValue(Val.getLValueBase()); 10910 } 10911 10912 10913 /// isIntegerConstantExpr - this recursive routine will test if an expression is 10914 /// an integer constant expression. 10915 10916 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 10917 /// comma, etc 10918 10919 // CheckICE - This function does the fundamental ICE checking: the returned 10920 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 10921 // and a (possibly null) SourceLocation indicating the location of the problem. 10922 // 10923 // Note that to reduce code duplication, this helper does no evaluation 10924 // itself; the caller checks whether the expression is evaluatable, and 10925 // in the rare cases where CheckICE actually cares about the evaluated 10926 // value, it calls into Evaluate. 10927 10928 namespace { 10929 10930 enum ICEKind { 10931 /// This expression is an ICE. 10932 IK_ICE, 10933 /// This expression is not an ICE, but if it isn't evaluated, it's 10934 /// a legal subexpression for an ICE. This return value is used to handle 10935 /// the comma operator in C99 mode, and non-constant subexpressions. 10936 IK_ICEIfUnevaluated, 10937 /// This expression is not an ICE, and is not a legal subexpression for one. 10938 IK_NotICE 10939 }; 10940 10941 struct ICEDiag { 10942 ICEKind Kind; 10943 SourceLocation Loc; 10944 10945 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 10946 }; 10947 10948 } 10949 10950 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 10951 10952 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 10953 10954 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 10955 Expr::EvalResult EVResult; 10956 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects || 10957 !EVResult.Val.isInt()) 10958 return ICEDiag(IK_NotICE, E->getBeginLoc()); 10959 10960 return NoDiag(); 10961 } 10962 10963 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 10964 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 10965 if (!E->getType()->isIntegralOrEnumerationType()) 10966 return ICEDiag(IK_NotICE, E->getBeginLoc()); 10967 10968 switch (E->getStmtClass()) { 10969 #define ABSTRACT_STMT(Node) 10970 #define STMT(Node, Base) case Expr::Node##Class: 10971 #define EXPR(Node, Base) 10972 #include "clang/AST/StmtNodes.inc" 10973 case Expr::PredefinedExprClass: 10974 case Expr::FloatingLiteralClass: 10975 case Expr::ImaginaryLiteralClass: 10976 case Expr::StringLiteralClass: 10977 case Expr::ArraySubscriptExprClass: 10978 case Expr::OMPArraySectionExprClass: 10979 case Expr::MemberExprClass: 10980 case Expr::CompoundAssignOperatorClass: 10981 case Expr::CompoundLiteralExprClass: 10982 case Expr::ExtVectorElementExprClass: 10983 case Expr::DesignatedInitExprClass: 10984 case Expr::ArrayInitLoopExprClass: 10985 case Expr::ArrayInitIndexExprClass: 10986 case Expr::NoInitExprClass: 10987 case Expr::DesignatedInitUpdateExprClass: 10988 case Expr::ImplicitValueInitExprClass: 10989 case Expr::ParenListExprClass: 10990 case Expr::VAArgExprClass: 10991 case Expr::AddrLabelExprClass: 10992 case Expr::StmtExprClass: 10993 case Expr::CXXMemberCallExprClass: 10994 case Expr::CUDAKernelCallExprClass: 10995 case Expr::CXXDynamicCastExprClass: 10996 case Expr::CXXTypeidExprClass: 10997 case Expr::CXXUuidofExprClass: 10998 case Expr::MSPropertyRefExprClass: 10999 case Expr::MSPropertySubscriptExprClass: 11000 case Expr::CXXNullPtrLiteralExprClass: 11001 case Expr::UserDefinedLiteralClass: 11002 case Expr::CXXThisExprClass: 11003 case Expr::CXXThrowExprClass: 11004 case Expr::CXXNewExprClass: 11005 case Expr::CXXDeleteExprClass: 11006 case Expr::CXXPseudoDestructorExprClass: 11007 case Expr::UnresolvedLookupExprClass: 11008 case Expr::TypoExprClass: 11009 case Expr::DependentScopeDeclRefExprClass: 11010 case Expr::CXXConstructExprClass: 11011 case Expr::CXXInheritedCtorInitExprClass: 11012 case Expr::CXXStdInitializerListExprClass: 11013 case Expr::CXXBindTemporaryExprClass: 11014 case Expr::ExprWithCleanupsClass: 11015 case Expr::CXXTemporaryObjectExprClass: 11016 case Expr::CXXUnresolvedConstructExprClass: 11017 case Expr::CXXDependentScopeMemberExprClass: 11018 case Expr::UnresolvedMemberExprClass: 11019 case Expr::ObjCStringLiteralClass: 11020 case Expr::ObjCBoxedExprClass: 11021 case Expr::ObjCArrayLiteralClass: 11022 case Expr::ObjCDictionaryLiteralClass: 11023 case Expr::ObjCEncodeExprClass: 11024 case Expr::ObjCMessageExprClass: 11025 case Expr::ObjCSelectorExprClass: 11026 case Expr::ObjCProtocolExprClass: 11027 case Expr::ObjCIvarRefExprClass: 11028 case Expr::ObjCPropertyRefExprClass: 11029 case Expr::ObjCSubscriptRefExprClass: 11030 case Expr::ObjCIsaExprClass: 11031 case Expr::ObjCAvailabilityCheckExprClass: 11032 case Expr::ShuffleVectorExprClass: 11033 case Expr::ConvertVectorExprClass: 11034 case Expr::BlockExprClass: 11035 case Expr::NoStmtClass: 11036 case Expr::OpaqueValueExprClass: 11037 case Expr::PackExpansionExprClass: 11038 case Expr::SubstNonTypeTemplateParmPackExprClass: 11039 case Expr::FunctionParmPackExprClass: 11040 case Expr::AsTypeExprClass: 11041 case Expr::ObjCIndirectCopyRestoreExprClass: 11042 case Expr::MaterializeTemporaryExprClass: 11043 case Expr::PseudoObjectExprClass: 11044 case Expr::AtomicExprClass: 11045 case Expr::LambdaExprClass: 11046 case Expr::CXXFoldExprClass: 11047 case Expr::CoawaitExprClass: 11048 case Expr::DependentCoawaitExprClass: 11049 case Expr::CoyieldExprClass: 11050 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11051 11052 case Expr::InitListExprClass: { 11053 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 11054 // form "T x = { a };" is equivalent to "T x = a;". 11055 // Unless we're initializing a reference, T is a scalar as it is known to be 11056 // of integral or enumeration type. 11057 if (E->isRValue()) 11058 if (cast<InitListExpr>(E)->getNumInits() == 1) 11059 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 11060 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11061 } 11062 11063 case Expr::SizeOfPackExprClass: 11064 case Expr::GNUNullExprClass: 11065 // GCC considers the GNU __null value to be an integral constant expression. 11066 return NoDiag(); 11067 11068 case Expr::SubstNonTypeTemplateParmExprClass: 11069 return 11070 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 11071 11072 case Expr::ConstantExprClass: 11073 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 11074 11075 case Expr::ParenExprClass: 11076 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 11077 case Expr::GenericSelectionExprClass: 11078 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 11079 case Expr::IntegerLiteralClass: 11080 case Expr::FixedPointLiteralClass: 11081 case Expr::CharacterLiteralClass: 11082 case Expr::ObjCBoolLiteralExprClass: 11083 case Expr::CXXBoolLiteralExprClass: 11084 case Expr::CXXScalarValueInitExprClass: 11085 case Expr::TypeTraitExprClass: 11086 case Expr::ArrayTypeTraitExprClass: 11087 case Expr::ExpressionTraitExprClass: 11088 case Expr::CXXNoexceptExprClass: 11089 return NoDiag(); 11090 case Expr::CallExprClass: 11091 case Expr::CXXOperatorCallExprClass: { 11092 // C99 6.6/3 allows function calls within unevaluated subexpressions of 11093 // constant expressions, but they can never be ICEs because an ICE cannot 11094 // contain an operand of (pointer to) function type. 11095 const CallExpr *CE = cast<CallExpr>(E); 11096 if (CE->getBuiltinCallee()) 11097 return CheckEvalInICE(E, Ctx); 11098 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11099 } 11100 case Expr::DeclRefExprClass: { 11101 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 11102 return NoDiag(); 11103 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 11104 if (Ctx.getLangOpts().CPlusPlus && 11105 D && IsConstNonVolatile(D->getType())) { 11106 // Parameter variables are never constants. Without this check, 11107 // getAnyInitializer() can find a default argument, which leads 11108 // to chaos. 11109 if (isa<ParmVarDecl>(D)) 11110 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11111 11112 // C++ 7.1.5.1p2 11113 // A variable of non-volatile const-qualified integral or enumeration 11114 // type initialized by an ICE can be used in ICEs. 11115 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 11116 if (!Dcl->getType()->isIntegralOrEnumerationType()) 11117 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11118 11119 const VarDecl *VD; 11120 // Look for a declaration of this variable that has an initializer, and 11121 // check whether it is an ICE. 11122 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 11123 return NoDiag(); 11124 else 11125 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 11126 } 11127 } 11128 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11129 } 11130 case Expr::UnaryOperatorClass: { 11131 const UnaryOperator *Exp = cast<UnaryOperator>(E); 11132 switch (Exp->getOpcode()) { 11133 case UO_PostInc: 11134 case UO_PostDec: 11135 case UO_PreInc: 11136 case UO_PreDec: 11137 case UO_AddrOf: 11138 case UO_Deref: 11139 case UO_Coawait: 11140 // C99 6.6/3 allows increment and decrement within unevaluated 11141 // subexpressions of constant expressions, but they can never be ICEs 11142 // because an ICE cannot contain an lvalue operand. 11143 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11144 case UO_Extension: 11145 case UO_LNot: 11146 case UO_Plus: 11147 case UO_Minus: 11148 case UO_Not: 11149 case UO_Real: 11150 case UO_Imag: 11151 return CheckICE(Exp->getSubExpr(), Ctx); 11152 } 11153 llvm_unreachable("invalid unary operator class"); 11154 } 11155 case Expr::OffsetOfExprClass: { 11156 // Note that per C99, offsetof must be an ICE. And AFAIK, using 11157 // EvaluateAsRValue matches the proposed gcc behavior for cases like 11158 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 11159 // compliance: we should warn earlier for offsetof expressions with 11160 // array subscripts that aren't ICEs, and if the array subscripts 11161 // are ICEs, the value of the offsetof must be an integer constant. 11162 return CheckEvalInICE(E, Ctx); 11163 } 11164 case Expr::UnaryExprOrTypeTraitExprClass: { 11165 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 11166 if ((Exp->getKind() == UETT_SizeOf) && 11167 Exp->getTypeOfArgument()->isVariableArrayType()) 11168 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11169 return NoDiag(); 11170 } 11171 case Expr::BinaryOperatorClass: { 11172 const BinaryOperator *Exp = cast<BinaryOperator>(E); 11173 switch (Exp->getOpcode()) { 11174 case BO_PtrMemD: 11175 case BO_PtrMemI: 11176 case BO_Assign: 11177 case BO_MulAssign: 11178 case BO_DivAssign: 11179 case BO_RemAssign: 11180 case BO_AddAssign: 11181 case BO_SubAssign: 11182 case BO_ShlAssign: 11183 case BO_ShrAssign: 11184 case BO_AndAssign: 11185 case BO_XorAssign: 11186 case BO_OrAssign: 11187 // C99 6.6/3 allows assignments within unevaluated subexpressions of 11188 // constant expressions, but they can never be ICEs because an ICE cannot 11189 // contain an lvalue operand. 11190 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11191 11192 case BO_Mul: 11193 case BO_Div: 11194 case BO_Rem: 11195 case BO_Add: 11196 case BO_Sub: 11197 case BO_Shl: 11198 case BO_Shr: 11199 case BO_LT: 11200 case BO_GT: 11201 case BO_LE: 11202 case BO_GE: 11203 case BO_EQ: 11204 case BO_NE: 11205 case BO_And: 11206 case BO_Xor: 11207 case BO_Or: 11208 case BO_Comma: 11209 case BO_Cmp: { 11210 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 11211 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 11212 if (Exp->getOpcode() == BO_Div || 11213 Exp->getOpcode() == BO_Rem) { 11214 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 11215 // we don't evaluate one. 11216 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 11217 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 11218 if (REval == 0) 11219 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11220 if (REval.isSigned() && REval.isAllOnesValue()) { 11221 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 11222 if (LEval.isMinSignedValue()) 11223 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11224 } 11225 } 11226 } 11227 if (Exp->getOpcode() == BO_Comma) { 11228 if (Ctx.getLangOpts().C99) { 11229 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 11230 // if it isn't evaluated. 11231 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 11232 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 11233 } else { 11234 // In both C89 and C++, commas in ICEs are illegal. 11235 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11236 } 11237 } 11238 return Worst(LHSResult, RHSResult); 11239 } 11240 case BO_LAnd: 11241 case BO_LOr: { 11242 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 11243 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 11244 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 11245 // Rare case where the RHS has a comma "side-effect"; we need 11246 // to actually check the condition to see whether the side 11247 // with the comma is evaluated. 11248 if ((Exp->getOpcode() == BO_LAnd) != 11249 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 11250 return RHSResult; 11251 return NoDiag(); 11252 } 11253 11254 return Worst(LHSResult, RHSResult); 11255 } 11256 } 11257 llvm_unreachable("invalid binary operator kind"); 11258 } 11259 case Expr::ImplicitCastExprClass: 11260 case Expr::CStyleCastExprClass: 11261 case Expr::CXXFunctionalCastExprClass: 11262 case Expr::CXXStaticCastExprClass: 11263 case Expr::CXXReinterpretCastExprClass: 11264 case Expr::CXXConstCastExprClass: 11265 case Expr::ObjCBridgedCastExprClass: { 11266 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 11267 if (isa<ExplicitCastExpr>(E)) { 11268 if (const FloatingLiteral *FL 11269 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 11270 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 11271 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 11272 APSInt IgnoredVal(DestWidth, !DestSigned); 11273 bool Ignored; 11274 // If the value does not fit in the destination type, the behavior is 11275 // undefined, so we are not required to treat it as a constant 11276 // expression. 11277 if (FL->getValue().convertToInteger(IgnoredVal, 11278 llvm::APFloat::rmTowardZero, 11279 &Ignored) & APFloat::opInvalidOp) 11280 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11281 return NoDiag(); 11282 } 11283 } 11284 switch (cast<CastExpr>(E)->getCastKind()) { 11285 case CK_LValueToRValue: 11286 case CK_AtomicToNonAtomic: 11287 case CK_NonAtomicToAtomic: 11288 case CK_NoOp: 11289 case CK_IntegralToBoolean: 11290 case CK_IntegralCast: 11291 return CheckICE(SubExpr, Ctx); 11292 default: 11293 return ICEDiag(IK_NotICE, E->getBeginLoc()); 11294 } 11295 } 11296 case Expr::BinaryConditionalOperatorClass: { 11297 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 11298 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 11299 if (CommonResult.Kind == IK_NotICE) return CommonResult; 11300 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 11301 if (FalseResult.Kind == IK_NotICE) return FalseResult; 11302 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 11303 if (FalseResult.Kind == IK_ICEIfUnevaluated && 11304 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 11305 return FalseResult; 11306 } 11307 case Expr::ConditionalOperatorClass: { 11308 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 11309 // If the condition (ignoring parens) is a __builtin_constant_p call, 11310 // then only the true side is actually considered in an integer constant 11311 // expression, and it is fully evaluated. This is an important GNU 11312 // extension. See GCC PR38377 for discussion. 11313 if (const CallExpr *CallCE 11314 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 11315 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 11316 return CheckEvalInICE(E, Ctx); 11317 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 11318 if (CondResult.Kind == IK_NotICE) 11319 return CondResult; 11320 11321 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 11322 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 11323 11324 if (TrueResult.Kind == IK_NotICE) 11325 return TrueResult; 11326 if (FalseResult.Kind == IK_NotICE) 11327 return FalseResult; 11328 if (CondResult.Kind == IK_ICEIfUnevaluated) 11329 return CondResult; 11330 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 11331 return NoDiag(); 11332 // Rare case where the diagnostics depend on which side is evaluated 11333 // Note that if we get here, CondResult is 0, and at least one of 11334 // TrueResult and FalseResult is non-zero. 11335 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 11336 return FalseResult; 11337 return TrueResult; 11338 } 11339 case Expr::CXXDefaultArgExprClass: 11340 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 11341 case Expr::CXXDefaultInitExprClass: 11342 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 11343 case Expr::ChooseExprClass: { 11344 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 11345 } 11346 } 11347 11348 llvm_unreachable("Invalid StmtClass!"); 11349 } 11350 11351 /// Evaluate an expression as a C++11 integral constant expression. 11352 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 11353 const Expr *E, 11354 llvm::APSInt *Value, 11355 SourceLocation *Loc) { 11356 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 11357 if (Loc) *Loc = E->getExprLoc(); 11358 return false; 11359 } 11360 11361 APValue Result; 11362 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 11363 return false; 11364 11365 if (!Result.isInt()) { 11366 if (Loc) *Loc = E->getExprLoc(); 11367 return false; 11368 } 11369 11370 if (Value) *Value = Result.getInt(); 11371 return true; 11372 } 11373 11374 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 11375 SourceLocation *Loc) const { 11376 if (Ctx.getLangOpts().CPlusPlus11) 11377 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 11378 11379 ICEDiag D = CheckICE(this, Ctx); 11380 if (D.Kind != IK_ICE) { 11381 if (Loc) *Loc = D.Loc; 11382 return false; 11383 } 11384 return true; 11385 } 11386 11387 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 11388 SourceLocation *Loc, bool isEvaluated) const { 11389 if (Ctx.getLangOpts().CPlusPlus11) 11390 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 11391 11392 if (!isIntegerConstantExpr(Ctx, Loc)) 11393 return false; 11394 // The only possible side-effects here are due to UB discovered in the 11395 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 11396 // required to treat the expression as an ICE, so we produce the folded 11397 // value. 11398 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects)) 11399 llvm_unreachable("ICE cannot be evaluated!"); 11400 return true; 11401 } 11402 11403 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 11404 return CheckICE(this, Ctx).Kind == IK_ICE; 11405 } 11406 11407 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 11408 SourceLocation *Loc) const { 11409 // We support this checking in C++98 mode in order to diagnose compatibility 11410 // issues. 11411 assert(Ctx.getLangOpts().CPlusPlus); 11412 11413 // Build evaluation settings. 11414 Expr::EvalStatus Status; 11415 SmallVector<PartialDiagnosticAt, 8> Diags; 11416 Status.Diag = &Diags; 11417 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 11418 11419 APValue Scratch; 11420 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 11421 11422 if (!Diags.empty()) { 11423 IsConstExpr = false; 11424 if (Loc) *Loc = Diags[0].first; 11425 } else if (!IsConstExpr) { 11426 // FIXME: This shouldn't happen. 11427 if (Loc) *Loc = getExprLoc(); 11428 } 11429 11430 return IsConstExpr; 11431 } 11432 11433 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 11434 const FunctionDecl *Callee, 11435 ArrayRef<const Expr*> Args, 11436 const Expr *This) const { 11437 Expr::EvalStatus Status; 11438 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 11439 11440 LValue ThisVal; 11441 const LValue *ThisPtr = nullptr; 11442 if (This) { 11443 #ifndef NDEBUG 11444 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 11445 assert(MD && "Don't provide `this` for non-methods."); 11446 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 11447 #endif 11448 if (EvaluateObjectArgument(Info, This, ThisVal)) 11449 ThisPtr = &ThisVal; 11450 if (Info.EvalStatus.HasSideEffects) 11451 return false; 11452 } 11453 11454 ArgVector ArgValues(Args.size()); 11455 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 11456 I != E; ++I) { 11457 if ((*I)->isValueDependent() || 11458 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 11459 // If evaluation fails, throw away the argument entirely. 11460 ArgValues[I - Args.begin()] = APValue(); 11461 if (Info.EvalStatus.HasSideEffects) 11462 return false; 11463 } 11464 11465 // Build fake call to Callee. 11466 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 11467 ArgValues.data()); 11468 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 11469 } 11470 11471 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 11472 SmallVectorImpl< 11473 PartialDiagnosticAt> &Diags) { 11474 // FIXME: It would be useful to check constexpr function templates, but at the 11475 // moment the constant expression evaluator cannot cope with the non-rigorous 11476 // ASTs which we build for dependent expressions. 11477 if (FD->isDependentContext()) 11478 return true; 11479 11480 Expr::EvalStatus Status; 11481 Status.Diag = &Diags; 11482 11483 EvalInfo Info(FD->getASTContext(), Status, 11484 EvalInfo::EM_PotentialConstantExpression); 11485 11486 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 11487 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 11488 11489 // Fabricate an arbitrary expression on the stack and pretend that it 11490 // is a temporary being used as the 'this' pointer. 11491 LValue This; 11492 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 11493 This.set({&VIE, Info.CurrentCall->Index}); 11494 11495 ArrayRef<const Expr*> Args; 11496 11497 APValue Scratch; 11498 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 11499 // Evaluate the call as a constant initializer, to allow the construction 11500 // of objects of non-literal types. 11501 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 11502 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 11503 } else { 11504 SourceLocation Loc = FD->getLocation(); 11505 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 11506 Args, FD->getBody(), Info, Scratch, nullptr); 11507 } 11508 11509 return Diags.empty(); 11510 } 11511 11512 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 11513 const FunctionDecl *FD, 11514 SmallVectorImpl< 11515 PartialDiagnosticAt> &Diags) { 11516 Expr::EvalStatus Status; 11517 Status.Diag = &Diags; 11518 11519 EvalInfo Info(FD->getASTContext(), Status, 11520 EvalInfo::EM_PotentialConstantExpressionUnevaluated); 11521 11522 // Fabricate a call stack frame to give the arguments a plausible cover story. 11523 ArrayRef<const Expr*> Args; 11524 ArgVector ArgValues(0); 11525 bool Success = EvaluateArgs(Args, ArgValues, Info); 11526 (void)Success; 11527 assert(Success && 11528 "Failed to set up arguments for potential constant evaluation"); 11529 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 11530 11531 APValue ResultScratch; 11532 Evaluate(ResultScratch, Info, E); 11533 return Diags.empty(); 11534 } 11535 11536 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 11537 unsigned Type) const { 11538 if (!getType()->isPointerType()) 11539 return false; 11540 11541 Expr::EvalStatus Status; 11542 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 11543 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 11544 } 11545