1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Expr constant evaluator. 10 // 11 // Constant expression evaluation produces four main results: 12 // 13 // * A success/failure flag indicating whether constant folding was successful. 14 // This is the 'bool' return value used by most of the code in this file. A 15 // 'false' return value indicates that constant folding has failed, and any 16 // appropriate diagnostic has already been produced. 17 // 18 // * An evaluated result, valid only if constant folding has not failed. 19 // 20 // * A flag indicating if evaluation encountered (unevaluated) side-effects. 21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1), 22 // where it is possible to determine the evaluated result regardless. 23 // 24 // * A set of notes indicating why the evaluation was not a constant expression 25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed 26 // too, why the expression could not be folded. 27 // 28 // If we are checking for a potential constant expression, failure to constant 29 // fold a potential constant sub-expression will be indicated by a 'false' 30 // return value (the expression could not be folded) and no diagnostic (the 31 // expression is not necessarily non-constant). 32 // 33 //===----------------------------------------------------------------------===// 34 35 #include "clang/AST/APValue.h" 36 #include "clang/AST/ASTContext.h" 37 #include "clang/AST/ASTDiagnostic.h" 38 #include "clang/AST/ASTLambda.h" 39 #include "clang/AST/CharUnits.h" 40 #include "clang/AST/CurrentSourceLocExprScope.h" 41 #include "clang/AST/CXXInheritance.h" 42 #include "clang/AST/Expr.h" 43 #include "clang/AST/OSLog.h" 44 #include "clang/AST/RecordLayout.h" 45 #include "clang/AST/StmtVisitor.h" 46 #include "clang/AST/TypeLoc.h" 47 #include "clang/Basic/Builtins.h" 48 #include "clang/Basic/FixedPoint.h" 49 #include "clang/Basic/TargetInfo.h" 50 #include "llvm/ADT/Optional.h" 51 #include "llvm/ADT/SmallBitVector.h" 52 #include "llvm/Support/SaveAndRestore.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include <cstring> 55 #include <functional> 56 57 #define DEBUG_TYPE "exprconstant" 58 59 using namespace clang; 60 using llvm::APInt; 61 using llvm::APSInt; 62 using llvm::APFloat; 63 using llvm::Optional; 64 65 static bool IsGlobalLValue(APValue::LValueBase B); 66 67 namespace { 68 struct LValue; 69 struct CallStackFrame; 70 struct EvalInfo; 71 72 using SourceLocExprScopeGuard = 73 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 74 75 static QualType getType(APValue::LValueBase B) { 76 if (!B) return QualType(); 77 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 78 // FIXME: It's unclear where we're supposed to take the type from, and 79 // this actually matters for arrays of unknown bound. Eg: 80 // 81 // extern int arr[]; void f() { extern int arr[3]; }; 82 // constexpr int *p = &arr[1]; // valid? 83 // 84 // For now, we take the array bound from the most recent declaration. 85 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 86 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 87 QualType T = Redecl->getType(); 88 if (!T->isIncompleteArrayType()) 89 return T; 90 } 91 return D->getType(); 92 } 93 94 if (B.is<TypeInfoLValue>()) 95 return B.getTypeInfoType(); 96 97 const Expr *Base = B.get<const Expr*>(); 98 99 // For a materialized temporary, the type of the temporary we materialized 100 // may not be the type of the expression. 101 if (const MaterializeTemporaryExpr *MTE = 102 dyn_cast<MaterializeTemporaryExpr>(Base)) { 103 SmallVector<const Expr *, 2> CommaLHSs; 104 SmallVector<SubobjectAdjustment, 2> Adjustments; 105 const Expr *Temp = MTE->GetTemporaryExpr(); 106 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 107 Adjustments); 108 // Keep any cv-qualifiers from the reference if we generated a temporary 109 // for it directly. Otherwise use the type after adjustment. 110 if (!Adjustments.empty()) 111 return Inner->getType(); 112 } 113 114 return Base->getType(); 115 } 116 117 /// Get an LValue path entry, which is known to not be an array index, as a 118 /// field declaration. 119 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 120 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 121 } 122 /// Get an LValue path entry, which is known to not be an array index, as a 123 /// base class declaration. 124 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 125 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 126 } 127 /// Determine whether this LValue path entry for a base class names a virtual 128 /// base class. 129 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 130 return E.getAsBaseOrMember().getInt(); 131 } 132 133 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 134 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 135 const FunctionDecl *Callee = CE->getDirectCallee(); 136 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 137 } 138 139 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 140 /// This will look through a single cast. 141 /// 142 /// Returns null if we couldn't unwrap a function with alloc_size. 143 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 144 if (!E->getType()->isPointerType()) 145 return nullptr; 146 147 E = E->IgnoreParens(); 148 // If we're doing a variable assignment from e.g. malloc(N), there will 149 // probably be a cast of some kind. In exotic cases, we might also see a 150 // top-level ExprWithCleanups. Ignore them either way. 151 if (const auto *FE = dyn_cast<FullExpr>(E)) 152 E = FE->getSubExpr()->IgnoreParens(); 153 154 if (const auto *Cast = dyn_cast<CastExpr>(E)) 155 E = Cast->getSubExpr()->IgnoreParens(); 156 157 if (const auto *CE = dyn_cast<CallExpr>(E)) 158 return getAllocSizeAttr(CE) ? CE : nullptr; 159 return nullptr; 160 } 161 162 /// Determines whether or not the given Base contains a call to a function 163 /// with the alloc_size attribute. 164 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 165 const auto *E = Base.dyn_cast<const Expr *>(); 166 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 167 } 168 169 /// The bound to claim that an array of unknown bound has. 170 /// The value in MostDerivedArraySize is undefined in this case. So, set it 171 /// to an arbitrary value that's likely to loudly break things if it's used. 172 static const uint64_t AssumedSizeForUnsizedArray = 173 std::numeric_limits<uint64_t>::max() / 2; 174 175 /// Determines if an LValue with the given LValueBase will have an unsized 176 /// array in its designator. 177 /// Find the path length and type of the most-derived subobject in the given 178 /// path, and find the size of the containing array, if any. 179 static unsigned 180 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 181 ArrayRef<APValue::LValuePathEntry> Path, 182 uint64_t &ArraySize, QualType &Type, bool &IsArray, 183 bool &FirstEntryIsUnsizedArray) { 184 // This only accepts LValueBases from APValues, and APValues don't support 185 // arrays that lack size info. 186 assert(!isBaseAnAllocSizeCall(Base) && 187 "Unsized arrays shouldn't appear here"); 188 unsigned MostDerivedLength = 0; 189 Type = getType(Base); 190 191 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 192 if (Type->isArrayType()) { 193 const ArrayType *AT = Ctx.getAsArrayType(Type); 194 Type = AT->getElementType(); 195 MostDerivedLength = I + 1; 196 IsArray = true; 197 198 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 199 ArraySize = CAT->getSize().getZExtValue(); 200 } else { 201 assert(I == 0 && "unexpected unsized array designator"); 202 FirstEntryIsUnsizedArray = true; 203 ArraySize = AssumedSizeForUnsizedArray; 204 } 205 } else if (Type->isAnyComplexType()) { 206 const ComplexType *CT = Type->castAs<ComplexType>(); 207 Type = CT->getElementType(); 208 ArraySize = 2; 209 MostDerivedLength = I + 1; 210 IsArray = true; 211 } else if (const FieldDecl *FD = getAsField(Path[I])) { 212 Type = FD->getType(); 213 ArraySize = 0; 214 MostDerivedLength = I + 1; 215 IsArray = false; 216 } else { 217 // Path[I] describes a base class. 218 ArraySize = 0; 219 IsArray = false; 220 } 221 } 222 return MostDerivedLength; 223 } 224 225 // The order of this enum is important for diagnostics. 226 enum CheckSubobjectKind { 227 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 228 CSK_Real, CSK_Imag 229 }; 230 231 /// A path from a glvalue to a subobject of that glvalue. 232 struct SubobjectDesignator { 233 /// True if the subobject was named in a manner not supported by C++11. Such 234 /// lvalues can still be folded, but they are not core constant expressions 235 /// and we cannot perform lvalue-to-rvalue conversions on them. 236 unsigned Invalid : 1; 237 238 /// Is this a pointer one past the end of an object? 239 unsigned IsOnePastTheEnd : 1; 240 241 /// Indicator of whether the first entry is an unsized array. 242 unsigned FirstEntryIsAnUnsizedArray : 1; 243 244 /// Indicator of whether the most-derived object is an array element. 245 unsigned MostDerivedIsArrayElement : 1; 246 247 /// The length of the path to the most-derived object of which this is a 248 /// subobject. 249 unsigned MostDerivedPathLength : 28; 250 251 /// The size of the array of which the most-derived object is an element. 252 /// This will always be 0 if the most-derived object is not an array 253 /// element. 0 is not an indicator of whether or not the most-derived object 254 /// is an array, however, because 0-length arrays are allowed. 255 /// 256 /// If the current array is an unsized array, the value of this is 257 /// undefined. 258 uint64_t MostDerivedArraySize; 259 260 /// The type of the most derived object referred to by this address. 261 QualType MostDerivedType; 262 263 typedef APValue::LValuePathEntry PathEntry; 264 265 /// The entries on the path from the glvalue to the designated subobject. 266 SmallVector<PathEntry, 8> Entries; 267 268 SubobjectDesignator() : Invalid(true) {} 269 270 explicit SubobjectDesignator(QualType T) 271 : Invalid(false), IsOnePastTheEnd(false), 272 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 273 MostDerivedPathLength(0), MostDerivedArraySize(0), 274 MostDerivedType(T) {} 275 276 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 277 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 278 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 279 MostDerivedPathLength(0), MostDerivedArraySize(0) { 280 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 281 if (!Invalid) { 282 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 283 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 284 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 285 if (V.getLValueBase()) { 286 bool IsArray = false; 287 bool FirstIsUnsizedArray = false; 288 MostDerivedPathLength = findMostDerivedSubobject( 289 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 290 MostDerivedType, IsArray, FirstIsUnsizedArray); 291 MostDerivedIsArrayElement = IsArray; 292 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 293 } 294 } 295 } 296 297 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 298 unsigned NewLength) { 299 if (Invalid) 300 return; 301 302 assert(Base && "cannot truncate path for null pointer"); 303 assert(NewLength <= Entries.size() && "not a truncation"); 304 305 if (NewLength == Entries.size()) 306 return; 307 Entries.resize(NewLength); 308 309 bool IsArray = false; 310 bool FirstIsUnsizedArray = false; 311 MostDerivedPathLength = findMostDerivedSubobject( 312 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 313 FirstIsUnsizedArray); 314 MostDerivedIsArrayElement = IsArray; 315 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 316 } 317 318 void setInvalid() { 319 Invalid = true; 320 Entries.clear(); 321 } 322 323 /// Determine whether the most derived subobject is an array without a 324 /// known bound. 325 bool isMostDerivedAnUnsizedArray() const { 326 assert(!Invalid && "Calling this makes no sense on invalid designators"); 327 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 328 } 329 330 /// Determine what the most derived array's size is. Results in an assertion 331 /// failure if the most derived array lacks a size. 332 uint64_t getMostDerivedArraySize() const { 333 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 334 return MostDerivedArraySize; 335 } 336 337 /// Determine whether this is a one-past-the-end pointer. 338 bool isOnePastTheEnd() const { 339 assert(!Invalid); 340 if (IsOnePastTheEnd) 341 return true; 342 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 343 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 344 MostDerivedArraySize) 345 return true; 346 return false; 347 } 348 349 /// Get the range of valid index adjustments in the form 350 /// {maximum value that can be subtracted from this pointer, 351 /// maximum value that can be added to this pointer} 352 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 353 if (Invalid || isMostDerivedAnUnsizedArray()) 354 return {0, 0}; 355 356 // [expr.add]p4: For the purposes of these operators, a pointer to a 357 // nonarray object behaves the same as a pointer to the first element of 358 // an array of length one with the type of the object as its element type. 359 bool IsArray = MostDerivedPathLength == Entries.size() && 360 MostDerivedIsArrayElement; 361 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 362 : (uint64_t)IsOnePastTheEnd; 363 uint64_t ArraySize = 364 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 365 return {ArrayIndex, ArraySize - ArrayIndex}; 366 } 367 368 /// Check that this refers to a valid subobject. 369 bool isValidSubobject() const { 370 if (Invalid) 371 return false; 372 return !isOnePastTheEnd(); 373 } 374 /// Check that this refers to a valid subobject, and if not, produce a 375 /// relevant diagnostic and set the designator as invalid. 376 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 377 378 /// Get the type of the designated object. 379 QualType getType(ASTContext &Ctx) const { 380 assert(!Invalid && "invalid designator has no subobject type"); 381 return MostDerivedPathLength == Entries.size() 382 ? MostDerivedType 383 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 384 } 385 386 /// Update this designator to refer to the first element within this array. 387 void addArrayUnchecked(const ConstantArrayType *CAT) { 388 Entries.push_back(PathEntry::ArrayIndex(0)); 389 390 // This is a most-derived object. 391 MostDerivedType = CAT->getElementType(); 392 MostDerivedIsArrayElement = true; 393 MostDerivedArraySize = CAT->getSize().getZExtValue(); 394 MostDerivedPathLength = Entries.size(); 395 } 396 /// Update this designator to refer to the first element within the array of 397 /// elements of type T. This is an array of unknown size. 398 void addUnsizedArrayUnchecked(QualType ElemTy) { 399 Entries.push_back(PathEntry::ArrayIndex(0)); 400 401 MostDerivedType = ElemTy; 402 MostDerivedIsArrayElement = true; 403 // The value in MostDerivedArraySize is undefined in this case. So, set it 404 // to an arbitrary value that's likely to loudly break things if it's 405 // used. 406 MostDerivedArraySize = AssumedSizeForUnsizedArray; 407 MostDerivedPathLength = Entries.size(); 408 } 409 /// Update this designator to refer to the given base or member of this 410 /// object. 411 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 412 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 413 414 // If this isn't a base class, it's a new most-derived object. 415 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 416 MostDerivedType = FD->getType(); 417 MostDerivedIsArrayElement = false; 418 MostDerivedArraySize = 0; 419 MostDerivedPathLength = Entries.size(); 420 } 421 } 422 /// Update this designator to refer to the given complex component. 423 void addComplexUnchecked(QualType EltTy, bool Imag) { 424 Entries.push_back(PathEntry::ArrayIndex(Imag)); 425 426 // This is technically a most-derived object, though in practice this 427 // is unlikely to matter. 428 MostDerivedType = EltTy; 429 MostDerivedIsArrayElement = true; 430 MostDerivedArraySize = 2; 431 MostDerivedPathLength = Entries.size(); 432 } 433 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 434 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 435 const APSInt &N); 436 /// Add N to the address of this subobject. 437 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 438 if (Invalid || !N) return; 439 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 440 if (isMostDerivedAnUnsizedArray()) { 441 diagnoseUnsizedArrayPointerArithmetic(Info, E); 442 // Can't verify -- trust that the user is doing the right thing (or if 443 // not, trust that the caller will catch the bad behavior). 444 // FIXME: Should we reject if this overflows, at least? 445 Entries.back() = PathEntry::ArrayIndex( 446 Entries.back().getAsArrayIndex() + TruncatedN); 447 return; 448 } 449 450 // [expr.add]p4: For the purposes of these operators, a pointer to a 451 // nonarray object behaves the same as a pointer to the first element of 452 // an array of length one with the type of the object as its element type. 453 bool IsArray = MostDerivedPathLength == Entries.size() && 454 MostDerivedIsArrayElement; 455 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 456 : (uint64_t)IsOnePastTheEnd; 457 uint64_t ArraySize = 458 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 459 460 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 461 // Calculate the actual index in a wide enough type, so we can include 462 // it in the note. 463 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 464 (llvm::APInt&)N += ArrayIndex; 465 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 466 diagnosePointerArithmetic(Info, E, N); 467 setInvalid(); 468 return; 469 } 470 471 ArrayIndex += TruncatedN; 472 assert(ArrayIndex <= ArraySize && 473 "bounds check succeeded for out-of-bounds index"); 474 475 if (IsArray) 476 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 477 else 478 IsOnePastTheEnd = (ArrayIndex != 0); 479 } 480 }; 481 482 /// A stack frame in the constexpr call stack. 483 struct CallStackFrame { 484 EvalInfo &Info; 485 486 /// Parent - The caller of this stack frame. 487 CallStackFrame *Caller; 488 489 /// Callee - The function which was called. 490 const FunctionDecl *Callee; 491 492 /// This - The binding for the this pointer in this call, if any. 493 const LValue *This; 494 495 /// Arguments - Parameter bindings for this function call, indexed by 496 /// parameters' function scope indices. 497 APValue *Arguments; 498 499 /// Source location information about the default argument or default 500 /// initializer expression we're evaluating, if any. 501 CurrentSourceLocExprScope CurSourceLocExprScope; 502 503 // Note that we intentionally use std::map here so that references to 504 // values are stable. 505 typedef std::pair<const void *, unsigned> MapKeyTy; 506 typedef std::map<MapKeyTy, APValue> MapTy; 507 /// Temporaries - Temporary lvalues materialized within this stack frame. 508 MapTy Temporaries; 509 510 /// CallLoc - The location of the call expression for this call. 511 SourceLocation CallLoc; 512 513 /// Index - The call index of this call. 514 unsigned Index; 515 516 /// The stack of integers for tracking version numbers for temporaries. 517 SmallVector<unsigned, 2> TempVersionStack = {1}; 518 unsigned CurTempVersion = TempVersionStack.back(); 519 520 unsigned getTempVersion() const { return TempVersionStack.back(); } 521 522 void pushTempVersion() { 523 TempVersionStack.push_back(++CurTempVersion); 524 } 525 526 void popTempVersion() { 527 TempVersionStack.pop_back(); 528 } 529 530 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 531 // on the overall stack usage of deeply-recursing constexpr evaluations. 532 // (We should cache this map rather than recomputing it repeatedly.) 533 // But let's try this and see how it goes; we can look into caching the map 534 // as a later change. 535 536 /// LambdaCaptureFields - Mapping from captured variables/this to 537 /// corresponding data members in the closure class. 538 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 539 FieldDecl *LambdaThisCaptureField; 540 541 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 542 const FunctionDecl *Callee, const LValue *This, 543 APValue *Arguments); 544 ~CallStackFrame(); 545 546 // Return the temporary for Key whose version number is Version. 547 APValue *getTemporary(const void *Key, unsigned Version) { 548 MapKeyTy KV(Key, Version); 549 auto LB = Temporaries.lower_bound(KV); 550 if (LB != Temporaries.end() && LB->first == KV) 551 return &LB->second; 552 // Pair (Key,Version) wasn't found in the map. Check that no elements 553 // in the map have 'Key' as their key. 554 assert((LB == Temporaries.end() || LB->first.first != Key) && 555 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 556 "Element with key 'Key' found in map"); 557 return nullptr; 558 } 559 560 // Return the current temporary for Key in the map. 561 APValue *getCurrentTemporary(const void *Key) { 562 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 563 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 564 return &std::prev(UB)->second; 565 return nullptr; 566 } 567 568 // Return the version number of the current temporary for Key. 569 unsigned getCurrentTemporaryVersion(const void *Key) const { 570 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 571 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 572 return std::prev(UB)->first.second; 573 return 0; 574 } 575 576 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 577 }; 578 579 /// Temporarily override 'this'. 580 class ThisOverrideRAII { 581 public: 582 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 583 : Frame(Frame), OldThis(Frame.This) { 584 if (Enable) 585 Frame.This = NewThis; 586 } 587 ~ThisOverrideRAII() { 588 Frame.This = OldThis; 589 } 590 private: 591 CallStackFrame &Frame; 592 const LValue *OldThis; 593 }; 594 595 /// A partial diagnostic which we might know in advance that we are not going 596 /// to emit. 597 class OptionalDiagnostic { 598 PartialDiagnostic *Diag; 599 600 public: 601 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr) 602 : Diag(Diag) {} 603 604 template<typename T> 605 OptionalDiagnostic &operator<<(const T &v) { 606 if (Diag) 607 *Diag << v; 608 return *this; 609 } 610 611 OptionalDiagnostic &operator<<(const APSInt &I) { 612 if (Diag) { 613 SmallVector<char, 32> Buffer; 614 I.toString(Buffer); 615 *Diag << StringRef(Buffer.data(), Buffer.size()); 616 } 617 return *this; 618 } 619 620 OptionalDiagnostic &operator<<(const APFloat &F) { 621 if (Diag) { 622 // FIXME: Force the precision of the source value down so we don't 623 // print digits which are usually useless (we don't really care here if 624 // we truncate a digit by accident in edge cases). Ideally, 625 // APFloat::toString would automatically print the shortest 626 // representation which rounds to the correct value, but it's a bit 627 // tricky to implement. 628 unsigned precision = 629 llvm::APFloat::semanticsPrecision(F.getSemantics()); 630 precision = (precision * 59 + 195) / 196; 631 SmallVector<char, 32> Buffer; 632 F.toString(Buffer, precision); 633 *Diag << StringRef(Buffer.data(), Buffer.size()); 634 } 635 return *this; 636 } 637 638 OptionalDiagnostic &operator<<(const APFixedPoint &FX) { 639 if (Diag) { 640 SmallVector<char, 32> Buffer; 641 FX.toString(Buffer); 642 *Diag << StringRef(Buffer.data(), Buffer.size()); 643 } 644 return *this; 645 } 646 }; 647 648 /// A cleanup, and a flag indicating whether it is lifetime-extended. 649 class Cleanup { 650 llvm::PointerIntPair<APValue*, 1, bool> Value; 651 652 public: 653 Cleanup(APValue *Val, bool IsLifetimeExtended) 654 : Value(Val, IsLifetimeExtended) {} 655 656 bool isLifetimeExtended() const { return Value.getInt(); } 657 void endLifetime() { 658 *Value.getPointer() = APValue(); 659 } 660 }; 661 662 /// A reference to an object whose construction we are currently evaluating. 663 struct ObjectUnderConstruction { 664 APValue::LValueBase Base; 665 ArrayRef<APValue::LValuePathEntry> Path; 666 friend bool operator==(const ObjectUnderConstruction &LHS, 667 const ObjectUnderConstruction &RHS) { 668 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 669 } 670 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 671 return llvm::hash_combine(Obj.Base, Obj.Path); 672 } 673 }; 674 enum class ConstructionPhase { None, Bases, AfterBases }; 675 } 676 677 namespace llvm { 678 template<> struct DenseMapInfo<ObjectUnderConstruction> { 679 using Base = DenseMapInfo<APValue::LValueBase>; 680 static ObjectUnderConstruction getEmptyKey() { 681 return {Base::getEmptyKey(), {}}; } 682 static ObjectUnderConstruction getTombstoneKey() { 683 return {Base::getTombstoneKey(), {}}; 684 } 685 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 686 return hash_value(Object); 687 } 688 static bool isEqual(const ObjectUnderConstruction &LHS, 689 const ObjectUnderConstruction &RHS) { 690 return LHS == RHS; 691 } 692 }; 693 } 694 695 namespace { 696 /// EvalInfo - This is a private struct used by the evaluator to capture 697 /// information about a subexpression as it is folded. It retains information 698 /// about the AST context, but also maintains information about the folded 699 /// expression. 700 /// 701 /// If an expression could be evaluated, it is still possible it is not a C 702 /// "integer constant expression" or constant expression. If not, this struct 703 /// captures information about how and why not. 704 /// 705 /// One bit of information passed *into* the request for constant folding 706 /// indicates whether the subexpression is "evaluated" or not according to C 707 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 708 /// evaluate the expression regardless of what the RHS is, but C only allows 709 /// certain things in certain situations. 710 struct EvalInfo { 711 ASTContext &Ctx; 712 713 /// EvalStatus - Contains information about the evaluation. 714 Expr::EvalStatus &EvalStatus; 715 716 /// CurrentCall - The top of the constexpr call stack. 717 CallStackFrame *CurrentCall; 718 719 /// CallStackDepth - The number of calls in the call stack right now. 720 unsigned CallStackDepth; 721 722 /// NextCallIndex - The next call index to assign. 723 unsigned NextCallIndex; 724 725 /// StepsLeft - The remaining number of evaluation steps we're permitted 726 /// to perform. This is essentially a limit for the number of statements 727 /// we will evaluate. 728 unsigned StepsLeft; 729 730 /// BottomFrame - The frame in which evaluation started. This must be 731 /// initialized after CurrentCall and CallStackDepth. 732 CallStackFrame BottomFrame; 733 734 /// A stack of values whose lifetimes end at the end of some surrounding 735 /// evaluation frame. 736 llvm::SmallVector<Cleanup, 16> CleanupStack; 737 738 /// EvaluatingDecl - This is the declaration whose initializer is being 739 /// evaluated, if any. 740 APValue::LValueBase EvaluatingDecl; 741 742 /// EvaluatingDeclValue - This is the value being constructed for the 743 /// declaration whose initializer is being evaluated, if any. 744 APValue *EvaluatingDeclValue; 745 746 /// Set of objects that are currently being constructed. 747 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 748 ObjectsUnderConstruction; 749 750 struct EvaluatingConstructorRAII { 751 EvalInfo &EI; 752 ObjectUnderConstruction Object; 753 bool DidInsert; 754 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 755 bool HasBases) 756 : EI(EI), Object(Object) { 757 DidInsert = 758 EI.ObjectsUnderConstruction 759 .insert({Object, HasBases ? ConstructionPhase::Bases 760 : ConstructionPhase::AfterBases}) 761 .second; 762 } 763 void finishedConstructingBases() { 764 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 765 } 766 ~EvaluatingConstructorRAII() { 767 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 768 } 769 }; 770 771 ConstructionPhase 772 isEvaluatingConstructor(APValue::LValueBase Base, 773 ArrayRef<APValue::LValuePathEntry> Path) { 774 return ObjectsUnderConstruction.lookup({Base, Path}); 775 } 776 777 /// If we're currently speculatively evaluating, the outermost call stack 778 /// depth at which we can mutate state, otherwise 0. 779 unsigned SpeculativeEvaluationDepth = 0; 780 781 /// The current array initialization index, if we're performing array 782 /// initialization. 783 uint64_t ArrayInitIndex = -1; 784 785 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 786 /// notes attached to it will also be stored, otherwise they will not be. 787 bool HasActiveDiagnostic; 788 789 /// Have we emitted a diagnostic explaining why we couldn't constant 790 /// fold (not just why it's not strictly a constant expression)? 791 bool HasFoldFailureDiagnostic; 792 793 /// Whether or not we're in a context where the front end requires a 794 /// constant value. 795 bool InConstantContext; 796 797 enum EvaluationMode { 798 /// Evaluate as a constant expression. Stop if we find that the expression 799 /// is not a constant expression. 800 EM_ConstantExpression, 801 802 /// Evaluate as a potential constant expression. Keep going if we hit a 803 /// construct that we can't evaluate yet (because we don't yet know the 804 /// value of something) but stop if we hit something that could never be 805 /// a constant expression. 806 EM_PotentialConstantExpression, 807 808 /// Fold the expression to a constant. Stop if we hit a side-effect that 809 /// we can't model. 810 EM_ConstantFold, 811 812 /// Evaluate the expression looking for integer overflow and similar 813 /// issues. Don't worry about side-effects, and try to visit all 814 /// subexpressions. 815 EM_EvaluateForOverflow, 816 817 /// Evaluate in any way we know how. Don't worry about side-effects that 818 /// can't be modeled. 819 EM_IgnoreSideEffects, 820 821 /// Evaluate as a constant expression. Stop if we find that the expression 822 /// is not a constant expression. Some expressions can be retried in the 823 /// optimizer if we don't constant fold them here, but in an unevaluated 824 /// context we try to fold them immediately since the optimizer never 825 /// gets a chance to look at it. 826 EM_ConstantExpressionUnevaluated, 827 828 /// Evaluate as a potential constant expression. Keep going if we hit a 829 /// construct that we can't evaluate yet (because we don't yet know the 830 /// value of something) but stop if we hit something that could never be 831 /// a constant expression. Some expressions can be retried in the 832 /// optimizer if we don't constant fold them here, but in an unevaluated 833 /// context we try to fold them immediately since the optimizer never 834 /// gets a chance to look at it. 835 EM_PotentialConstantExpressionUnevaluated, 836 } EvalMode; 837 838 /// Are we checking whether the expression is a potential constant 839 /// expression? 840 bool checkingPotentialConstantExpression() const { 841 return EvalMode == EM_PotentialConstantExpression || 842 EvalMode == EM_PotentialConstantExpressionUnevaluated; 843 } 844 845 /// Are we checking an expression for overflow? 846 // FIXME: We should check for any kind of undefined or suspicious behavior 847 // in such constructs, not just overflow. 848 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; } 849 850 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 851 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 852 CallStackDepth(0), NextCallIndex(1), 853 StepsLeft(getLangOpts().ConstexprStepLimit), 854 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 855 EvaluatingDecl((const ValueDecl *)nullptr), 856 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 857 HasFoldFailureDiagnostic(false), 858 InConstantContext(false), EvalMode(Mode) {} 859 860 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 861 EvaluatingDecl = Base; 862 EvaluatingDeclValue = &Value; 863 } 864 865 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 866 867 bool CheckCallLimit(SourceLocation Loc) { 868 // Don't perform any constexpr calls (other than the call we're checking) 869 // when checking a potential constant expression. 870 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 871 return false; 872 if (NextCallIndex == 0) { 873 // NextCallIndex has wrapped around. 874 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 875 return false; 876 } 877 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 878 return true; 879 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 880 << getLangOpts().ConstexprCallDepth; 881 return false; 882 } 883 884 std::pair<CallStackFrame *, unsigned> 885 getCallFrameAndDepth(unsigned CallIndex) { 886 assert(CallIndex && "no call index in getCallFrameAndDepth"); 887 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 888 // be null in this loop. 889 unsigned Depth = CallStackDepth; 890 CallStackFrame *Frame = CurrentCall; 891 while (Frame->Index > CallIndex) { 892 Frame = Frame->Caller; 893 --Depth; 894 } 895 if (Frame->Index == CallIndex) 896 return {Frame, Depth}; 897 return {nullptr, 0}; 898 } 899 900 bool nextStep(const Stmt *S) { 901 if (!StepsLeft) { 902 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 903 return false; 904 } 905 --StepsLeft; 906 return true; 907 } 908 909 private: 910 /// Add a diagnostic to the diagnostics list. 911 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 912 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 913 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 914 return EvalStatus.Diag->back().second; 915 } 916 917 /// Add notes containing a call stack to the current point of evaluation. 918 void addCallStack(unsigned Limit); 919 920 private: 921 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, 922 unsigned ExtraNotes, bool IsCCEDiag) { 923 924 if (EvalStatus.Diag) { 925 // If we have a prior diagnostic, it will be noting that the expression 926 // isn't a constant expression. This diagnostic is more important, 927 // unless we require this evaluation to produce a constant expression. 928 // 929 // FIXME: We might want to show both diagnostics to the user in 930 // EM_ConstantFold mode. 931 if (!EvalStatus.Diag->empty()) { 932 switch (EvalMode) { 933 case EM_ConstantFold: 934 case EM_IgnoreSideEffects: 935 case EM_EvaluateForOverflow: 936 if (!HasFoldFailureDiagnostic) 937 break; 938 // We've already failed to fold something. Keep that diagnostic. 939 LLVM_FALLTHROUGH; 940 case EM_ConstantExpression: 941 case EM_PotentialConstantExpression: 942 case EM_ConstantExpressionUnevaluated: 943 case EM_PotentialConstantExpressionUnevaluated: 944 HasActiveDiagnostic = false; 945 return OptionalDiagnostic(); 946 } 947 } 948 949 unsigned CallStackNotes = CallStackDepth - 1; 950 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 951 if (Limit) 952 CallStackNotes = std::min(CallStackNotes, Limit + 1); 953 if (checkingPotentialConstantExpression()) 954 CallStackNotes = 0; 955 956 HasActiveDiagnostic = true; 957 HasFoldFailureDiagnostic = !IsCCEDiag; 958 EvalStatus.Diag->clear(); 959 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 960 addDiag(Loc, DiagId); 961 if (!checkingPotentialConstantExpression()) 962 addCallStack(Limit); 963 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 964 } 965 HasActiveDiagnostic = false; 966 return OptionalDiagnostic(); 967 } 968 public: 969 // Diagnose that the evaluation could not be folded (FF => FoldFailure) 970 OptionalDiagnostic 971 FFDiag(SourceLocation Loc, 972 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, 973 unsigned ExtraNotes = 0) { 974 return Diag(Loc, DiagId, ExtraNotes, false); 975 } 976 977 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId 978 = diag::note_invalid_subexpr_in_const_expr, 979 unsigned ExtraNotes = 0) { 980 if (EvalStatus.Diag) 981 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false); 982 HasActiveDiagnostic = false; 983 return OptionalDiagnostic(); 984 } 985 986 /// Diagnose that the evaluation does not produce a C++11 core constant 987 /// expression. 988 /// 989 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or 990 /// EM_PotentialConstantExpression mode and we produce one of these. 991 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 992 = diag::note_invalid_subexpr_in_const_expr, 993 unsigned ExtraNotes = 0) { 994 // Don't override a previous diagnostic. Don't bother collecting 995 // diagnostics if we're evaluating for overflow. 996 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 997 HasActiveDiagnostic = false; 998 return OptionalDiagnostic(); 999 } 1000 return Diag(Loc, DiagId, ExtraNotes, true); 1001 } 1002 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId 1003 = diag::note_invalid_subexpr_in_const_expr, 1004 unsigned ExtraNotes = 0) { 1005 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes); 1006 } 1007 /// Add a note to a prior diagnostic. 1008 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 1009 if (!HasActiveDiagnostic) 1010 return OptionalDiagnostic(); 1011 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 1012 } 1013 1014 /// Add a stack of notes to a prior diagnostic. 1015 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 1016 if (HasActiveDiagnostic) { 1017 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 1018 Diags.begin(), Diags.end()); 1019 } 1020 } 1021 1022 /// Should we continue evaluation after encountering a side-effect that we 1023 /// couldn't model? 1024 bool keepEvaluatingAfterSideEffect() { 1025 switch (EvalMode) { 1026 case EM_PotentialConstantExpression: 1027 case EM_PotentialConstantExpressionUnevaluated: 1028 case EM_EvaluateForOverflow: 1029 case EM_IgnoreSideEffects: 1030 return true; 1031 1032 case EM_ConstantExpression: 1033 case EM_ConstantExpressionUnevaluated: 1034 case EM_ConstantFold: 1035 return false; 1036 } 1037 llvm_unreachable("Missed EvalMode case"); 1038 } 1039 1040 /// Note that we have had a side-effect, and determine whether we should 1041 /// keep evaluating. 1042 bool noteSideEffect() { 1043 EvalStatus.HasSideEffects = true; 1044 return keepEvaluatingAfterSideEffect(); 1045 } 1046 1047 /// Should we continue evaluation after encountering undefined behavior? 1048 bool keepEvaluatingAfterUndefinedBehavior() { 1049 switch (EvalMode) { 1050 case EM_EvaluateForOverflow: 1051 case EM_IgnoreSideEffects: 1052 case EM_ConstantFold: 1053 return true; 1054 1055 case EM_PotentialConstantExpression: 1056 case EM_PotentialConstantExpressionUnevaluated: 1057 case EM_ConstantExpression: 1058 case EM_ConstantExpressionUnevaluated: 1059 return false; 1060 } 1061 llvm_unreachable("Missed EvalMode case"); 1062 } 1063 1064 /// Note that we hit something that was technically undefined behavior, but 1065 /// that we can evaluate past it (such as signed overflow or floating-point 1066 /// division by zero.) 1067 bool noteUndefinedBehavior() { 1068 EvalStatus.HasUndefinedBehavior = true; 1069 return keepEvaluatingAfterUndefinedBehavior(); 1070 } 1071 1072 /// Should we continue evaluation as much as possible after encountering a 1073 /// construct which can't be reduced to a value? 1074 bool keepEvaluatingAfterFailure() { 1075 if (!StepsLeft) 1076 return false; 1077 1078 switch (EvalMode) { 1079 case EM_PotentialConstantExpression: 1080 case EM_PotentialConstantExpressionUnevaluated: 1081 case EM_EvaluateForOverflow: 1082 return true; 1083 1084 case EM_ConstantExpression: 1085 case EM_ConstantExpressionUnevaluated: 1086 case EM_ConstantFold: 1087 case EM_IgnoreSideEffects: 1088 return false; 1089 } 1090 llvm_unreachable("Missed EvalMode case"); 1091 } 1092 1093 /// Notes that we failed to evaluate an expression that other expressions 1094 /// directly depend on, and determine if we should keep evaluating. This 1095 /// should only be called if we actually intend to keep evaluating. 1096 /// 1097 /// Call noteSideEffect() instead if we may be able to ignore the value that 1098 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1099 /// 1100 /// (Foo(), 1) // use noteSideEffect 1101 /// (Foo() || true) // use noteSideEffect 1102 /// Foo() + 1 // use noteFailure 1103 LLVM_NODISCARD bool noteFailure() { 1104 // Failure when evaluating some expression often means there is some 1105 // subexpression whose evaluation was skipped. Therefore, (because we 1106 // don't track whether we skipped an expression when unwinding after an 1107 // evaluation failure) every evaluation failure that bubbles up from a 1108 // subexpression implies that a side-effect has potentially happened. We 1109 // skip setting the HasSideEffects flag to true until we decide to 1110 // continue evaluating after that point, which happens here. 1111 bool KeepGoing = keepEvaluatingAfterFailure(); 1112 EvalStatus.HasSideEffects |= KeepGoing; 1113 return KeepGoing; 1114 } 1115 1116 class ArrayInitLoopIndex { 1117 EvalInfo &Info; 1118 uint64_t OuterIndex; 1119 1120 public: 1121 ArrayInitLoopIndex(EvalInfo &Info) 1122 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1123 Info.ArrayInitIndex = 0; 1124 } 1125 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1126 1127 operator uint64_t&() { return Info.ArrayInitIndex; } 1128 }; 1129 }; 1130 1131 /// Object used to treat all foldable expressions as constant expressions. 1132 struct FoldConstant { 1133 EvalInfo &Info; 1134 bool Enabled; 1135 bool HadNoPriorDiags; 1136 EvalInfo::EvaluationMode OldMode; 1137 1138 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1139 : Info(Info), 1140 Enabled(Enabled), 1141 HadNoPriorDiags(Info.EvalStatus.Diag && 1142 Info.EvalStatus.Diag->empty() && 1143 !Info.EvalStatus.HasSideEffects), 1144 OldMode(Info.EvalMode) { 1145 if (Enabled && 1146 (Info.EvalMode == EvalInfo::EM_ConstantExpression || 1147 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated)) 1148 Info.EvalMode = EvalInfo::EM_ConstantFold; 1149 } 1150 void keepDiagnostics() { Enabled = false; } 1151 ~FoldConstant() { 1152 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1153 !Info.EvalStatus.HasSideEffects) 1154 Info.EvalStatus.Diag->clear(); 1155 Info.EvalMode = OldMode; 1156 } 1157 }; 1158 1159 /// RAII object used to set the current evaluation mode to ignore 1160 /// side-effects. 1161 struct IgnoreSideEffectsRAII { 1162 EvalInfo &Info; 1163 EvalInfo::EvaluationMode OldMode; 1164 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1165 : Info(Info), OldMode(Info.EvalMode) { 1166 if (!Info.checkingPotentialConstantExpression()) 1167 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1168 } 1169 1170 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1171 }; 1172 1173 /// RAII object used to optionally suppress diagnostics and side-effects from 1174 /// a speculative evaluation. 1175 class SpeculativeEvaluationRAII { 1176 EvalInfo *Info = nullptr; 1177 Expr::EvalStatus OldStatus; 1178 unsigned OldSpeculativeEvaluationDepth; 1179 1180 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1181 Info = Other.Info; 1182 OldStatus = Other.OldStatus; 1183 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1184 Other.Info = nullptr; 1185 } 1186 1187 void maybeRestoreState() { 1188 if (!Info) 1189 return; 1190 1191 Info->EvalStatus = OldStatus; 1192 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1193 } 1194 1195 public: 1196 SpeculativeEvaluationRAII() = default; 1197 1198 SpeculativeEvaluationRAII( 1199 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1200 : Info(&Info), OldStatus(Info.EvalStatus), 1201 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1202 Info.EvalStatus.Diag = NewDiag; 1203 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1204 } 1205 1206 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1207 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1208 moveFromAndCancel(std::move(Other)); 1209 } 1210 1211 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1212 maybeRestoreState(); 1213 moveFromAndCancel(std::move(Other)); 1214 return *this; 1215 } 1216 1217 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1218 }; 1219 1220 /// RAII object wrapping a full-expression or block scope, and handling 1221 /// the ending of the lifetime of temporaries created within it. 1222 template<bool IsFullExpression> 1223 class ScopeRAII { 1224 EvalInfo &Info; 1225 unsigned OldStackSize; 1226 public: 1227 ScopeRAII(EvalInfo &Info) 1228 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1229 // Push a new temporary version. This is needed to distinguish between 1230 // temporaries created in different iterations of a loop. 1231 Info.CurrentCall->pushTempVersion(); 1232 } 1233 ~ScopeRAII() { 1234 // Body moved to a static method to encourage the compiler to inline away 1235 // instances of this class. 1236 cleanup(Info, OldStackSize); 1237 Info.CurrentCall->popTempVersion(); 1238 } 1239 private: 1240 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 1241 unsigned NewEnd = OldStackSize; 1242 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 1243 I != N; ++I) { 1244 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 1245 // Full-expression cleanup of a lifetime-extended temporary: nothing 1246 // to do, just move this cleanup to the right place in the stack. 1247 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 1248 ++NewEnd; 1249 } else { 1250 // End the lifetime of the object. 1251 Info.CleanupStack[I].endLifetime(); 1252 } 1253 } 1254 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 1255 Info.CleanupStack.end()); 1256 } 1257 }; 1258 typedef ScopeRAII<false> BlockScopeRAII; 1259 typedef ScopeRAII<true> FullExpressionRAII; 1260 } 1261 1262 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1263 CheckSubobjectKind CSK) { 1264 if (Invalid) 1265 return false; 1266 if (isOnePastTheEnd()) { 1267 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1268 << CSK; 1269 setInvalid(); 1270 return false; 1271 } 1272 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1273 // must actually be at least one array element; even a VLA cannot have a 1274 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1275 return true; 1276 } 1277 1278 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1279 const Expr *E) { 1280 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1281 // Do not set the designator as invalid: we can represent this situation, 1282 // and correct handling of __builtin_object_size requires us to do so. 1283 } 1284 1285 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1286 const Expr *E, 1287 const APSInt &N) { 1288 // If we're complaining, we must be able to statically determine the size of 1289 // the most derived array. 1290 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1291 Info.CCEDiag(E, diag::note_constexpr_array_index) 1292 << N << /*array*/ 0 1293 << static_cast<unsigned>(getMostDerivedArraySize()); 1294 else 1295 Info.CCEDiag(E, diag::note_constexpr_array_index) 1296 << N << /*non-array*/ 1; 1297 setInvalid(); 1298 } 1299 1300 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1301 const FunctionDecl *Callee, const LValue *This, 1302 APValue *Arguments) 1303 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1304 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1305 Info.CurrentCall = this; 1306 ++Info.CallStackDepth; 1307 } 1308 1309 CallStackFrame::~CallStackFrame() { 1310 assert(Info.CurrentCall == this && "calls retired out of order"); 1311 --Info.CallStackDepth; 1312 Info.CurrentCall = Caller; 1313 } 1314 1315 APValue &CallStackFrame::createTemporary(const void *Key, 1316 bool IsLifetimeExtended) { 1317 unsigned Version = Info.CurrentCall->getTempVersion(); 1318 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1319 assert(Result.isAbsent() && "temporary created multiple times"); 1320 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 1321 return Result; 1322 } 1323 1324 static void describeCall(CallStackFrame *Frame, raw_ostream &Out); 1325 1326 void EvalInfo::addCallStack(unsigned Limit) { 1327 // Determine which calls to skip, if any. 1328 unsigned ActiveCalls = CallStackDepth - 1; 1329 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 1330 if (Limit && Limit < ActiveCalls) { 1331 SkipStart = Limit / 2 + Limit % 2; 1332 SkipEnd = ActiveCalls - Limit / 2; 1333 } 1334 1335 // Walk the call stack and add the diagnostics. 1336 unsigned CallIdx = 0; 1337 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 1338 Frame = Frame->Caller, ++CallIdx) { 1339 // Skip this call? 1340 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 1341 if (CallIdx == SkipStart) { 1342 // Note that we're skipping calls. 1343 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 1344 << unsigned(ActiveCalls - Limit); 1345 } 1346 continue; 1347 } 1348 1349 // Use a different note for an inheriting constructor, because from the 1350 // user's perspective it's not really a function at all. 1351 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) { 1352 if (CD->isInheritingConstructor()) { 1353 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here) 1354 << CD->getParent(); 1355 continue; 1356 } 1357 } 1358 1359 SmallVector<char, 128> Buffer; 1360 llvm::raw_svector_ostream Out(Buffer); 1361 describeCall(Frame, Out); 1362 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 1363 } 1364 } 1365 1366 /// Kinds of access we can perform on an object, for diagnostics. Note that 1367 /// we consider a member function call to be a kind of access, even though 1368 /// it is not formally an access of the object, because it has (largely) the 1369 /// same set of semantic restrictions. 1370 enum AccessKinds { 1371 AK_Read, 1372 AK_Assign, 1373 AK_Increment, 1374 AK_Decrement, 1375 AK_MemberCall, 1376 AK_DynamicCast, 1377 AK_TypeId, 1378 }; 1379 1380 static bool isModification(AccessKinds AK) { 1381 switch (AK) { 1382 case AK_Read: 1383 case AK_MemberCall: 1384 case AK_DynamicCast: 1385 case AK_TypeId: 1386 return false; 1387 case AK_Assign: 1388 case AK_Increment: 1389 case AK_Decrement: 1390 return true; 1391 } 1392 llvm_unreachable("unknown access kind"); 1393 } 1394 1395 /// Is this an access per the C++ definition? 1396 static bool isFormalAccess(AccessKinds AK) { 1397 return AK == AK_Read || isModification(AK); 1398 } 1399 1400 namespace { 1401 struct ComplexValue { 1402 private: 1403 bool IsInt; 1404 1405 public: 1406 APSInt IntReal, IntImag; 1407 APFloat FloatReal, FloatImag; 1408 1409 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1410 1411 void makeComplexFloat() { IsInt = false; } 1412 bool isComplexFloat() const { return !IsInt; } 1413 APFloat &getComplexFloatReal() { return FloatReal; } 1414 APFloat &getComplexFloatImag() { return FloatImag; } 1415 1416 void makeComplexInt() { IsInt = true; } 1417 bool isComplexInt() const { return IsInt; } 1418 APSInt &getComplexIntReal() { return IntReal; } 1419 APSInt &getComplexIntImag() { return IntImag; } 1420 1421 void moveInto(APValue &v) const { 1422 if (isComplexFloat()) 1423 v = APValue(FloatReal, FloatImag); 1424 else 1425 v = APValue(IntReal, IntImag); 1426 } 1427 void setFrom(const APValue &v) { 1428 assert(v.isComplexFloat() || v.isComplexInt()); 1429 if (v.isComplexFloat()) { 1430 makeComplexFloat(); 1431 FloatReal = v.getComplexFloatReal(); 1432 FloatImag = v.getComplexFloatImag(); 1433 } else { 1434 makeComplexInt(); 1435 IntReal = v.getComplexIntReal(); 1436 IntImag = v.getComplexIntImag(); 1437 } 1438 } 1439 }; 1440 1441 struct LValue { 1442 APValue::LValueBase Base; 1443 CharUnits Offset; 1444 SubobjectDesignator Designator; 1445 bool IsNullPtr : 1; 1446 bool InvalidBase : 1; 1447 1448 const APValue::LValueBase getLValueBase() const { return Base; } 1449 CharUnits &getLValueOffset() { return Offset; } 1450 const CharUnits &getLValueOffset() const { return Offset; } 1451 SubobjectDesignator &getLValueDesignator() { return Designator; } 1452 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1453 bool isNullPointer() const { return IsNullPtr;} 1454 1455 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1456 unsigned getLValueVersion() const { return Base.getVersion(); } 1457 1458 void moveInto(APValue &V) const { 1459 if (Designator.Invalid) 1460 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1461 else { 1462 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1463 V = APValue(Base, Offset, Designator.Entries, 1464 Designator.IsOnePastTheEnd, IsNullPtr); 1465 } 1466 } 1467 void setFrom(ASTContext &Ctx, const APValue &V) { 1468 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1469 Base = V.getLValueBase(); 1470 Offset = V.getLValueOffset(); 1471 InvalidBase = false; 1472 Designator = SubobjectDesignator(Ctx, V); 1473 IsNullPtr = V.isNullPointer(); 1474 } 1475 1476 void set(APValue::LValueBase B, bool BInvalid = false) { 1477 #ifndef NDEBUG 1478 // We only allow a few types of invalid bases. Enforce that here. 1479 if (BInvalid) { 1480 const auto *E = B.get<const Expr *>(); 1481 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1482 "Unexpected type of invalid base"); 1483 } 1484 #endif 1485 1486 Base = B; 1487 Offset = CharUnits::fromQuantity(0); 1488 InvalidBase = BInvalid; 1489 Designator = SubobjectDesignator(getType(B)); 1490 IsNullPtr = false; 1491 } 1492 1493 void setNull(QualType PointerTy, uint64_t TargetVal) { 1494 Base = (Expr *)nullptr; 1495 Offset = CharUnits::fromQuantity(TargetVal); 1496 InvalidBase = false; 1497 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1498 IsNullPtr = true; 1499 } 1500 1501 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1502 set(B, true); 1503 } 1504 1505 private: 1506 // Check that this LValue is not based on a null pointer. If it is, produce 1507 // a diagnostic and mark the designator as invalid. 1508 template <typename GenDiagType> 1509 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1510 if (Designator.Invalid) 1511 return false; 1512 if (IsNullPtr) { 1513 GenDiag(); 1514 Designator.setInvalid(); 1515 return false; 1516 } 1517 return true; 1518 } 1519 1520 public: 1521 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1522 CheckSubobjectKind CSK) { 1523 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1524 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1525 }); 1526 } 1527 1528 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1529 AccessKinds AK) { 1530 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1531 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1532 }); 1533 } 1534 1535 // Check this LValue refers to an object. If not, set the designator to be 1536 // invalid and emit a diagnostic. 1537 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1538 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1539 Designator.checkSubobject(Info, E, CSK); 1540 } 1541 1542 void addDecl(EvalInfo &Info, const Expr *E, 1543 const Decl *D, bool Virtual = false) { 1544 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1545 Designator.addDeclUnchecked(D, Virtual); 1546 } 1547 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1548 if (!Designator.Entries.empty()) { 1549 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1550 Designator.setInvalid(); 1551 return; 1552 } 1553 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1554 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1555 Designator.FirstEntryIsAnUnsizedArray = true; 1556 Designator.addUnsizedArrayUnchecked(ElemTy); 1557 } 1558 } 1559 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1560 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1561 Designator.addArrayUnchecked(CAT); 1562 } 1563 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1564 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1565 Designator.addComplexUnchecked(EltTy, Imag); 1566 } 1567 void clearIsNullPointer() { 1568 IsNullPtr = false; 1569 } 1570 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1571 const APSInt &Index, CharUnits ElementSize) { 1572 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1573 // but we're not required to diagnose it and it's valid in C++.) 1574 if (!Index) 1575 return; 1576 1577 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1578 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1579 // offsets. 1580 uint64_t Offset64 = Offset.getQuantity(); 1581 uint64_t ElemSize64 = ElementSize.getQuantity(); 1582 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1583 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1584 1585 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1586 Designator.adjustIndex(Info, E, Index); 1587 clearIsNullPointer(); 1588 } 1589 void adjustOffset(CharUnits N) { 1590 Offset += N; 1591 if (N.getQuantity()) 1592 clearIsNullPointer(); 1593 } 1594 }; 1595 1596 struct MemberPtr { 1597 MemberPtr() {} 1598 explicit MemberPtr(const ValueDecl *Decl) : 1599 DeclAndIsDerivedMember(Decl, false), Path() {} 1600 1601 /// The member or (direct or indirect) field referred to by this member 1602 /// pointer, or 0 if this is a null member pointer. 1603 const ValueDecl *getDecl() const { 1604 return DeclAndIsDerivedMember.getPointer(); 1605 } 1606 /// Is this actually a member of some type derived from the relevant class? 1607 bool isDerivedMember() const { 1608 return DeclAndIsDerivedMember.getInt(); 1609 } 1610 /// Get the class which the declaration actually lives in. 1611 const CXXRecordDecl *getContainingRecord() const { 1612 return cast<CXXRecordDecl>( 1613 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1614 } 1615 1616 void moveInto(APValue &V) const { 1617 V = APValue(getDecl(), isDerivedMember(), Path); 1618 } 1619 void setFrom(const APValue &V) { 1620 assert(V.isMemberPointer()); 1621 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1622 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1623 Path.clear(); 1624 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1625 Path.insert(Path.end(), P.begin(), P.end()); 1626 } 1627 1628 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1629 /// whether the member is a member of some class derived from the class type 1630 /// of the member pointer. 1631 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1632 /// Path - The path of base/derived classes from the member declaration's 1633 /// class (exclusive) to the class type of the member pointer (inclusive). 1634 SmallVector<const CXXRecordDecl*, 4> Path; 1635 1636 /// Perform a cast towards the class of the Decl (either up or down the 1637 /// hierarchy). 1638 bool castBack(const CXXRecordDecl *Class) { 1639 assert(!Path.empty()); 1640 const CXXRecordDecl *Expected; 1641 if (Path.size() >= 2) 1642 Expected = Path[Path.size() - 2]; 1643 else 1644 Expected = getContainingRecord(); 1645 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1646 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1647 // if B does not contain the original member and is not a base or 1648 // derived class of the class containing the original member, the result 1649 // of the cast is undefined. 1650 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1651 // (D::*). We consider that to be a language defect. 1652 return false; 1653 } 1654 Path.pop_back(); 1655 return true; 1656 } 1657 /// Perform a base-to-derived member pointer cast. 1658 bool castToDerived(const CXXRecordDecl *Derived) { 1659 if (!getDecl()) 1660 return true; 1661 if (!isDerivedMember()) { 1662 Path.push_back(Derived); 1663 return true; 1664 } 1665 if (!castBack(Derived)) 1666 return false; 1667 if (Path.empty()) 1668 DeclAndIsDerivedMember.setInt(false); 1669 return true; 1670 } 1671 /// Perform a derived-to-base member pointer cast. 1672 bool castToBase(const CXXRecordDecl *Base) { 1673 if (!getDecl()) 1674 return true; 1675 if (Path.empty()) 1676 DeclAndIsDerivedMember.setInt(true); 1677 if (isDerivedMember()) { 1678 Path.push_back(Base); 1679 return true; 1680 } 1681 return castBack(Base); 1682 } 1683 }; 1684 1685 /// Compare two member pointers, which are assumed to be of the same type. 1686 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1687 if (!LHS.getDecl() || !RHS.getDecl()) 1688 return !LHS.getDecl() && !RHS.getDecl(); 1689 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1690 return false; 1691 return LHS.Path == RHS.Path; 1692 } 1693 } 1694 1695 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1696 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1697 const LValue &This, const Expr *E, 1698 bool AllowNonLiteralTypes = false); 1699 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1700 bool InvalidBaseOK = false); 1701 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1702 bool InvalidBaseOK = false); 1703 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1704 EvalInfo &Info); 1705 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1706 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1707 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1708 EvalInfo &Info); 1709 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1710 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1711 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1712 EvalInfo &Info); 1713 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1714 1715 /// Evaluate an integer or fixed point expression into an APResult. 1716 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1717 EvalInfo &Info); 1718 1719 /// Evaluate only a fixed point expression into an APResult. 1720 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1721 EvalInfo &Info); 1722 1723 //===----------------------------------------------------------------------===// 1724 // Misc utilities 1725 //===----------------------------------------------------------------------===// 1726 1727 /// A helper function to create a temporary and set an LValue. 1728 template <class KeyTy> 1729 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended, 1730 LValue &LV, CallStackFrame &Frame) { 1731 LV.set({Key, Frame.Info.CurrentCall->Index, 1732 Frame.Info.CurrentCall->getTempVersion()}); 1733 return Frame.createTemporary(Key, IsLifetimeExtended); 1734 } 1735 1736 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1737 /// preserving its value (by extending by up to one bit as needed). 1738 static void negateAsSigned(APSInt &Int) { 1739 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1740 Int = Int.extend(Int.getBitWidth() + 1); 1741 Int.setIsSigned(true); 1742 } 1743 Int = -Int; 1744 } 1745 1746 /// Produce a string describing the given constexpr call. 1747 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) { 1748 unsigned ArgIndex = 0; 1749 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 1750 !isa<CXXConstructorDecl>(Frame->Callee) && 1751 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 1752 1753 if (!IsMemberCall) 1754 Out << *Frame->Callee << '('; 1755 1756 if (Frame->This && IsMemberCall) { 1757 APValue Val; 1758 Frame->This->moveInto(Val); 1759 Val.printPretty(Out, Frame->Info.Ctx, 1760 Frame->This->Designator.MostDerivedType); 1761 // FIXME: Add parens around Val if needed. 1762 Out << "->" << *Frame->Callee << '('; 1763 IsMemberCall = false; 1764 } 1765 1766 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 1767 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 1768 if (ArgIndex > (unsigned)IsMemberCall) 1769 Out << ", "; 1770 1771 const ParmVarDecl *Param = *I; 1772 const APValue &Arg = Frame->Arguments[ArgIndex]; 1773 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 1774 1775 if (ArgIndex == 0 && IsMemberCall) 1776 Out << "->" << *Frame->Callee << '('; 1777 } 1778 1779 Out << ')'; 1780 } 1781 1782 /// Evaluate an expression to see if it had side-effects, and discard its 1783 /// result. 1784 /// \return \c true if the caller should keep evaluating. 1785 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1786 APValue Scratch; 1787 if (!Evaluate(Scratch, Info, E)) 1788 // We don't need the value, but we might have skipped a side effect here. 1789 return Info.noteSideEffect(); 1790 return true; 1791 } 1792 1793 /// Should this call expression be treated as a string literal? 1794 static bool IsStringLiteralCall(const CallExpr *E) { 1795 unsigned Builtin = E->getBuiltinCallee(); 1796 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1797 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1798 } 1799 1800 static bool IsGlobalLValue(APValue::LValueBase B) { 1801 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1802 // constant expression of pointer type that evaluates to... 1803 1804 // ... a null pointer value, or a prvalue core constant expression of type 1805 // std::nullptr_t. 1806 if (!B) return true; 1807 1808 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1809 // ... the address of an object with static storage duration, 1810 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1811 return VD->hasGlobalStorage(); 1812 // ... the address of a function, 1813 return isa<FunctionDecl>(D); 1814 } 1815 1816 if (B.is<TypeInfoLValue>()) 1817 return true; 1818 1819 const Expr *E = B.get<const Expr*>(); 1820 switch (E->getStmtClass()) { 1821 default: 1822 return false; 1823 case Expr::CompoundLiteralExprClass: { 1824 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1825 return CLE->isFileScope() && CLE->isLValue(); 1826 } 1827 case Expr::MaterializeTemporaryExprClass: 1828 // A materialized temporary might have been lifetime-extended to static 1829 // storage duration. 1830 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1831 // A string literal has static storage duration. 1832 case Expr::StringLiteralClass: 1833 case Expr::PredefinedExprClass: 1834 case Expr::ObjCStringLiteralClass: 1835 case Expr::ObjCEncodeExprClass: 1836 case Expr::CXXUuidofExprClass: 1837 return true; 1838 case Expr::ObjCBoxedExprClass: 1839 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1840 case Expr::CallExprClass: 1841 return IsStringLiteralCall(cast<CallExpr>(E)); 1842 // For GCC compatibility, &&label has static storage duration. 1843 case Expr::AddrLabelExprClass: 1844 return true; 1845 // A Block literal expression may be used as the initialization value for 1846 // Block variables at global or local static scope. 1847 case Expr::BlockExprClass: 1848 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1849 case Expr::ImplicitValueInitExprClass: 1850 // FIXME: 1851 // We can never form an lvalue with an implicit value initialization as its 1852 // base through expression evaluation, so these only appear in one case: the 1853 // implicit variable declaration we invent when checking whether a constexpr 1854 // constructor can produce a constant expression. We must assume that such 1855 // an expression might be a global lvalue. 1856 return true; 1857 } 1858 } 1859 1860 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1861 return LVal.Base.dyn_cast<const ValueDecl*>(); 1862 } 1863 1864 static bool IsLiteralLValue(const LValue &Value) { 1865 if (Value.getLValueCallIndex()) 1866 return false; 1867 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1868 return E && !isa<MaterializeTemporaryExpr>(E); 1869 } 1870 1871 static bool IsWeakLValue(const LValue &Value) { 1872 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1873 return Decl && Decl->isWeak(); 1874 } 1875 1876 static bool isZeroSized(const LValue &Value) { 1877 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1878 if (Decl && isa<VarDecl>(Decl)) { 1879 QualType Ty = Decl->getType(); 1880 if (Ty->isArrayType()) 1881 return Ty->isIncompleteType() || 1882 Decl->getASTContext().getTypeSize(Ty) == 0; 1883 } 1884 return false; 1885 } 1886 1887 static bool HasSameBase(const LValue &A, const LValue &B) { 1888 if (!A.getLValueBase()) 1889 return !B.getLValueBase(); 1890 if (!B.getLValueBase()) 1891 return false; 1892 1893 if (A.getLValueBase().getOpaqueValue() != 1894 B.getLValueBase().getOpaqueValue()) { 1895 const Decl *ADecl = GetLValueBaseDecl(A); 1896 if (!ADecl) 1897 return false; 1898 const Decl *BDecl = GetLValueBaseDecl(B); 1899 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1900 return false; 1901 } 1902 1903 return IsGlobalLValue(A.getLValueBase()) || 1904 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1905 A.getLValueVersion() == B.getLValueVersion()); 1906 } 1907 1908 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1909 assert(Base && "no location for a null lvalue"); 1910 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1911 if (VD) 1912 Info.Note(VD->getLocation(), diag::note_declared_at); 1913 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 1914 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 1915 // We have no information to show for a typeid(T) object. 1916 } 1917 1918 /// Check that this reference or pointer core constant expression is a valid 1919 /// value for an address or reference constant expression. Return true if we 1920 /// can fold this expression, whether or not it's a constant expression. 1921 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1922 QualType Type, const LValue &LVal, 1923 Expr::ConstExprUsage Usage) { 1924 bool IsReferenceType = Type->isReferenceType(); 1925 1926 APValue::LValueBase Base = LVal.getLValueBase(); 1927 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1928 1929 // Check that the object is a global. Note that the fake 'this' object we 1930 // manufacture when checking potential constant expressions is conservatively 1931 // assumed to be global here. 1932 if (!IsGlobalLValue(Base)) { 1933 if (Info.getLangOpts().CPlusPlus11) { 1934 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1935 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1936 << IsReferenceType << !Designator.Entries.empty() 1937 << !!VD << VD; 1938 NoteLValueLocation(Info, Base); 1939 } else { 1940 Info.FFDiag(Loc); 1941 } 1942 // Don't allow references to temporaries to escape. 1943 return false; 1944 } 1945 assert((Info.checkingPotentialConstantExpression() || 1946 LVal.getLValueCallIndex() == 0) && 1947 "have call index for global lvalue"); 1948 1949 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1950 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1951 // Check if this is a thread-local variable. 1952 if (Var->getTLSKind()) 1953 return false; 1954 1955 // A dllimport variable never acts like a constant. 1956 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 1957 return false; 1958 } 1959 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1960 // __declspec(dllimport) must be handled very carefully: 1961 // We must never initialize an expression with the thunk in C++. 1962 // Doing otherwise would allow the same id-expression to yield 1963 // different addresses for the same function in different translation 1964 // units. However, this means that we must dynamically initialize the 1965 // expression with the contents of the import address table at runtime. 1966 // 1967 // The C language has no notion of ODR; furthermore, it has no notion of 1968 // dynamic initialization. This means that we are permitted to 1969 // perform initialization with the address of the thunk. 1970 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 1971 FD->hasAttr<DLLImportAttr>()) 1972 return false; 1973 } 1974 } 1975 1976 // Allow address constant expressions to be past-the-end pointers. This is 1977 // an extension: the standard requires them to point to an object. 1978 if (!IsReferenceType) 1979 return true; 1980 1981 // A reference constant expression must refer to an object. 1982 if (!Base) { 1983 // FIXME: diagnostic 1984 Info.CCEDiag(Loc); 1985 return true; 1986 } 1987 1988 // Does this refer one past the end of some object? 1989 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1990 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1991 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1992 << !Designator.Entries.empty() << !!VD << VD; 1993 NoteLValueLocation(Info, Base); 1994 } 1995 1996 return true; 1997 } 1998 1999 /// Member pointers are constant expressions unless they point to a 2000 /// non-virtual dllimport member function. 2001 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2002 SourceLocation Loc, 2003 QualType Type, 2004 const APValue &Value, 2005 Expr::ConstExprUsage Usage) { 2006 const ValueDecl *Member = Value.getMemberPointerDecl(); 2007 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2008 if (!FD) 2009 return true; 2010 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2011 !FD->hasAttr<DLLImportAttr>(); 2012 } 2013 2014 /// Check that this core constant expression is of literal type, and if not, 2015 /// produce an appropriate diagnostic. 2016 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2017 const LValue *This = nullptr) { 2018 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2019 return true; 2020 2021 // C++1y: A constant initializer for an object o [...] may also invoke 2022 // constexpr constructors for o and its subobjects even if those objects 2023 // are of non-literal class types. 2024 // 2025 // C++11 missed this detail for aggregates, so classes like this: 2026 // struct foo_t { union { int i; volatile int j; } u; }; 2027 // are not (obviously) initializable like so: 2028 // __attribute__((__require_constant_initialization__)) 2029 // static const foo_t x = {{0}}; 2030 // because "i" is a subobject with non-literal initialization (due to the 2031 // volatile member of the union). See: 2032 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2033 // Therefore, we use the C++1y behavior. 2034 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2035 return true; 2036 2037 // Prvalue constant expressions must be of literal types. 2038 if (Info.getLangOpts().CPlusPlus11) 2039 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2040 << E->getType(); 2041 else 2042 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2043 return false; 2044 } 2045 2046 /// Check that this core constant expression value is a valid value for a 2047 /// constant expression. If not, report an appropriate diagnostic. Does not 2048 /// check that the expression is of literal type. 2049 static bool 2050 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2051 const APValue &Value, 2052 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen, 2053 SourceLocation SubobjectLoc = SourceLocation()) { 2054 if (!Value.hasValue()) { 2055 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2056 << true << Type; 2057 if (SubobjectLoc.isValid()) 2058 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2059 return false; 2060 } 2061 2062 // We allow _Atomic(T) to be initialized from anything that T can be 2063 // initialized from. 2064 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2065 Type = AT->getValueType(); 2066 2067 // Core issue 1454: For a literal constant expression of array or class type, 2068 // each subobject of its value shall have been initialized by a constant 2069 // expression. 2070 if (Value.isArray()) { 2071 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2072 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2073 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 2074 Value.getArrayInitializedElt(I), Usage, 2075 SubobjectLoc)) 2076 return false; 2077 } 2078 if (!Value.hasArrayFiller()) 2079 return true; 2080 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(), 2081 Usage, SubobjectLoc); 2082 } 2083 if (Value.isUnion() && Value.getUnionField()) { 2084 return CheckConstantExpression(Info, DiagLoc, 2085 Value.getUnionField()->getType(), 2086 Value.getUnionValue(), Usage, 2087 Value.getUnionField()->getLocation()); 2088 } 2089 if (Value.isStruct()) { 2090 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2091 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2092 unsigned BaseIndex = 0; 2093 for (const CXXBaseSpecifier &BS : CD->bases()) { 2094 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(), 2095 Value.getStructBase(BaseIndex), Usage, 2096 BS.getBeginLoc())) 2097 return false; 2098 ++BaseIndex; 2099 } 2100 } 2101 for (const auto *I : RD->fields()) { 2102 if (I->isUnnamedBitfield()) 2103 continue; 2104 2105 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 2106 Value.getStructField(I->getFieldIndex()), 2107 Usage, I->getLocation())) 2108 return false; 2109 } 2110 } 2111 2112 if (Value.isLValue()) { 2113 LValue LVal; 2114 LVal.setFrom(Info.Ctx, Value); 2115 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage); 2116 } 2117 2118 if (Value.isMemberPointer()) 2119 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2120 2121 // Everything else is fine. 2122 return true; 2123 } 2124 2125 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2126 // A null base expression indicates a null pointer. These are always 2127 // evaluatable, and they are false unless the offset is zero. 2128 if (!Value.getLValueBase()) { 2129 Result = !Value.getLValueOffset().isZero(); 2130 return true; 2131 } 2132 2133 // We have a non-null base. These are generally known to be true, but if it's 2134 // a weak declaration it can be null at runtime. 2135 Result = true; 2136 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2137 return !Decl || !Decl->isWeak(); 2138 } 2139 2140 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2141 switch (Val.getKind()) { 2142 case APValue::None: 2143 case APValue::Indeterminate: 2144 return false; 2145 case APValue::Int: 2146 Result = Val.getInt().getBoolValue(); 2147 return true; 2148 case APValue::FixedPoint: 2149 Result = Val.getFixedPoint().getBoolValue(); 2150 return true; 2151 case APValue::Float: 2152 Result = !Val.getFloat().isZero(); 2153 return true; 2154 case APValue::ComplexInt: 2155 Result = Val.getComplexIntReal().getBoolValue() || 2156 Val.getComplexIntImag().getBoolValue(); 2157 return true; 2158 case APValue::ComplexFloat: 2159 Result = !Val.getComplexFloatReal().isZero() || 2160 !Val.getComplexFloatImag().isZero(); 2161 return true; 2162 case APValue::LValue: 2163 return EvalPointerValueAsBool(Val, Result); 2164 case APValue::MemberPointer: 2165 Result = Val.getMemberPointerDecl(); 2166 return true; 2167 case APValue::Vector: 2168 case APValue::Array: 2169 case APValue::Struct: 2170 case APValue::Union: 2171 case APValue::AddrLabelDiff: 2172 return false; 2173 } 2174 2175 llvm_unreachable("unknown APValue kind"); 2176 } 2177 2178 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2179 EvalInfo &Info) { 2180 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2181 APValue Val; 2182 if (!Evaluate(Val, Info, E)) 2183 return false; 2184 return HandleConversionToBool(Val, Result); 2185 } 2186 2187 template<typename T> 2188 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2189 const T &SrcValue, QualType DestType) { 2190 Info.CCEDiag(E, diag::note_constexpr_overflow) 2191 << SrcValue << DestType; 2192 return Info.noteUndefinedBehavior(); 2193 } 2194 2195 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2196 QualType SrcType, const APFloat &Value, 2197 QualType DestType, APSInt &Result) { 2198 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2199 // Determine whether we are converting to unsigned or signed. 2200 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2201 2202 Result = APSInt(DestWidth, !DestSigned); 2203 bool ignored; 2204 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2205 & APFloat::opInvalidOp) 2206 return HandleOverflow(Info, E, Value, DestType); 2207 return true; 2208 } 2209 2210 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2211 QualType SrcType, QualType DestType, 2212 APFloat &Result) { 2213 APFloat Value = Result; 2214 bool ignored; 2215 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2216 APFloat::rmNearestTiesToEven, &ignored); 2217 return true; 2218 } 2219 2220 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2221 QualType DestType, QualType SrcType, 2222 const APSInt &Value) { 2223 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2224 // Figure out if this is a truncate, extend or noop cast. 2225 // If the input is signed, do a sign extend, noop, or truncate. 2226 APSInt Result = Value.extOrTrunc(DestWidth); 2227 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2228 if (DestType->isBooleanType()) 2229 Result = Value.getBoolValue(); 2230 return Result; 2231 } 2232 2233 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2234 QualType SrcType, const APSInt &Value, 2235 QualType DestType, APFloat &Result) { 2236 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2237 Result.convertFromAPInt(Value, Value.isSigned(), 2238 APFloat::rmNearestTiesToEven); 2239 return true; 2240 } 2241 2242 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2243 APValue &Value, const FieldDecl *FD) { 2244 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2245 2246 if (!Value.isInt()) { 2247 // Trying to store a pointer-cast-to-integer into a bitfield. 2248 // FIXME: In this case, we should provide the diagnostic for casting 2249 // a pointer to an integer. 2250 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2251 Info.FFDiag(E); 2252 return false; 2253 } 2254 2255 APSInt &Int = Value.getInt(); 2256 unsigned OldBitWidth = Int.getBitWidth(); 2257 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2258 if (NewBitWidth < OldBitWidth) 2259 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2260 return true; 2261 } 2262 2263 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2264 llvm::APInt &Res) { 2265 APValue SVal; 2266 if (!Evaluate(SVal, Info, E)) 2267 return false; 2268 if (SVal.isInt()) { 2269 Res = SVal.getInt(); 2270 return true; 2271 } 2272 if (SVal.isFloat()) { 2273 Res = SVal.getFloat().bitcastToAPInt(); 2274 return true; 2275 } 2276 if (SVal.isVector()) { 2277 QualType VecTy = E->getType(); 2278 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2279 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2280 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2281 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2282 Res = llvm::APInt::getNullValue(VecSize); 2283 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2284 APValue &Elt = SVal.getVectorElt(i); 2285 llvm::APInt EltAsInt; 2286 if (Elt.isInt()) { 2287 EltAsInt = Elt.getInt(); 2288 } else if (Elt.isFloat()) { 2289 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2290 } else { 2291 // Don't try to handle vectors of anything other than int or float 2292 // (not sure if it's possible to hit this case). 2293 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2294 return false; 2295 } 2296 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2297 if (BigEndian) 2298 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2299 else 2300 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2301 } 2302 return true; 2303 } 2304 // Give up if the input isn't an int, float, or vector. For example, we 2305 // reject "(v4i16)(intptr_t)&a". 2306 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2307 return false; 2308 } 2309 2310 /// Perform the given integer operation, which is known to need at most BitWidth 2311 /// bits, and check for overflow in the original type (if that type was not an 2312 /// unsigned type). 2313 template<typename Operation> 2314 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2315 const APSInt &LHS, const APSInt &RHS, 2316 unsigned BitWidth, Operation Op, 2317 APSInt &Result) { 2318 if (LHS.isUnsigned()) { 2319 Result = Op(LHS, RHS); 2320 return true; 2321 } 2322 2323 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2324 Result = Value.trunc(LHS.getBitWidth()); 2325 if (Result.extend(BitWidth) != Value) { 2326 if (Info.checkingForOverflow()) 2327 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2328 diag::warn_integer_constant_overflow) 2329 << Result.toString(10) << E->getType(); 2330 else 2331 return HandleOverflow(Info, E, Value, E->getType()); 2332 } 2333 return true; 2334 } 2335 2336 /// Perform the given binary integer operation. 2337 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2338 BinaryOperatorKind Opcode, APSInt RHS, 2339 APSInt &Result) { 2340 switch (Opcode) { 2341 default: 2342 Info.FFDiag(E); 2343 return false; 2344 case BO_Mul: 2345 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2346 std::multiplies<APSInt>(), Result); 2347 case BO_Add: 2348 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2349 std::plus<APSInt>(), Result); 2350 case BO_Sub: 2351 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2352 std::minus<APSInt>(), Result); 2353 case BO_And: Result = LHS & RHS; return true; 2354 case BO_Xor: Result = LHS ^ RHS; return true; 2355 case BO_Or: Result = LHS | RHS; return true; 2356 case BO_Div: 2357 case BO_Rem: 2358 if (RHS == 0) { 2359 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2360 return false; 2361 } 2362 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2363 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2364 // this operation and gives the two's complement result. 2365 if (RHS.isNegative() && RHS.isAllOnesValue() && 2366 LHS.isSigned() && LHS.isMinSignedValue()) 2367 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2368 E->getType()); 2369 return true; 2370 case BO_Shl: { 2371 if (Info.getLangOpts().OpenCL) 2372 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2373 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2374 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2375 RHS.isUnsigned()); 2376 else if (RHS.isSigned() && RHS.isNegative()) { 2377 // During constant-folding, a negative shift is an opposite shift. Such 2378 // a shift is not a constant expression. 2379 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2380 RHS = -RHS; 2381 goto shift_right; 2382 } 2383 shift_left: 2384 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2385 // the shifted type. 2386 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2387 if (SA != RHS) { 2388 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2389 << RHS << E->getType() << LHS.getBitWidth(); 2390 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) { 2391 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2392 // operand, and must not overflow the corresponding unsigned type. 2393 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2394 // E1 x 2^E2 module 2^N. 2395 if (LHS.isNegative()) 2396 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2397 else if (LHS.countLeadingZeros() < SA) 2398 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2399 } 2400 Result = LHS << SA; 2401 return true; 2402 } 2403 case BO_Shr: { 2404 if (Info.getLangOpts().OpenCL) 2405 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2406 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2407 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2408 RHS.isUnsigned()); 2409 else if (RHS.isSigned() && RHS.isNegative()) { 2410 // During constant-folding, a negative shift is an opposite shift. Such a 2411 // shift is not a constant expression. 2412 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2413 RHS = -RHS; 2414 goto shift_left; 2415 } 2416 shift_right: 2417 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2418 // shifted type. 2419 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2420 if (SA != RHS) 2421 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2422 << RHS << E->getType() << LHS.getBitWidth(); 2423 Result = LHS >> SA; 2424 return true; 2425 } 2426 2427 case BO_LT: Result = LHS < RHS; return true; 2428 case BO_GT: Result = LHS > RHS; return true; 2429 case BO_LE: Result = LHS <= RHS; return true; 2430 case BO_GE: Result = LHS >= RHS; return true; 2431 case BO_EQ: Result = LHS == RHS; return true; 2432 case BO_NE: Result = LHS != RHS; return true; 2433 case BO_Cmp: 2434 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2435 } 2436 } 2437 2438 /// Perform the given binary floating-point operation, in-place, on LHS. 2439 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2440 APFloat &LHS, BinaryOperatorKind Opcode, 2441 const APFloat &RHS) { 2442 switch (Opcode) { 2443 default: 2444 Info.FFDiag(E); 2445 return false; 2446 case BO_Mul: 2447 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2448 break; 2449 case BO_Add: 2450 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2451 break; 2452 case BO_Sub: 2453 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2454 break; 2455 case BO_Div: 2456 // [expr.mul]p4: 2457 // If the second operand of / or % is zero the behavior is undefined. 2458 if (RHS.isZero()) 2459 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2460 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2461 break; 2462 } 2463 2464 // [expr.pre]p4: 2465 // If during the evaluation of an expression, the result is not 2466 // mathematically defined [...], the behavior is undefined. 2467 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2468 if (LHS.isNaN()) { 2469 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2470 return Info.noteUndefinedBehavior(); 2471 } 2472 return true; 2473 } 2474 2475 /// Cast an lvalue referring to a base subobject to a derived class, by 2476 /// truncating the lvalue's path to the given length. 2477 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2478 const RecordDecl *TruncatedType, 2479 unsigned TruncatedElements) { 2480 SubobjectDesignator &D = Result.Designator; 2481 2482 // Check we actually point to a derived class object. 2483 if (TruncatedElements == D.Entries.size()) 2484 return true; 2485 assert(TruncatedElements >= D.MostDerivedPathLength && 2486 "not casting to a derived class"); 2487 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2488 return false; 2489 2490 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2491 const RecordDecl *RD = TruncatedType; 2492 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2493 if (RD->isInvalidDecl()) return false; 2494 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2495 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2496 if (isVirtualBaseClass(D.Entries[I])) 2497 Result.Offset -= Layout.getVBaseClassOffset(Base); 2498 else 2499 Result.Offset -= Layout.getBaseClassOffset(Base); 2500 RD = Base; 2501 } 2502 D.Entries.resize(TruncatedElements); 2503 return true; 2504 } 2505 2506 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2507 const CXXRecordDecl *Derived, 2508 const CXXRecordDecl *Base, 2509 const ASTRecordLayout *RL = nullptr) { 2510 if (!RL) { 2511 if (Derived->isInvalidDecl()) return false; 2512 RL = &Info.Ctx.getASTRecordLayout(Derived); 2513 } 2514 2515 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2516 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2517 return true; 2518 } 2519 2520 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2521 const CXXRecordDecl *DerivedDecl, 2522 const CXXBaseSpecifier *Base) { 2523 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2524 2525 if (!Base->isVirtual()) 2526 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2527 2528 SubobjectDesignator &D = Obj.Designator; 2529 if (D.Invalid) 2530 return false; 2531 2532 // Extract most-derived object and corresponding type. 2533 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2534 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2535 return false; 2536 2537 // Find the virtual base class. 2538 if (DerivedDecl->isInvalidDecl()) return false; 2539 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2540 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2541 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2542 return true; 2543 } 2544 2545 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2546 QualType Type, LValue &Result) { 2547 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2548 PathE = E->path_end(); 2549 PathI != PathE; ++PathI) { 2550 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2551 *PathI)) 2552 return false; 2553 Type = (*PathI)->getType(); 2554 } 2555 return true; 2556 } 2557 2558 /// Cast an lvalue referring to a derived class to a known base subobject. 2559 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2560 const CXXRecordDecl *DerivedRD, 2561 const CXXRecordDecl *BaseRD) { 2562 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2563 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2564 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2565 llvm_unreachable("Class must be derived from the passed in base class!"); 2566 2567 for (CXXBasePathElement &Elem : Paths.front()) 2568 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2569 return false; 2570 return true; 2571 } 2572 2573 /// Update LVal to refer to the given field, which must be a member of the type 2574 /// currently described by LVal. 2575 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2576 const FieldDecl *FD, 2577 const ASTRecordLayout *RL = nullptr) { 2578 if (!RL) { 2579 if (FD->getParent()->isInvalidDecl()) return false; 2580 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2581 } 2582 2583 unsigned I = FD->getFieldIndex(); 2584 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2585 LVal.addDecl(Info, E, FD); 2586 return true; 2587 } 2588 2589 /// Update LVal to refer to the given indirect field. 2590 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2591 LValue &LVal, 2592 const IndirectFieldDecl *IFD) { 2593 for (const auto *C : IFD->chain()) 2594 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2595 return false; 2596 return true; 2597 } 2598 2599 /// Get the size of the given type in char units. 2600 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2601 QualType Type, CharUnits &Size) { 2602 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2603 // extension. 2604 if (Type->isVoidType() || Type->isFunctionType()) { 2605 Size = CharUnits::One(); 2606 return true; 2607 } 2608 2609 if (Type->isDependentType()) { 2610 Info.FFDiag(Loc); 2611 return false; 2612 } 2613 2614 if (!Type->isConstantSizeType()) { 2615 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2616 // FIXME: Better diagnostic. 2617 Info.FFDiag(Loc); 2618 return false; 2619 } 2620 2621 Size = Info.Ctx.getTypeSizeInChars(Type); 2622 return true; 2623 } 2624 2625 /// Update a pointer value to model pointer arithmetic. 2626 /// \param Info - Information about the ongoing evaluation. 2627 /// \param E - The expression being evaluated, for diagnostic purposes. 2628 /// \param LVal - The pointer value to be updated. 2629 /// \param EltTy - The pointee type represented by LVal. 2630 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2631 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2632 LValue &LVal, QualType EltTy, 2633 APSInt Adjustment) { 2634 CharUnits SizeOfPointee; 2635 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2636 return false; 2637 2638 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2639 return true; 2640 } 2641 2642 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2643 LValue &LVal, QualType EltTy, 2644 int64_t Adjustment) { 2645 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2646 APSInt::get(Adjustment)); 2647 } 2648 2649 /// Update an lvalue to refer to a component of a complex number. 2650 /// \param Info - Information about the ongoing evaluation. 2651 /// \param LVal - The lvalue to be updated. 2652 /// \param EltTy - The complex number's component type. 2653 /// \param Imag - False for the real component, true for the imaginary. 2654 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2655 LValue &LVal, QualType EltTy, 2656 bool Imag) { 2657 if (Imag) { 2658 CharUnits SizeOfComponent; 2659 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2660 return false; 2661 LVal.Offset += SizeOfComponent; 2662 } 2663 LVal.addComplex(Info, E, EltTy, Imag); 2664 return true; 2665 } 2666 2667 /// Try to evaluate the initializer for a variable declaration. 2668 /// 2669 /// \param Info Information about the ongoing evaluation. 2670 /// \param E An expression to be used when printing diagnostics. 2671 /// \param VD The variable whose initializer should be obtained. 2672 /// \param Frame The frame in which the variable was created. Must be null 2673 /// if this variable is not local to the evaluation. 2674 /// \param Result Filled in with a pointer to the value of the variable. 2675 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2676 const VarDecl *VD, CallStackFrame *Frame, 2677 APValue *&Result, const LValue *LVal) { 2678 2679 // If this is a parameter to an active constexpr function call, perform 2680 // argument substitution. 2681 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2682 // Assume arguments of a potential constant expression are unknown 2683 // constant expressions. 2684 if (Info.checkingPotentialConstantExpression()) 2685 return false; 2686 if (!Frame || !Frame->Arguments) { 2687 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2688 return false; 2689 } 2690 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2691 return true; 2692 } 2693 2694 // If this is a local variable, dig out its value. 2695 if (Frame) { 2696 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 2697 : Frame->getCurrentTemporary(VD); 2698 if (!Result) { 2699 // Assume variables referenced within a lambda's call operator that were 2700 // not declared within the call operator are captures and during checking 2701 // of a potential constant expression, assume they are unknown constant 2702 // expressions. 2703 assert(isLambdaCallOperator(Frame->Callee) && 2704 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2705 "missing value for local variable"); 2706 if (Info.checkingPotentialConstantExpression()) 2707 return false; 2708 // FIXME: implement capture evaluation during constant expr evaluation. 2709 Info.FFDiag(E->getBeginLoc(), 2710 diag::note_unimplemented_constexpr_lambda_feature_ast) 2711 << "captures not currently allowed"; 2712 return false; 2713 } 2714 return true; 2715 } 2716 2717 // Dig out the initializer, and use the declaration which it's attached to. 2718 const Expr *Init = VD->getAnyInitializer(VD); 2719 if (!Init || Init->isValueDependent()) { 2720 // If we're checking a potential constant expression, the variable could be 2721 // initialized later. 2722 if (!Info.checkingPotentialConstantExpression()) 2723 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2724 return false; 2725 } 2726 2727 // If we're currently evaluating the initializer of this declaration, use that 2728 // in-flight value. 2729 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2730 Result = Info.EvaluatingDeclValue; 2731 return true; 2732 } 2733 2734 // Never evaluate the initializer of a weak variable. We can't be sure that 2735 // this is the definition which will be used. 2736 if (VD->isWeak()) { 2737 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2738 return false; 2739 } 2740 2741 // Check that we can fold the initializer. In C++, we will have already done 2742 // this in the cases where it matters for conformance. 2743 SmallVector<PartialDiagnosticAt, 8> Notes; 2744 if (!VD->evaluateValue(Notes)) { 2745 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2746 Notes.size() + 1) << VD; 2747 Info.Note(VD->getLocation(), diag::note_declared_at); 2748 Info.addNotes(Notes); 2749 return false; 2750 } else if (!VD->checkInitIsICE()) { 2751 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2752 Notes.size() + 1) << VD; 2753 Info.Note(VD->getLocation(), diag::note_declared_at); 2754 Info.addNotes(Notes); 2755 } 2756 2757 Result = VD->getEvaluatedValue(); 2758 return true; 2759 } 2760 2761 static bool IsConstNonVolatile(QualType T) { 2762 Qualifiers Quals = T.getQualifiers(); 2763 return Quals.hasConst() && !Quals.hasVolatile(); 2764 } 2765 2766 /// Get the base index of the given base class within an APValue representing 2767 /// the given derived class. 2768 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2769 const CXXRecordDecl *Base) { 2770 Base = Base->getCanonicalDecl(); 2771 unsigned Index = 0; 2772 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2773 E = Derived->bases_end(); I != E; ++I, ++Index) { 2774 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2775 return Index; 2776 } 2777 2778 llvm_unreachable("base class missing from derived class's bases list"); 2779 } 2780 2781 /// Extract the value of a character from a string literal. 2782 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2783 uint64_t Index) { 2784 assert(!isa<SourceLocExpr>(Lit) && 2785 "SourceLocExpr should have already been converted to a StringLiteral"); 2786 2787 // FIXME: Support MakeStringConstant 2788 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2789 std::string Str; 2790 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2791 assert(Index <= Str.size() && "Index too large"); 2792 return APSInt::getUnsigned(Str.c_str()[Index]); 2793 } 2794 2795 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2796 Lit = PE->getFunctionName(); 2797 const StringLiteral *S = cast<StringLiteral>(Lit); 2798 const ConstantArrayType *CAT = 2799 Info.Ctx.getAsConstantArrayType(S->getType()); 2800 assert(CAT && "string literal isn't an array"); 2801 QualType CharType = CAT->getElementType(); 2802 assert(CharType->isIntegerType() && "unexpected character type"); 2803 2804 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2805 CharType->isUnsignedIntegerType()); 2806 if (Index < S->getLength()) 2807 Value = S->getCodeUnit(Index); 2808 return Value; 2809 } 2810 2811 // Expand a string literal into an array of characters. 2812 // 2813 // FIXME: This is inefficient; we should probably introduce something similar 2814 // to the LLVM ConstantDataArray to make this cheaper. 2815 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 2816 APValue &Result) { 2817 const ConstantArrayType *CAT = 2818 Info.Ctx.getAsConstantArrayType(S->getType()); 2819 assert(CAT && "string literal isn't an array"); 2820 QualType CharType = CAT->getElementType(); 2821 assert(CharType->isIntegerType() && "unexpected character type"); 2822 2823 unsigned Elts = CAT->getSize().getZExtValue(); 2824 Result = APValue(APValue::UninitArray(), 2825 std::min(S->getLength(), Elts), Elts); 2826 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2827 CharType->isUnsignedIntegerType()); 2828 if (Result.hasArrayFiller()) 2829 Result.getArrayFiller() = APValue(Value); 2830 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2831 Value = S->getCodeUnit(I); 2832 Result.getArrayInitializedElt(I) = APValue(Value); 2833 } 2834 } 2835 2836 // Expand an array so that it has more than Index filled elements. 2837 static void expandArray(APValue &Array, unsigned Index) { 2838 unsigned Size = Array.getArraySize(); 2839 assert(Index < Size); 2840 2841 // Always at least double the number of elements for which we store a value. 2842 unsigned OldElts = Array.getArrayInitializedElts(); 2843 unsigned NewElts = std::max(Index+1, OldElts * 2); 2844 NewElts = std::min(Size, std::max(NewElts, 8u)); 2845 2846 // Copy the data across. 2847 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2848 for (unsigned I = 0; I != OldElts; ++I) 2849 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2850 for (unsigned I = OldElts; I != NewElts; ++I) 2851 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2852 if (NewValue.hasArrayFiller()) 2853 NewValue.getArrayFiller() = Array.getArrayFiller(); 2854 Array.swap(NewValue); 2855 } 2856 2857 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2858 /// conversion. If it's of class type, we may assume that the copy operation 2859 /// is trivial. Note that this is never true for a union type with fields 2860 /// (because the copy always "reads" the active member) and always true for 2861 /// a non-class type. 2862 static bool isReadByLvalueToRvalueConversion(QualType T) { 2863 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2864 if (!RD || (RD->isUnion() && !RD->field_empty())) 2865 return true; 2866 if (RD->isEmpty()) 2867 return false; 2868 2869 for (auto *Field : RD->fields()) 2870 if (isReadByLvalueToRvalueConversion(Field->getType())) 2871 return true; 2872 2873 for (auto &BaseSpec : RD->bases()) 2874 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2875 return true; 2876 2877 return false; 2878 } 2879 2880 /// Diagnose an attempt to read from any unreadable field within the specified 2881 /// type, which might be a class type. 2882 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2883 QualType T) { 2884 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2885 if (!RD) 2886 return false; 2887 2888 if (!RD->hasMutableFields()) 2889 return false; 2890 2891 for (auto *Field : RD->fields()) { 2892 // If we're actually going to read this field in some way, then it can't 2893 // be mutable. If we're in a union, then assigning to a mutable field 2894 // (even an empty one) can change the active member, so that's not OK. 2895 // FIXME: Add core issue number for the union case. 2896 if (Field->isMutable() && 2897 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2898 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2899 Info.Note(Field->getLocation(), diag::note_declared_at); 2900 return true; 2901 } 2902 2903 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2904 return true; 2905 } 2906 2907 for (auto &BaseSpec : RD->bases()) 2908 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2909 return true; 2910 2911 // All mutable fields were empty, and thus not actually read. 2912 return false; 2913 } 2914 2915 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 2916 APValue::LValueBase Base) { 2917 // A temporary we created. 2918 if (Base.getCallIndex()) 2919 return true; 2920 2921 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 2922 if (!Evaluating) 2923 return false; 2924 2925 // The variable whose initializer we're evaluating. 2926 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>()) 2927 if (declaresSameEntity(Evaluating, BaseD)) 2928 return true; 2929 2930 // A temporary lifetime-extended by the variable whose initializer we're 2931 // evaluating. 2932 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 2933 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 2934 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating)) 2935 return true; 2936 2937 return false; 2938 } 2939 2940 namespace { 2941 /// A handle to a complete object (an object that is not a subobject of 2942 /// another object). 2943 struct CompleteObject { 2944 /// The identity of the object. 2945 APValue::LValueBase Base; 2946 /// The value of the complete object. 2947 APValue *Value; 2948 /// The type of the complete object. 2949 QualType Type; 2950 2951 CompleteObject() : Value(nullptr) {} 2952 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 2953 : Base(Base), Value(Value), Type(Type) {} 2954 2955 bool mayReadMutableMembers(EvalInfo &Info) const { 2956 // In C++14 onwards, it is permitted to read a mutable member whose 2957 // lifetime began within the evaluation. 2958 // FIXME: Should we also allow this in C++11? 2959 if (!Info.getLangOpts().CPlusPlus14) 2960 return false; 2961 return lifetimeStartedInEvaluation(Info, Base); 2962 } 2963 2964 explicit operator bool() const { return !Type.isNull(); } 2965 }; 2966 } // end anonymous namespace 2967 2968 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 2969 bool IsMutable = false) { 2970 // C++ [basic.type.qualifier]p1: 2971 // - A const object is an object of type const T or a non-mutable subobject 2972 // of a const object. 2973 if (ObjType.isConstQualified() && !IsMutable) 2974 SubobjType.addConst(); 2975 // - A volatile object is an object of type const T or a subobject of a 2976 // volatile object. 2977 if (ObjType.isVolatileQualified()) 2978 SubobjType.addVolatile(); 2979 return SubobjType; 2980 } 2981 2982 /// Find the designated sub-object of an rvalue. 2983 template<typename SubobjectHandler> 2984 typename SubobjectHandler::result_type 2985 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2986 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2987 if (Sub.Invalid) 2988 // A diagnostic will have already been produced. 2989 return handler.failed(); 2990 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 2991 if (Info.getLangOpts().CPlusPlus11) 2992 Info.FFDiag(E, Sub.isOnePastTheEnd() 2993 ? diag::note_constexpr_access_past_end 2994 : diag::note_constexpr_access_unsized_array) 2995 << handler.AccessKind; 2996 else 2997 Info.FFDiag(E); 2998 return handler.failed(); 2999 } 3000 3001 APValue *O = Obj.Value; 3002 QualType ObjType = Obj.Type; 3003 const FieldDecl *LastField = nullptr; 3004 const FieldDecl *VolatileField = nullptr; 3005 3006 // Walk the designator's path to find the subobject. 3007 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3008 // Reading an indeterminate value is undefined, but assigning over one is OK. 3009 if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) { 3010 if (!Info.checkingPotentialConstantExpression()) 3011 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3012 << handler.AccessKind << O->isIndeterminate(); 3013 return handler.failed(); 3014 } 3015 3016 // C++ [class.ctor]p5: 3017 // const and volatile semantics are not applied on an object under 3018 // construction. 3019 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3020 ObjType->isRecordType() && 3021 Info.isEvaluatingConstructor( 3022 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3023 Sub.Entries.begin() + I)) != 3024 ConstructionPhase::None) { 3025 ObjType = Info.Ctx.getCanonicalType(ObjType); 3026 ObjType.removeLocalConst(); 3027 ObjType.removeLocalVolatile(); 3028 } 3029 3030 // If this is our last pass, check that the final object type is OK. 3031 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3032 // Accesses to volatile objects are prohibited. 3033 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3034 if (Info.getLangOpts().CPlusPlus) { 3035 int DiagKind; 3036 SourceLocation Loc; 3037 const NamedDecl *Decl = nullptr; 3038 if (VolatileField) { 3039 DiagKind = 2; 3040 Loc = VolatileField->getLocation(); 3041 Decl = VolatileField; 3042 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3043 DiagKind = 1; 3044 Loc = VD->getLocation(); 3045 Decl = VD; 3046 } else { 3047 DiagKind = 0; 3048 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3049 Loc = E->getExprLoc(); 3050 } 3051 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3052 << handler.AccessKind << DiagKind << Decl; 3053 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3054 } else { 3055 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3056 } 3057 return handler.failed(); 3058 } 3059 3060 // If we are reading an object of class type, there may still be more 3061 // things we need to check: if there are any mutable subobjects, we 3062 // cannot perform this read. (This only happens when performing a trivial 3063 // copy or assignment.) 3064 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 3065 !Obj.mayReadMutableMembers(Info) && 3066 diagnoseUnreadableFields(Info, E, ObjType)) 3067 return handler.failed(); 3068 } 3069 3070 if (I == N) { 3071 if (!handler.found(*O, ObjType)) 3072 return false; 3073 3074 // If we modified a bit-field, truncate it to the right width. 3075 if (isModification(handler.AccessKind) && 3076 LastField && LastField->isBitField() && 3077 !truncateBitfieldValue(Info, E, *O, LastField)) 3078 return false; 3079 3080 return true; 3081 } 3082 3083 LastField = nullptr; 3084 if (ObjType->isArrayType()) { 3085 // Next subobject is an array element. 3086 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3087 assert(CAT && "vla in literal type?"); 3088 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3089 if (CAT->getSize().ule(Index)) { 3090 // Note, it should not be possible to form a pointer with a valid 3091 // designator which points more than one past the end of the array. 3092 if (Info.getLangOpts().CPlusPlus11) 3093 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3094 << handler.AccessKind; 3095 else 3096 Info.FFDiag(E); 3097 return handler.failed(); 3098 } 3099 3100 ObjType = CAT->getElementType(); 3101 3102 if (O->getArrayInitializedElts() > Index) 3103 O = &O->getArrayInitializedElt(Index); 3104 else if (handler.AccessKind != AK_Read) { 3105 expandArray(*O, Index); 3106 O = &O->getArrayInitializedElt(Index); 3107 } else 3108 O = &O->getArrayFiller(); 3109 } else if (ObjType->isAnyComplexType()) { 3110 // Next subobject is a complex number. 3111 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3112 if (Index > 1) { 3113 if (Info.getLangOpts().CPlusPlus11) 3114 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3115 << handler.AccessKind; 3116 else 3117 Info.FFDiag(E); 3118 return handler.failed(); 3119 } 3120 3121 ObjType = getSubobjectType( 3122 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3123 3124 assert(I == N - 1 && "extracting subobject of scalar?"); 3125 if (O->isComplexInt()) { 3126 return handler.found(Index ? O->getComplexIntImag() 3127 : O->getComplexIntReal(), ObjType); 3128 } else { 3129 assert(O->isComplexFloat()); 3130 return handler.found(Index ? O->getComplexFloatImag() 3131 : O->getComplexFloatReal(), ObjType); 3132 } 3133 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3134 if (Field->isMutable() && handler.AccessKind == AK_Read && 3135 !Obj.mayReadMutableMembers(Info)) { 3136 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 3137 << Field; 3138 Info.Note(Field->getLocation(), diag::note_declared_at); 3139 return handler.failed(); 3140 } 3141 3142 // Next subobject is a class, struct or union field. 3143 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3144 if (RD->isUnion()) { 3145 const FieldDecl *UnionField = O->getUnionField(); 3146 if (!UnionField || 3147 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3148 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3149 << handler.AccessKind << Field << !UnionField << UnionField; 3150 return handler.failed(); 3151 } 3152 O = &O->getUnionValue(); 3153 } else 3154 O = &O->getStructField(Field->getFieldIndex()); 3155 3156 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3157 LastField = Field; 3158 if (Field->getType().isVolatileQualified()) 3159 VolatileField = Field; 3160 } else { 3161 // Next subobject is a base class. 3162 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3163 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3164 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3165 3166 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3167 } 3168 } 3169 } 3170 3171 namespace { 3172 struct ExtractSubobjectHandler { 3173 EvalInfo &Info; 3174 APValue &Result; 3175 3176 static const AccessKinds AccessKind = AK_Read; 3177 3178 typedef bool result_type; 3179 bool failed() { return false; } 3180 bool found(APValue &Subobj, QualType SubobjType) { 3181 Result = Subobj; 3182 return true; 3183 } 3184 bool found(APSInt &Value, QualType SubobjType) { 3185 Result = APValue(Value); 3186 return true; 3187 } 3188 bool found(APFloat &Value, QualType SubobjType) { 3189 Result = APValue(Value); 3190 return true; 3191 } 3192 }; 3193 } // end anonymous namespace 3194 3195 const AccessKinds ExtractSubobjectHandler::AccessKind; 3196 3197 /// Extract the designated sub-object of an rvalue. 3198 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3199 const CompleteObject &Obj, 3200 const SubobjectDesignator &Sub, 3201 APValue &Result) { 3202 ExtractSubobjectHandler Handler = { Info, Result }; 3203 return findSubobject(Info, E, Obj, Sub, Handler); 3204 } 3205 3206 namespace { 3207 struct ModifySubobjectHandler { 3208 EvalInfo &Info; 3209 APValue &NewVal; 3210 const Expr *E; 3211 3212 typedef bool result_type; 3213 static const AccessKinds AccessKind = AK_Assign; 3214 3215 bool checkConst(QualType QT) { 3216 // Assigning to a const object has undefined behavior. 3217 if (QT.isConstQualified()) { 3218 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3219 return false; 3220 } 3221 return true; 3222 } 3223 3224 bool failed() { return false; } 3225 bool found(APValue &Subobj, QualType SubobjType) { 3226 if (!checkConst(SubobjType)) 3227 return false; 3228 // We've been given ownership of NewVal, so just swap it in. 3229 Subobj.swap(NewVal); 3230 return true; 3231 } 3232 bool found(APSInt &Value, QualType SubobjType) { 3233 if (!checkConst(SubobjType)) 3234 return false; 3235 if (!NewVal.isInt()) { 3236 // Maybe trying to write a cast pointer value into a complex? 3237 Info.FFDiag(E); 3238 return false; 3239 } 3240 Value = NewVal.getInt(); 3241 return true; 3242 } 3243 bool found(APFloat &Value, QualType SubobjType) { 3244 if (!checkConst(SubobjType)) 3245 return false; 3246 Value = NewVal.getFloat(); 3247 return true; 3248 } 3249 }; 3250 } // end anonymous namespace 3251 3252 const AccessKinds ModifySubobjectHandler::AccessKind; 3253 3254 /// Update the designated sub-object of an rvalue to the given value. 3255 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3256 const CompleteObject &Obj, 3257 const SubobjectDesignator &Sub, 3258 APValue &NewVal) { 3259 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3260 return findSubobject(Info, E, Obj, Sub, Handler); 3261 } 3262 3263 /// Find the position where two subobject designators diverge, or equivalently 3264 /// the length of the common initial subsequence. 3265 static unsigned FindDesignatorMismatch(QualType ObjType, 3266 const SubobjectDesignator &A, 3267 const SubobjectDesignator &B, 3268 bool &WasArrayIndex) { 3269 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3270 for (/**/; I != N; ++I) { 3271 if (!ObjType.isNull() && 3272 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3273 // Next subobject is an array element. 3274 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3275 WasArrayIndex = true; 3276 return I; 3277 } 3278 if (ObjType->isAnyComplexType()) 3279 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3280 else 3281 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3282 } else { 3283 if (A.Entries[I].getAsBaseOrMember() != 3284 B.Entries[I].getAsBaseOrMember()) { 3285 WasArrayIndex = false; 3286 return I; 3287 } 3288 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3289 // Next subobject is a field. 3290 ObjType = FD->getType(); 3291 else 3292 // Next subobject is a base class. 3293 ObjType = QualType(); 3294 } 3295 } 3296 WasArrayIndex = false; 3297 return I; 3298 } 3299 3300 /// Determine whether the given subobject designators refer to elements of the 3301 /// same array object. 3302 static bool AreElementsOfSameArray(QualType ObjType, 3303 const SubobjectDesignator &A, 3304 const SubobjectDesignator &B) { 3305 if (A.Entries.size() != B.Entries.size()) 3306 return false; 3307 3308 bool IsArray = A.MostDerivedIsArrayElement; 3309 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3310 // A is a subobject of the array element. 3311 return false; 3312 3313 // If A (and B) designates an array element, the last entry will be the array 3314 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3315 // of length 1' case, and the entire path must match. 3316 bool WasArrayIndex; 3317 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3318 return CommonLength >= A.Entries.size() - IsArray; 3319 } 3320 3321 /// Find the complete object to which an LValue refers. 3322 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3323 AccessKinds AK, const LValue &LVal, 3324 QualType LValType) { 3325 if (LVal.InvalidBase) { 3326 Info.FFDiag(E); 3327 return CompleteObject(); 3328 } 3329 3330 if (!LVal.Base) { 3331 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3332 return CompleteObject(); 3333 } 3334 3335 CallStackFrame *Frame = nullptr; 3336 unsigned Depth = 0; 3337 if (LVal.getLValueCallIndex()) { 3338 std::tie(Frame, Depth) = 3339 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3340 if (!Frame) { 3341 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3342 << AK << LVal.Base.is<const ValueDecl*>(); 3343 NoteLValueLocation(Info, LVal.Base); 3344 return CompleteObject(); 3345 } 3346 } 3347 3348 bool IsAccess = isFormalAccess(AK); 3349 3350 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3351 // is not a constant expression (even if the object is non-volatile). We also 3352 // apply this rule to C++98, in order to conform to the expected 'volatile' 3353 // semantics. 3354 if (IsAccess && LValType.isVolatileQualified()) { 3355 if (Info.getLangOpts().CPlusPlus) 3356 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3357 << AK << LValType; 3358 else 3359 Info.FFDiag(E); 3360 return CompleteObject(); 3361 } 3362 3363 // Compute value storage location and type of base object. 3364 APValue *BaseVal = nullptr; 3365 QualType BaseType = getType(LVal.Base); 3366 3367 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3368 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3369 // In C++11, constexpr, non-volatile variables initialized with constant 3370 // expressions are constant expressions too. Inside constexpr functions, 3371 // parameters are constant expressions even if they're non-const. 3372 // In C++1y, objects local to a constant expression (those with a Frame) are 3373 // both readable and writable inside constant expressions. 3374 // In C, such things can also be folded, although they are not ICEs. 3375 const VarDecl *VD = dyn_cast<VarDecl>(D); 3376 if (VD) { 3377 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3378 VD = VDef; 3379 } 3380 if (!VD || VD->isInvalidDecl()) { 3381 Info.FFDiag(E); 3382 return CompleteObject(); 3383 } 3384 3385 // Unless we're looking at a local variable or argument in a constexpr call, 3386 // the variable we're reading must be const. 3387 if (!Frame) { 3388 if (Info.getLangOpts().CPlusPlus14 && 3389 declaresSameEntity( 3390 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) { 3391 // OK, we can read and modify an object if we're in the process of 3392 // evaluating its initializer, because its lifetime began in this 3393 // evaluation. 3394 } else if (isModification(AK)) { 3395 // All the remaining cases do not permit modification of the object. 3396 Info.FFDiag(E, diag::note_constexpr_modify_global); 3397 return CompleteObject(); 3398 } else if (VD->isConstexpr()) { 3399 // OK, we can read this variable. 3400 } else if (BaseType->isIntegralOrEnumerationType()) { 3401 // In OpenCL if a variable is in constant address space it is a const 3402 // value. 3403 if (!(BaseType.isConstQualified() || 3404 (Info.getLangOpts().OpenCL && 3405 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3406 if (!IsAccess) 3407 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3408 if (Info.getLangOpts().CPlusPlus) { 3409 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3410 Info.Note(VD->getLocation(), diag::note_declared_at); 3411 } else { 3412 Info.FFDiag(E); 3413 } 3414 return CompleteObject(); 3415 } 3416 } else if (!IsAccess) { 3417 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3418 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3419 // We support folding of const floating-point types, in order to make 3420 // static const data members of such types (supported as an extension) 3421 // more useful. 3422 if (Info.getLangOpts().CPlusPlus11) { 3423 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3424 Info.Note(VD->getLocation(), diag::note_declared_at); 3425 } else { 3426 Info.CCEDiag(E); 3427 } 3428 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3429 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3430 // Keep evaluating to see what we can do. 3431 } else { 3432 // FIXME: Allow folding of values of any literal type in all languages. 3433 if (Info.checkingPotentialConstantExpression() && 3434 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3435 // The definition of this variable could be constexpr. We can't 3436 // access it right now, but may be able to in future. 3437 } else if (Info.getLangOpts().CPlusPlus11) { 3438 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3439 Info.Note(VD->getLocation(), diag::note_declared_at); 3440 } else { 3441 Info.FFDiag(E); 3442 } 3443 return CompleteObject(); 3444 } 3445 } 3446 3447 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3448 return CompleteObject(); 3449 } else { 3450 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3451 3452 if (!Frame) { 3453 if (const MaterializeTemporaryExpr *MTE = 3454 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3455 assert(MTE->getStorageDuration() == SD_Static && 3456 "should have a frame for a non-global materialized temporary"); 3457 3458 // Per C++1y [expr.const]p2: 3459 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3460 // - a [...] glvalue of integral or enumeration type that refers to 3461 // a non-volatile const object [...] 3462 // [...] 3463 // - a [...] glvalue of literal type that refers to a non-volatile 3464 // object whose lifetime began within the evaluation of e. 3465 // 3466 // C++11 misses the 'began within the evaluation of e' check and 3467 // instead allows all temporaries, including things like: 3468 // int &&r = 1; 3469 // int x = ++r; 3470 // constexpr int k = r; 3471 // Therefore we use the C++14 rules in C++11 too. 3472 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3473 const ValueDecl *ED = MTE->getExtendingDecl(); 3474 if (!(BaseType.isConstQualified() && 3475 BaseType->isIntegralOrEnumerationType()) && 3476 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 3477 if (!IsAccess) 3478 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3479 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3480 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3481 return CompleteObject(); 3482 } 3483 3484 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3485 assert(BaseVal && "got reference to unevaluated temporary"); 3486 } else { 3487 if (!IsAccess) 3488 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3489 APValue Val; 3490 LVal.moveInto(Val); 3491 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 3492 << AK 3493 << Val.getAsString(Info.Ctx, 3494 Info.Ctx.getLValueReferenceType(LValType)); 3495 NoteLValueLocation(Info, LVal.Base); 3496 return CompleteObject(); 3497 } 3498 } else { 3499 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3500 assert(BaseVal && "missing value for temporary"); 3501 } 3502 } 3503 3504 // In C++14, we can't safely access any mutable state when we might be 3505 // evaluating after an unmodeled side effect. 3506 // 3507 // FIXME: Not all local state is mutable. Allow local constant subobjects 3508 // to be read here (but take care with 'mutable' fields). 3509 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3510 Info.EvalStatus.HasSideEffects) || 3511 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 3512 return CompleteObject(); 3513 3514 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 3515 } 3516 3517 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3518 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3519 /// glvalue referred to by an entity of reference type. 3520 /// 3521 /// \param Info - Information about the ongoing evaluation. 3522 /// \param Conv - The expression for which we are performing the conversion. 3523 /// Used for diagnostics. 3524 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3525 /// case of a non-class type). 3526 /// \param LVal - The glvalue on which we are attempting to perform this action. 3527 /// \param RVal - The produced value will be placed here. 3528 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 3529 QualType Type, 3530 const LValue &LVal, APValue &RVal) { 3531 if (LVal.Designator.Invalid) 3532 return false; 3533 3534 // Check for special cases where there is no existing APValue to look at. 3535 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3536 3537 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 3538 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3539 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3540 // initializer until now for such expressions. Such an expression can't be 3541 // an ICE in C, so this only matters for fold. 3542 if (Type.isVolatileQualified()) { 3543 Info.FFDiag(Conv); 3544 return false; 3545 } 3546 APValue Lit; 3547 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3548 return false; 3549 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 3550 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 3551 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3552 // Special-case character extraction so we don't have to construct an 3553 // APValue for the whole string. 3554 assert(LVal.Designator.Entries.size() <= 1 && 3555 "Can only read characters from string literals"); 3556 if (LVal.Designator.Entries.empty()) { 3557 // Fail for now for LValue to RValue conversion of an array. 3558 // (This shouldn't show up in C/C++, but it could be triggered by a 3559 // weird EvaluateAsRValue call from a tool.) 3560 Info.FFDiag(Conv); 3561 return false; 3562 } 3563 if (LVal.Designator.isOnePastTheEnd()) { 3564 if (Info.getLangOpts().CPlusPlus11) 3565 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read; 3566 else 3567 Info.FFDiag(Conv); 3568 return false; 3569 } 3570 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 3571 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 3572 return true; 3573 } 3574 } 3575 3576 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 3577 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 3578 } 3579 3580 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3581 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3582 QualType LValType, APValue &Val) { 3583 if (LVal.Designator.Invalid) 3584 return false; 3585 3586 if (!Info.getLangOpts().CPlusPlus14) { 3587 Info.FFDiag(E); 3588 return false; 3589 } 3590 3591 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3592 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3593 } 3594 3595 namespace { 3596 struct CompoundAssignSubobjectHandler { 3597 EvalInfo &Info; 3598 const Expr *E; 3599 QualType PromotedLHSType; 3600 BinaryOperatorKind Opcode; 3601 const APValue &RHS; 3602 3603 static const AccessKinds AccessKind = AK_Assign; 3604 3605 typedef bool result_type; 3606 3607 bool checkConst(QualType QT) { 3608 // Assigning to a const object has undefined behavior. 3609 if (QT.isConstQualified()) { 3610 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3611 return false; 3612 } 3613 return true; 3614 } 3615 3616 bool failed() { return false; } 3617 bool found(APValue &Subobj, QualType SubobjType) { 3618 switch (Subobj.getKind()) { 3619 case APValue::Int: 3620 return found(Subobj.getInt(), SubobjType); 3621 case APValue::Float: 3622 return found(Subobj.getFloat(), SubobjType); 3623 case APValue::ComplexInt: 3624 case APValue::ComplexFloat: 3625 // FIXME: Implement complex compound assignment. 3626 Info.FFDiag(E); 3627 return false; 3628 case APValue::LValue: 3629 return foundPointer(Subobj, SubobjType); 3630 default: 3631 // FIXME: can this happen? 3632 Info.FFDiag(E); 3633 return false; 3634 } 3635 } 3636 bool found(APSInt &Value, QualType SubobjType) { 3637 if (!checkConst(SubobjType)) 3638 return false; 3639 3640 if (!SubobjType->isIntegerType()) { 3641 // We don't support compound assignment on integer-cast-to-pointer 3642 // values. 3643 Info.FFDiag(E); 3644 return false; 3645 } 3646 3647 if (RHS.isInt()) { 3648 APSInt LHS = 3649 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 3650 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3651 return false; 3652 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3653 return true; 3654 } else if (RHS.isFloat()) { 3655 APFloat FValue(0.0); 3656 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 3657 FValue) && 3658 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 3659 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 3660 Value); 3661 } 3662 3663 Info.FFDiag(E); 3664 return false; 3665 } 3666 bool found(APFloat &Value, QualType SubobjType) { 3667 return checkConst(SubobjType) && 3668 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3669 Value) && 3670 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3671 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3672 } 3673 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3674 if (!checkConst(SubobjType)) 3675 return false; 3676 3677 QualType PointeeType; 3678 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3679 PointeeType = PT->getPointeeType(); 3680 3681 if (PointeeType.isNull() || !RHS.isInt() || 3682 (Opcode != BO_Add && Opcode != BO_Sub)) { 3683 Info.FFDiag(E); 3684 return false; 3685 } 3686 3687 APSInt Offset = RHS.getInt(); 3688 if (Opcode == BO_Sub) 3689 negateAsSigned(Offset); 3690 3691 LValue LVal; 3692 LVal.setFrom(Info.Ctx, Subobj); 3693 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3694 return false; 3695 LVal.moveInto(Subobj); 3696 return true; 3697 } 3698 }; 3699 } // end anonymous namespace 3700 3701 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3702 3703 /// Perform a compound assignment of LVal <op>= RVal. 3704 static bool handleCompoundAssignment( 3705 EvalInfo &Info, const Expr *E, 3706 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3707 BinaryOperatorKind Opcode, const APValue &RVal) { 3708 if (LVal.Designator.Invalid) 3709 return false; 3710 3711 if (!Info.getLangOpts().CPlusPlus14) { 3712 Info.FFDiag(E); 3713 return false; 3714 } 3715 3716 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3717 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3718 RVal }; 3719 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3720 } 3721 3722 namespace { 3723 struct IncDecSubobjectHandler { 3724 EvalInfo &Info; 3725 const UnaryOperator *E; 3726 AccessKinds AccessKind; 3727 APValue *Old; 3728 3729 typedef bool result_type; 3730 3731 bool checkConst(QualType QT) { 3732 // Assigning to a const object has undefined behavior. 3733 if (QT.isConstQualified()) { 3734 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3735 return false; 3736 } 3737 return true; 3738 } 3739 3740 bool failed() { return false; } 3741 bool found(APValue &Subobj, QualType SubobjType) { 3742 // Stash the old value. Also clear Old, so we don't clobber it later 3743 // if we're post-incrementing a complex. 3744 if (Old) { 3745 *Old = Subobj; 3746 Old = nullptr; 3747 } 3748 3749 switch (Subobj.getKind()) { 3750 case APValue::Int: 3751 return found(Subobj.getInt(), SubobjType); 3752 case APValue::Float: 3753 return found(Subobj.getFloat(), SubobjType); 3754 case APValue::ComplexInt: 3755 return found(Subobj.getComplexIntReal(), 3756 SubobjType->castAs<ComplexType>()->getElementType() 3757 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3758 case APValue::ComplexFloat: 3759 return found(Subobj.getComplexFloatReal(), 3760 SubobjType->castAs<ComplexType>()->getElementType() 3761 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3762 case APValue::LValue: 3763 return foundPointer(Subobj, SubobjType); 3764 default: 3765 // FIXME: can this happen? 3766 Info.FFDiag(E); 3767 return false; 3768 } 3769 } 3770 bool found(APSInt &Value, QualType SubobjType) { 3771 if (!checkConst(SubobjType)) 3772 return false; 3773 3774 if (!SubobjType->isIntegerType()) { 3775 // We don't support increment / decrement on integer-cast-to-pointer 3776 // values. 3777 Info.FFDiag(E); 3778 return false; 3779 } 3780 3781 if (Old) *Old = APValue(Value); 3782 3783 // bool arithmetic promotes to int, and the conversion back to bool 3784 // doesn't reduce mod 2^n, so special-case it. 3785 if (SubobjType->isBooleanType()) { 3786 if (AccessKind == AK_Increment) 3787 Value = 1; 3788 else 3789 Value = !Value; 3790 return true; 3791 } 3792 3793 bool WasNegative = Value.isNegative(); 3794 if (AccessKind == AK_Increment) { 3795 ++Value; 3796 3797 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 3798 APSInt ActualValue(Value, /*IsUnsigned*/true); 3799 return HandleOverflow(Info, E, ActualValue, SubobjType); 3800 } 3801 } else { 3802 --Value; 3803 3804 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 3805 unsigned BitWidth = Value.getBitWidth(); 3806 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3807 ActualValue.setBit(BitWidth); 3808 return HandleOverflow(Info, E, ActualValue, SubobjType); 3809 } 3810 } 3811 return true; 3812 } 3813 bool found(APFloat &Value, QualType SubobjType) { 3814 if (!checkConst(SubobjType)) 3815 return false; 3816 3817 if (Old) *Old = APValue(Value); 3818 3819 APFloat One(Value.getSemantics(), 1); 3820 if (AccessKind == AK_Increment) 3821 Value.add(One, APFloat::rmNearestTiesToEven); 3822 else 3823 Value.subtract(One, APFloat::rmNearestTiesToEven); 3824 return true; 3825 } 3826 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3827 if (!checkConst(SubobjType)) 3828 return false; 3829 3830 QualType PointeeType; 3831 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3832 PointeeType = PT->getPointeeType(); 3833 else { 3834 Info.FFDiag(E); 3835 return false; 3836 } 3837 3838 LValue LVal; 3839 LVal.setFrom(Info.Ctx, Subobj); 3840 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3841 AccessKind == AK_Increment ? 1 : -1)) 3842 return false; 3843 LVal.moveInto(Subobj); 3844 return true; 3845 } 3846 }; 3847 } // end anonymous namespace 3848 3849 /// Perform an increment or decrement on LVal. 3850 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3851 QualType LValType, bool IsIncrement, APValue *Old) { 3852 if (LVal.Designator.Invalid) 3853 return false; 3854 3855 if (!Info.getLangOpts().CPlusPlus14) { 3856 Info.FFDiag(E); 3857 return false; 3858 } 3859 3860 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3861 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3862 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 3863 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3864 } 3865 3866 /// Build an lvalue for the object argument of a member function call. 3867 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3868 LValue &This) { 3869 if (Object->getType()->isPointerType()) 3870 return EvaluatePointer(Object, This, Info); 3871 3872 if (Object->isGLValue()) 3873 return EvaluateLValue(Object, This, Info); 3874 3875 if (Object->getType()->isLiteralType(Info.Ctx)) 3876 return EvaluateTemporary(Object, This, Info); 3877 3878 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3879 return false; 3880 } 3881 3882 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3883 /// lvalue referring to the result. 3884 /// 3885 /// \param Info - Information about the ongoing evaluation. 3886 /// \param LV - An lvalue referring to the base of the member pointer. 3887 /// \param RHS - The member pointer expression. 3888 /// \param IncludeMember - Specifies whether the member itself is included in 3889 /// the resulting LValue subobject designator. This is not possible when 3890 /// creating a bound member function. 3891 /// \return The field or method declaration to which the member pointer refers, 3892 /// or 0 if evaluation fails. 3893 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3894 QualType LVType, 3895 LValue &LV, 3896 const Expr *RHS, 3897 bool IncludeMember = true) { 3898 MemberPtr MemPtr; 3899 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3900 return nullptr; 3901 3902 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3903 // member value, the behavior is undefined. 3904 if (!MemPtr.getDecl()) { 3905 // FIXME: Specific diagnostic. 3906 Info.FFDiag(RHS); 3907 return nullptr; 3908 } 3909 3910 if (MemPtr.isDerivedMember()) { 3911 // This is a member of some derived class. Truncate LV appropriately. 3912 // The end of the derived-to-base path for the base object must match the 3913 // derived-to-base path for the member pointer. 3914 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3915 LV.Designator.Entries.size()) { 3916 Info.FFDiag(RHS); 3917 return nullptr; 3918 } 3919 unsigned PathLengthToMember = 3920 LV.Designator.Entries.size() - MemPtr.Path.size(); 3921 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3922 const CXXRecordDecl *LVDecl = getAsBaseClass( 3923 LV.Designator.Entries[PathLengthToMember + I]); 3924 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3925 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3926 Info.FFDiag(RHS); 3927 return nullptr; 3928 } 3929 } 3930 3931 // Truncate the lvalue to the appropriate derived class. 3932 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3933 PathLengthToMember)) 3934 return nullptr; 3935 } else if (!MemPtr.Path.empty()) { 3936 // Extend the LValue path with the member pointer's path. 3937 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3938 MemPtr.Path.size() + IncludeMember); 3939 3940 // Walk down to the appropriate base class. 3941 if (const PointerType *PT = LVType->getAs<PointerType>()) 3942 LVType = PT->getPointeeType(); 3943 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3944 assert(RD && "member pointer access on non-class-type expression"); 3945 // The first class in the path is that of the lvalue. 3946 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3947 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3948 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3949 return nullptr; 3950 RD = Base; 3951 } 3952 // Finally cast to the class containing the member. 3953 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3954 MemPtr.getContainingRecord())) 3955 return nullptr; 3956 } 3957 3958 // Add the member. Note that we cannot build bound member functions here. 3959 if (IncludeMember) { 3960 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3961 if (!HandleLValueMember(Info, RHS, LV, FD)) 3962 return nullptr; 3963 } else if (const IndirectFieldDecl *IFD = 3964 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3965 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3966 return nullptr; 3967 } else { 3968 llvm_unreachable("can't construct reference to bound member function"); 3969 } 3970 } 3971 3972 return MemPtr.getDecl(); 3973 } 3974 3975 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3976 const BinaryOperator *BO, 3977 LValue &LV, 3978 bool IncludeMember = true) { 3979 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3980 3981 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3982 if (Info.noteFailure()) { 3983 MemberPtr MemPtr; 3984 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3985 } 3986 return nullptr; 3987 } 3988 3989 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3990 BO->getRHS(), IncludeMember); 3991 } 3992 3993 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3994 /// the provided lvalue, which currently refers to the base object. 3995 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3996 LValue &Result) { 3997 SubobjectDesignator &D = Result.Designator; 3998 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3999 return false; 4000 4001 QualType TargetQT = E->getType(); 4002 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4003 TargetQT = PT->getPointeeType(); 4004 4005 // Check this cast lands within the final derived-to-base subobject path. 4006 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4007 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4008 << D.MostDerivedType << TargetQT; 4009 return false; 4010 } 4011 4012 // Check the type of the final cast. We don't need to check the path, 4013 // since a cast can only be formed if the path is unique. 4014 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4015 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4016 const CXXRecordDecl *FinalType; 4017 if (NewEntriesSize == D.MostDerivedPathLength) 4018 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4019 else 4020 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4021 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4022 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4023 << D.MostDerivedType << TargetQT; 4024 return false; 4025 } 4026 4027 // Truncate the lvalue to the appropriate derived class. 4028 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4029 } 4030 4031 namespace { 4032 enum EvalStmtResult { 4033 /// Evaluation failed. 4034 ESR_Failed, 4035 /// Hit a 'return' statement. 4036 ESR_Returned, 4037 /// Evaluation succeeded. 4038 ESR_Succeeded, 4039 /// Hit a 'continue' statement. 4040 ESR_Continue, 4041 /// Hit a 'break' statement. 4042 ESR_Break, 4043 /// Still scanning for 'case' or 'default' statement. 4044 ESR_CaseNotFound 4045 }; 4046 } 4047 4048 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4049 // We don't need to evaluate the initializer for a static local. 4050 if (!VD->hasLocalStorage()) 4051 return true; 4052 4053 LValue Result; 4054 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall); 4055 4056 const Expr *InitE = VD->getInit(); 4057 if (!InitE) { 4058 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized) 4059 << false << VD->getType(); 4060 Val = APValue(); 4061 return false; 4062 } 4063 4064 if (InitE->isValueDependent()) 4065 return false; 4066 4067 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4068 // Wipe out any partially-computed value, to allow tracking that this 4069 // evaluation failed. 4070 Val = APValue(); 4071 return false; 4072 } 4073 4074 return true; 4075 } 4076 4077 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4078 bool OK = true; 4079 4080 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4081 OK &= EvaluateVarDecl(Info, VD); 4082 4083 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4084 for (auto *BD : DD->bindings()) 4085 if (auto *VD = BD->getHoldingVar()) 4086 OK &= EvaluateDecl(Info, VD); 4087 4088 return OK; 4089 } 4090 4091 4092 /// Evaluate a condition (either a variable declaration or an expression). 4093 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4094 const Expr *Cond, bool &Result) { 4095 FullExpressionRAII Scope(Info); 4096 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4097 return false; 4098 return EvaluateAsBooleanCondition(Cond, Result, Info); 4099 } 4100 4101 namespace { 4102 /// A location where the result (returned value) of evaluating a 4103 /// statement should be stored. 4104 struct StmtResult { 4105 /// The APValue that should be filled in with the returned value. 4106 APValue &Value; 4107 /// The location containing the result, if any (used to support RVO). 4108 const LValue *Slot; 4109 }; 4110 4111 struct TempVersionRAII { 4112 CallStackFrame &Frame; 4113 4114 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4115 Frame.pushTempVersion(); 4116 } 4117 4118 ~TempVersionRAII() { 4119 Frame.popTempVersion(); 4120 } 4121 }; 4122 4123 } 4124 4125 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4126 const Stmt *S, 4127 const SwitchCase *SC = nullptr); 4128 4129 /// Evaluate the body of a loop, and translate the result as appropriate. 4130 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4131 const Stmt *Body, 4132 const SwitchCase *Case = nullptr) { 4133 BlockScopeRAII Scope(Info); 4134 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 4135 case ESR_Break: 4136 return ESR_Succeeded; 4137 case ESR_Succeeded: 4138 case ESR_Continue: 4139 return ESR_Continue; 4140 case ESR_Failed: 4141 case ESR_Returned: 4142 case ESR_CaseNotFound: 4143 return ESR; 4144 } 4145 llvm_unreachable("Invalid EvalStmtResult!"); 4146 } 4147 4148 /// Evaluate a switch statement. 4149 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4150 const SwitchStmt *SS) { 4151 BlockScopeRAII Scope(Info); 4152 4153 // Evaluate the switch condition. 4154 APSInt Value; 4155 { 4156 FullExpressionRAII Scope(Info); 4157 if (const Stmt *Init = SS->getInit()) { 4158 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4159 if (ESR != ESR_Succeeded) 4160 return ESR; 4161 } 4162 if (SS->getConditionVariable() && 4163 !EvaluateDecl(Info, SS->getConditionVariable())) 4164 return ESR_Failed; 4165 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4166 return ESR_Failed; 4167 } 4168 4169 // Find the switch case corresponding to the value of the condition. 4170 // FIXME: Cache this lookup. 4171 const SwitchCase *Found = nullptr; 4172 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4173 SC = SC->getNextSwitchCase()) { 4174 if (isa<DefaultStmt>(SC)) { 4175 Found = SC; 4176 continue; 4177 } 4178 4179 const CaseStmt *CS = cast<CaseStmt>(SC); 4180 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4181 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4182 : LHS; 4183 if (LHS <= Value && Value <= RHS) { 4184 Found = SC; 4185 break; 4186 } 4187 } 4188 4189 if (!Found) 4190 return ESR_Succeeded; 4191 4192 // Search the switch body for the switch case and evaluate it from there. 4193 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 4194 case ESR_Break: 4195 return ESR_Succeeded; 4196 case ESR_Succeeded: 4197 case ESR_Continue: 4198 case ESR_Failed: 4199 case ESR_Returned: 4200 return ESR; 4201 case ESR_CaseNotFound: 4202 // This can only happen if the switch case is nested within a statement 4203 // expression. We have no intention of supporting that. 4204 Info.FFDiag(Found->getBeginLoc(), 4205 diag::note_constexpr_stmt_expr_unsupported); 4206 return ESR_Failed; 4207 } 4208 llvm_unreachable("Invalid EvalStmtResult!"); 4209 } 4210 4211 // Evaluate a statement. 4212 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4213 const Stmt *S, const SwitchCase *Case) { 4214 if (!Info.nextStep(S)) 4215 return ESR_Failed; 4216 4217 // If we're hunting down a 'case' or 'default' label, recurse through 4218 // substatements until we hit the label. 4219 if (Case) { 4220 // FIXME: We don't start the lifetime of objects whose initialization we 4221 // jump over. However, such objects must be of class type with a trivial 4222 // default constructor that initialize all subobjects, so must be empty, 4223 // so this almost never matters. 4224 switch (S->getStmtClass()) { 4225 case Stmt::CompoundStmtClass: 4226 // FIXME: Precompute which substatement of a compound statement we 4227 // would jump to, and go straight there rather than performing a 4228 // linear scan each time. 4229 case Stmt::LabelStmtClass: 4230 case Stmt::AttributedStmtClass: 4231 case Stmt::DoStmtClass: 4232 break; 4233 4234 case Stmt::CaseStmtClass: 4235 case Stmt::DefaultStmtClass: 4236 if (Case == S) 4237 Case = nullptr; 4238 break; 4239 4240 case Stmt::IfStmtClass: { 4241 // FIXME: Precompute which side of an 'if' we would jump to, and go 4242 // straight there rather than scanning both sides. 4243 const IfStmt *IS = cast<IfStmt>(S); 4244 4245 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4246 // preceded by our switch label. 4247 BlockScopeRAII Scope(Info); 4248 4249 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4250 if (ESR != ESR_CaseNotFound || !IS->getElse()) 4251 return ESR; 4252 return EvaluateStmt(Result, Info, IS->getElse(), Case); 4253 } 4254 4255 case Stmt::WhileStmtClass: { 4256 EvalStmtResult ESR = 4257 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4258 if (ESR != ESR_Continue) 4259 return ESR; 4260 break; 4261 } 4262 4263 case Stmt::ForStmtClass: { 4264 const ForStmt *FS = cast<ForStmt>(S); 4265 EvalStmtResult ESR = 4266 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4267 if (ESR != ESR_Continue) 4268 return ESR; 4269 if (FS->getInc()) { 4270 FullExpressionRAII IncScope(Info); 4271 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4272 return ESR_Failed; 4273 } 4274 break; 4275 } 4276 4277 case Stmt::DeclStmtClass: 4278 // FIXME: If the variable has initialization that can't be jumped over, 4279 // bail out of any immediately-surrounding compound-statement too. 4280 default: 4281 return ESR_CaseNotFound; 4282 } 4283 } 4284 4285 switch (S->getStmtClass()) { 4286 default: 4287 if (const Expr *E = dyn_cast<Expr>(S)) { 4288 // Don't bother evaluating beyond an expression-statement which couldn't 4289 // be evaluated. 4290 FullExpressionRAII Scope(Info); 4291 if (!EvaluateIgnoredValue(Info, E)) 4292 return ESR_Failed; 4293 return ESR_Succeeded; 4294 } 4295 4296 Info.FFDiag(S->getBeginLoc()); 4297 return ESR_Failed; 4298 4299 case Stmt::NullStmtClass: 4300 return ESR_Succeeded; 4301 4302 case Stmt::DeclStmtClass: { 4303 const DeclStmt *DS = cast<DeclStmt>(S); 4304 for (const auto *DclIt : DS->decls()) { 4305 // Each declaration initialization is its own full-expression. 4306 // FIXME: This isn't quite right; if we're performing aggregate 4307 // initialization, each braced subexpression is its own full-expression. 4308 FullExpressionRAII Scope(Info); 4309 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 4310 return ESR_Failed; 4311 } 4312 return ESR_Succeeded; 4313 } 4314 4315 case Stmt::ReturnStmtClass: { 4316 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4317 FullExpressionRAII Scope(Info); 4318 if (RetExpr && 4319 !(Result.Slot 4320 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4321 : Evaluate(Result.Value, Info, RetExpr))) 4322 return ESR_Failed; 4323 return ESR_Returned; 4324 } 4325 4326 case Stmt::CompoundStmtClass: { 4327 BlockScopeRAII Scope(Info); 4328 4329 const CompoundStmt *CS = cast<CompoundStmt>(S); 4330 for (const auto *BI : CS->body()) { 4331 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4332 if (ESR == ESR_Succeeded) 4333 Case = nullptr; 4334 else if (ESR != ESR_CaseNotFound) 4335 return ESR; 4336 } 4337 return Case ? ESR_CaseNotFound : ESR_Succeeded; 4338 } 4339 4340 case Stmt::IfStmtClass: { 4341 const IfStmt *IS = cast<IfStmt>(S); 4342 4343 // Evaluate the condition, as either a var decl or as an expression. 4344 BlockScopeRAII Scope(Info); 4345 if (const Stmt *Init = IS->getInit()) { 4346 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4347 if (ESR != ESR_Succeeded) 4348 return ESR; 4349 } 4350 bool Cond; 4351 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4352 return ESR_Failed; 4353 4354 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4355 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4356 if (ESR != ESR_Succeeded) 4357 return ESR; 4358 } 4359 return ESR_Succeeded; 4360 } 4361 4362 case Stmt::WhileStmtClass: { 4363 const WhileStmt *WS = cast<WhileStmt>(S); 4364 while (true) { 4365 BlockScopeRAII Scope(Info); 4366 bool Continue; 4367 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4368 Continue)) 4369 return ESR_Failed; 4370 if (!Continue) 4371 break; 4372 4373 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4374 if (ESR != ESR_Continue) 4375 return ESR; 4376 } 4377 return ESR_Succeeded; 4378 } 4379 4380 case Stmt::DoStmtClass: { 4381 const DoStmt *DS = cast<DoStmt>(S); 4382 bool Continue; 4383 do { 4384 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4385 if (ESR != ESR_Continue) 4386 return ESR; 4387 Case = nullptr; 4388 4389 FullExpressionRAII CondScope(Info); 4390 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 4391 return ESR_Failed; 4392 } while (Continue); 4393 return ESR_Succeeded; 4394 } 4395 4396 case Stmt::ForStmtClass: { 4397 const ForStmt *FS = cast<ForStmt>(S); 4398 BlockScopeRAII Scope(Info); 4399 if (FS->getInit()) { 4400 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4401 if (ESR != ESR_Succeeded) 4402 return ESR; 4403 } 4404 while (true) { 4405 BlockScopeRAII Scope(Info); 4406 bool Continue = true; 4407 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4408 FS->getCond(), Continue)) 4409 return ESR_Failed; 4410 if (!Continue) 4411 break; 4412 4413 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4414 if (ESR != ESR_Continue) 4415 return ESR; 4416 4417 if (FS->getInc()) { 4418 FullExpressionRAII IncScope(Info); 4419 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4420 return ESR_Failed; 4421 } 4422 } 4423 return ESR_Succeeded; 4424 } 4425 4426 case Stmt::CXXForRangeStmtClass: { 4427 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4428 BlockScopeRAII Scope(Info); 4429 4430 // Evaluate the init-statement if present. 4431 if (FS->getInit()) { 4432 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4433 if (ESR != ESR_Succeeded) 4434 return ESR; 4435 } 4436 4437 // Initialize the __range variable. 4438 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4439 if (ESR != ESR_Succeeded) 4440 return ESR; 4441 4442 // Create the __begin and __end iterators. 4443 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4444 if (ESR != ESR_Succeeded) 4445 return ESR; 4446 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4447 if (ESR != ESR_Succeeded) 4448 return ESR; 4449 4450 while (true) { 4451 // Condition: __begin != __end. 4452 { 4453 bool Continue = true; 4454 FullExpressionRAII CondExpr(Info); 4455 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4456 return ESR_Failed; 4457 if (!Continue) 4458 break; 4459 } 4460 4461 // User's variable declaration, initialized by *__begin. 4462 BlockScopeRAII InnerScope(Info); 4463 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4464 if (ESR != ESR_Succeeded) 4465 return ESR; 4466 4467 // Loop body. 4468 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4469 if (ESR != ESR_Continue) 4470 return ESR; 4471 4472 // Increment: ++__begin 4473 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4474 return ESR_Failed; 4475 } 4476 4477 return ESR_Succeeded; 4478 } 4479 4480 case Stmt::SwitchStmtClass: 4481 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4482 4483 case Stmt::ContinueStmtClass: 4484 return ESR_Continue; 4485 4486 case Stmt::BreakStmtClass: 4487 return ESR_Break; 4488 4489 case Stmt::LabelStmtClass: 4490 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4491 4492 case Stmt::AttributedStmtClass: 4493 // As a general principle, C++11 attributes can be ignored without 4494 // any semantic impact. 4495 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4496 Case); 4497 4498 case Stmt::CaseStmtClass: 4499 case Stmt::DefaultStmtClass: 4500 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4501 case Stmt::CXXTryStmtClass: 4502 // Evaluate try blocks by evaluating all sub statements. 4503 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 4504 } 4505 } 4506 4507 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4508 /// default constructor. If so, we'll fold it whether or not it's marked as 4509 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4510 /// so we need special handling. 4511 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4512 const CXXConstructorDecl *CD, 4513 bool IsValueInitialization) { 4514 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4515 return false; 4516 4517 // Value-initialization does not call a trivial default constructor, so such a 4518 // call is a core constant expression whether or not the constructor is 4519 // constexpr. 4520 if (!CD->isConstexpr() && !IsValueInitialization) { 4521 if (Info.getLangOpts().CPlusPlus11) { 4522 // FIXME: If DiagDecl is an implicitly-declared special member function, 4523 // we should be much more explicit about why it's not constexpr. 4524 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4525 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4526 Info.Note(CD->getLocation(), diag::note_declared_at); 4527 } else { 4528 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4529 } 4530 } 4531 return true; 4532 } 4533 4534 /// CheckConstexprFunction - Check that a function can be called in a constant 4535 /// expression. 4536 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4537 const FunctionDecl *Declaration, 4538 const FunctionDecl *Definition, 4539 const Stmt *Body) { 4540 // Potential constant expressions can contain calls to declared, but not yet 4541 // defined, constexpr functions. 4542 if (Info.checkingPotentialConstantExpression() && !Definition && 4543 Declaration->isConstexpr()) 4544 return false; 4545 4546 // Bail out if the function declaration itself is invalid. We will 4547 // have produced a relevant diagnostic while parsing it, so just 4548 // note the problematic sub-expression. 4549 if (Declaration->isInvalidDecl()) { 4550 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4551 return false; 4552 } 4553 4554 // DR1872: An instantiated virtual constexpr function can't be called in a 4555 // constant expression (prior to C++20). We can still constant-fold such a 4556 // call. 4557 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) && 4558 cast<CXXMethodDecl>(Declaration)->isVirtual()) 4559 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 4560 4561 if (Definition && Definition->isInvalidDecl()) { 4562 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4563 return false; 4564 } 4565 4566 // Can we evaluate this function call? 4567 if (Definition && Definition->isConstexpr() && Body) 4568 return true; 4569 4570 if (Info.getLangOpts().CPlusPlus11) { 4571 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4572 4573 // If this function is not constexpr because it is an inherited 4574 // non-constexpr constructor, diagnose that directly. 4575 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4576 if (CD && CD->isInheritingConstructor()) { 4577 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4578 if (!Inherited->isConstexpr()) 4579 DiagDecl = CD = Inherited; 4580 } 4581 4582 // FIXME: If DiagDecl is an implicitly-declared special member function 4583 // or an inheriting constructor, we should be much more explicit about why 4584 // it's not constexpr. 4585 if (CD && CD->isInheritingConstructor()) 4586 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4587 << CD->getInheritedConstructor().getConstructor()->getParent(); 4588 else 4589 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4590 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4591 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4592 } else { 4593 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4594 } 4595 return false; 4596 } 4597 4598 namespace { 4599 struct CheckDynamicTypeHandler { 4600 AccessKinds AccessKind; 4601 typedef bool result_type; 4602 bool failed() { return false; } 4603 bool found(APValue &Subobj, QualType SubobjType) { return true; } 4604 bool found(APSInt &Value, QualType SubobjType) { return true; } 4605 bool found(APFloat &Value, QualType SubobjType) { return true; } 4606 }; 4607 } // end anonymous namespace 4608 4609 /// Check that we can access the notional vptr of an object / determine its 4610 /// dynamic type. 4611 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 4612 AccessKinds AK, bool Polymorphic) { 4613 if (This.Designator.Invalid) 4614 return false; 4615 4616 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 4617 4618 if (!Obj) 4619 return false; 4620 4621 if (!Obj.Value) { 4622 // The object is not usable in constant expressions, so we can't inspect 4623 // its value to see if it's in-lifetime or what the active union members 4624 // are. We can still check for a one-past-the-end lvalue. 4625 if (This.Designator.isOnePastTheEnd() || 4626 This.Designator.isMostDerivedAnUnsizedArray()) { 4627 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 4628 ? diag::note_constexpr_access_past_end 4629 : diag::note_constexpr_access_unsized_array) 4630 << AK; 4631 return false; 4632 } else if (Polymorphic) { 4633 // Conservatively refuse to perform a polymorphic operation if we would 4634 // not be able to read a notional 'vptr' value. 4635 APValue Val; 4636 This.moveInto(Val); 4637 QualType StarThisType = 4638 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 4639 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 4640 << AK << Val.getAsString(Info.Ctx, StarThisType); 4641 return false; 4642 } 4643 return true; 4644 } 4645 4646 CheckDynamicTypeHandler Handler{AK}; 4647 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 4648 } 4649 4650 /// Check that the pointee of the 'this' pointer in a member function call is 4651 /// either within its lifetime or in its period of construction or destruction. 4652 static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 4653 const LValue &This) { 4654 return checkDynamicType(Info, E, This, AK_MemberCall, false); 4655 } 4656 4657 struct DynamicType { 4658 /// The dynamic class type of the object. 4659 const CXXRecordDecl *Type; 4660 /// The corresponding path length in the lvalue. 4661 unsigned PathLength; 4662 }; 4663 4664 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 4665 unsigned PathLength) { 4666 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 4667 Designator.Entries.size() && "invalid path length"); 4668 return (PathLength == Designator.MostDerivedPathLength) 4669 ? Designator.MostDerivedType->getAsCXXRecordDecl() 4670 : getAsBaseClass(Designator.Entries[PathLength - 1]); 4671 } 4672 4673 /// Determine the dynamic type of an object. 4674 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 4675 LValue &This, AccessKinds AK) { 4676 // If we don't have an lvalue denoting an object of class type, there is no 4677 // meaningful dynamic type. (We consider objects of non-class type to have no 4678 // dynamic type.) 4679 if (!checkDynamicType(Info, E, This, AK, true)) 4680 return None; 4681 4682 // Refuse to compute a dynamic type in the presence of virtual bases. This 4683 // shouldn't happen other than in constant-folding situations, since literal 4684 // types can't have virtual bases. 4685 // 4686 // Note that consumers of DynamicType assume that the type has no virtual 4687 // bases, and will need modifications if this restriction is relaxed. 4688 const CXXRecordDecl *Class = 4689 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 4690 if (!Class || Class->getNumVBases()) { 4691 Info.FFDiag(E); 4692 return None; 4693 } 4694 4695 // FIXME: For very deep class hierarchies, it might be beneficial to use a 4696 // binary search here instead. But the overwhelmingly common case is that 4697 // we're not in the middle of a constructor, so it probably doesn't matter 4698 // in practice. 4699 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 4700 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 4701 PathLength <= Path.size(); ++PathLength) { 4702 switch (Info.isEvaluatingConstructor(This.getLValueBase(), 4703 Path.slice(0, PathLength))) { 4704 case ConstructionPhase::Bases: 4705 // We're constructing a base class. This is not the dynamic type. 4706 break; 4707 4708 case ConstructionPhase::None: 4709 case ConstructionPhase::AfterBases: 4710 // We've finished constructing the base classes, so this is the dynamic 4711 // type. 4712 return DynamicType{getBaseClassType(This.Designator, PathLength), 4713 PathLength}; 4714 } 4715 } 4716 4717 // CWG issue 1517: we're constructing a base class of the object described by 4718 // 'This', so that object has not yet begun its period of construction and 4719 // any polymorphic operation on it results in undefined behavior. 4720 Info.FFDiag(E); 4721 return None; 4722 } 4723 4724 /// Perform virtual dispatch. 4725 static const CXXMethodDecl *HandleVirtualDispatch( 4726 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 4727 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 4728 Optional<DynamicType> DynType = 4729 ComputeDynamicType(Info, E, This, AK_MemberCall); 4730 if (!DynType) 4731 return nullptr; 4732 4733 // Find the final overrider. It must be declared in one of the classes on the 4734 // path from the dynamic type to the static type. 4735 // FIXME: If we ever allow literal types to have virtual base classes, that 4736 // won't be true. 4737 const CXXMethodDecl *Callee = Found; 4738 unsigned PathLength = DynType->PathLength; 4739 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 4740 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 4741 const CXXMethodDecl *Overrider = 4742 Found->getCorrespondingMethodDeclaredInClass(Class, false); 4743 if (Overrider) { 4744 Callee = Overrider; 4745 break; 4746 } 4747 } 4748 4749 // C++2a [class.abstract]p6: 4750 // the effect of making a virtual call to a pure virtual function [...] is 4751 // undefined 4752 if (Callee->isPure()) { 4753 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 4754 Info.Note(Callee->getLocation(), diag::note_declared_at); 4755 return nullptr; 4756 } 4757 4758 // If necessary, walk the rest of the path to determine the sequence of 4759 // covariant adjustment steps to apply. 4760 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 4761 Found->getReturnType())) { 4762 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 4763 for (unsigned CovariantPathLength = PathLength + 1; 4764 CovariantPathLength != This.Designator.Entries.size(); 4765 ++CovariantPathLength) { 4766 const CXXRecordDecl *NextClass = 4767 getBaseClassType(This.Designator, CovariantPathLength); 4768 const CXXMethodDecl *Next = 4769 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 4770 if (Next && !Info.Ctx.hasSameUnqualifiedType( 4771 Next->getReturnType(), CovariantAdjustmentPath.back())) 4772 CovariantAdjustmentPath.push_back(Next->getReturnType()); 4773 } 4774 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 4775 CovariantAdjustmentPath.back())) 4776 CovariantAdjustmentPath.push_back(Found->getReturnType()); 4777 } 4778 4779 // Perform 'this' adjustment. 4780 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 4781 return nullptr; 4782 4783 return Callee; 4784 } 4785 4786 /// Perform the adjustment from a value returned by a virtual function to 4787 /// a value of the statically expected type, which may be a pointer or 4788 /// reference to a base class of the returned type. 4789 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 4790 APValue &Result, 4791 ArrayRef<QualType> Path) { 4792 assert(Result.isLValue() && 4793 "unexpected kind of APValue for covariant return"); 4794 if (Result.isNullPointer()) 4795 return true; 4796 4797 LValue LVal; 4798 LVal.setFrom(Info.Ctx, Result); 4799 4800 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 4801 for (unsigned I = 1; I != Path.size(); ++I) { 4802 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 4803 assert(OldClass && NewClass && "unexpected kind of covariant return"); 4804 if (OldClass != NewClass && 4805 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 4806 return false; 4807 OldClass = NewClass; 4808 } 4809 4810 LVal.moveInto(Result); 4811 return true; 4812 } 4813 4814 /// Determine whether \p Base, which is known to be a direct base class of 4815 /// \p Derived, is a public base class. 4816 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 4817 const CXXRecordDecl *Base) { 4818 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 4819 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 4820 if (BaseClass && declaresSameEntity(BaseClass, Base)) 4821 return BaseSpec.getAccessSpecifier() == AS_public; 4822 } 4823 llvm_unreachable("Base is not a direct base of Derived"); 4824 } 4825 4826 /// Apply the given dynamic cast operation on the provided lvalue. 4827 /// 4828 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 4829 /// to find a suitable target subobject. 4830 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 4831 LValue &Ptr) { 4832 // We can't do anything with a non-symbolic pointer value. 4833 SubobjectDesignator &D = Ptr.Designator; 4834 if (D.Invalid) 4835 return false; 4836 4837 // C++ [expr.dynamic.cast]p6: 4838 // If v is a null pointer value, the result is a null pointer value. 4839 if (Ptr.isNullPointer() && !E->isGLValue()) 4840 return true; 4841 4842 // For all the other cases, we need the pointer to point to an object within 4843 // its lifetime / period of construction / destruction, and we need to know 4844 // its dynamic type. 4845 Optional<DynamicType> DynType = 4846 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 4847 if (!DynType) 4848 return false; 4849 4850 // C++ [expr.dynamic.cast]p7: 4851 // If T is "pointer to cv void", then the result is a pointer to the most 4852 // derived object 4853 if (E->getType()->isVoidPointerType()) 4854 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 4855 4856 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 4857 assert(C && "dynamic_cast target is not void pointer nor class"); 4858 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 4859 4860 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 4861 // C++ [expr.dynamic.cast]p9: 4862 if (!E->isGLValue()) { 4863 // The value of a failed cast to pointer type is the null pointer value 4864 // of the required result type. 4865 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 4866 Ptr.setNull(E->getType(), TargetVal); 4867 return true; 4868 } 4869 4870 // A failed cast to reference type throws [...] std::bad_cast. 4871 unsigned DiagKind; 4872 if (!Paths && (declaresSameEntity(DynType->Type, C) || 4873 DynType->Type->isDerivedFrom(C))) 4874 DiagKind = 0; 4875 else if (!Paths || Paths->begin() == Paths->end()) 4876 DiagKind = 1; 4877 else if (Paths->isAmbiguous(CQT)) 4878 DiagKind = 2; 4879 else { 4880 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 4881 DiagKind = 3; 4882 } 4883 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 4884 << DiagKind << Ptr.Designator.getType(Info.Ctx) 4885 << Info.Ctx.getRecordType(DynType->Type) 4886 << E->getType().getUnqualifiedType(); 4887 return false; 4888 }; 4889 4890 // Runtime check, phase 1: 4891 // Walk from the base subobject towards the derived object looking for the 4892 // target type. 4893 for (int PathLength = Ptr.Designator.Entries.size(); 4894 PathLength >= (int)DynType->PathLength; --PathLength) { 4895 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 4896 if (declaresSameEntity(Class, C)) 4897 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 4898 // We can only walk across public inheritance edges. 4899 if (PathLength > (int)DynType->PathLength && 4900 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 4901 Class)) 4902 return RuntimeCheckFailed(nullptr); 4903 } 4904 4905 // Runtime check, phase 2: 4906 // Search the dynamic type for an unambiguous public base of type C. 4907 CXXBasePaths Paths(/*FindAmbiguities=*/true, 4908 /*RecordPaths=*/true, /*DetectVirtual=*/false); 4909 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 4910 Paths.front().Access == AS_public) { 4911 // Downcast to the dynamic type... 4912 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 4913 return false; 4914 // ... then upcast to the chosen base class subobject. 4915 for (CXXBasePathElement &Elem : Paths.front()) 4916 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 4917 return false; 4918 return true; 4919 } 4920 4921 // Otherwise, the runtime check fails. 4922 return RuntimeCheckFailed(&Paths); 4923 } 4924 4925 namespace { 4926 struct StartLifetimeOfUnionMemberHandler { 4927 const FieldDecl *Field; 4928 4929 static const AccessKinds AccessKind = AK_Assign; 4930 4931 APValue getDefaultInitValue(QualType SubobjType) { 4932 if (auto *RD = SubobjType->getAsCXXRecordDecl()) { 4933 if (RD->isUnion()) 4934 return APValue((const FieldDecl*)nullptr); 4935 4936 APValue Struct(APValue::UninitStruct(), RD->getNumBases(), 4937 std::distance(RD->field_begin(), RD->field_end())); 4938 4939 unsigned Index = 0; 4940 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4941 End = RD->bases_end(); I != End; ++I, ++Index) 4942 Struct.getStructBase(Index) = getDefaultInitValue(I->getType()); 4943 4944 for (const auto *I : RD->fields()) { 4945 if (I->isUnnamedBitfield()) 4946 continue; 4947 Struct.getStructField(I->getFieldIndex()) = 4948 getDefaultInitValue(I->getType()); 4949 } 4950 return Struct; 4951 } 4952 4953 if (auto *AT = dyn_cast_or_null<ConstantArrayType>( 4954 SubobjType->getAsArrayTypeUnsafe())) { 4955 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4956 if (Array.hasArrayFiller()) 4957 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType()); 4958 return Array; 4959 } 4960 4961 return APValue::IndeterminateValue(); 4962 } 4963 4964 typedef bool result_type; 4965 bool failed() { return false; } 4966 bool found(APValue &Subobj, QualType SubobjType) { 4967 // We are supposed to perform no initialization but begin the lifetime of 4968 // the object. We interpret that as meaning to do what default 4969 // initialization of the object would do if all constructors involved were 4970 // trivial: 4971 // * All base, non-variant member, and array element subobjects' lifetimes 4972 // begin 4973 // * No variant members' lifetimes begin 4974 // * All scalar subobjects whose lifetimes begin have indeterminate values 4975 assert(SubobjType->isUnionType()); 4976 if (!declaresSameEntity(Subobj.getUnionField(), Field)) 4977 Subobj.setUnion(Field, getDefaultInitValue(Field->getType())); 4978 return true; 4979 } 4980 bool found(APSInt &Value, QualType SubobjType) { 4981 llvm_unreachable("wrong value kind for union object"); 4982 } 4983 bool found(APFloat &Value, QualType SubobjType) { 4984 llvm_unreachable("wrong value kind for union object"); 4985 } 4986 }; 4987 } // end anonymous namespace 4988 4989 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 4990 4991 /// Handle a builtin simple-assignment or a call to a trivial assignment 4992 /// operator whose left-hand side might involve a union member access. If it 4993 /// does, implicitly start the lifetime of any accessed union elements per 4994 /// C++20 [class.union]5. 4995 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 4996 const LValue &LHS) { 4997 if (LHS.InvalidBase || LHS.Designator.Invalid) 4998 return false; 4999 5000 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5001 // C++ [class.union]p5: 5002 // define the set S(E) of subexpressions of E as follows: 5003 unsigned PathLength = LHS.Designator.Entries.size(); 5004 for (const Expr *E = LHSExpr; E != nullptr;) { 5005 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5006 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5007 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5008 if (!FD) 5009 break; 5010 5011 // ... and also contains A.B if B names a union member 5012 if (FD->getParent()->isUnion()) 5013 UnionPathLengths.push_back({PathLength - 1, FD}); 5014 5015 E = ME->getBase(); 5016 --PathLength; 5017 assert(declaresSameEntity(FD, 5018 LHS.Designator.Entries[PathLength] 5019 .getAsBaseOrMember().getPointer())); 5020 5021 // -- If E is of the form A[B] and is interpreted as a built-in array 5022 // subscripting operator, S(E) is [S(the array operand, if any)]. 5023 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5024 // Step over an ArrayToPointerDecay implicit cast. 5025 auto *Base = ASE->getBase()->IgnoreImplicit(); 5026 if (!Base->getType()->isArrayType()) 5027 break; 5028 5029 E = Base; 5030 --PathLength; 5031 5032 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5033 // Step over a derived-to-base conversion. 5034 E = ICE->getSubExpr(); 5035 if (ICE->getCastKind() == CK_NoOp) 5036 continue; 5037 if (ICE->getCastKind() != CK_DerivedToBase && 5038 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5039 break; 5040 // Walk path backwards as we walk up from the base to the derived class. 5041 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5042 --PathLength; 5043 (void)Elt; 5044 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5045 LHS.Designator.Entries[PathLength] 5046 .getAsBaseOrMember().getPointer())); 5047 } 5048 5049 // -- Otherwise, S(E) is empty. 5050 } else { 5051 break; 5052 } 5053 } 5054 5055 // Common case: no unions' lifetimes are started. 5056 if (UnionPathLengths.empty()) 5057 return true; 5058 5059 // if modification of X [would access an inactive union member], an object 5060 // of the type of X is implicitly created 5061 CompleteObject Obj = 5062 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5063 if (!Obj) 5064 return false; 5065 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5066 llvm::reverse(UnionPathLengths)) { 5067 // Form a designator for the union object. 5068 SubobjectDesignator D = LHS.Designator; 5069 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5070 5071 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second}; 5072 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5073 return false; 5074 } 5075 5076 return true; 5077 } 5078 5079 /// Determine if a class has any fields that might need to be copied by a 5080 /// trivial copy or move operation. 5081 static bool hasFields(const CXXRecordDecl *RD) { 5082 if (!RD || RD->isEmpty()) 5083 return false; 5084 for (auto *FD : RD->fields()) { 5085 if (FD->isUnnamedBitfield()) 5086 continue; 5087 return true; 5088 } 5089 for (auto &Base : RD->bases()) 5090 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 5091 return true; 5092 return false; 5093 } 5094 5095 namespace { 5096 typedef SmallVector<APValue, 8> ArgVector; 5097 } 5098 5099 /// EvaluateArgs - Evaluate the arguments to a function call. 5100 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 5101 EvalInfo &Info, const FunctionDecl *Callee) { 5102 bool Success = true; 5103 llvm::SmallBitVector ForbiddenNullArgs; 5104 if (Callee->hasAttr<NonNullAttr>()) { 5105 ForbiddenNullArgs.resize(Args.size()); 5106 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5107 if (!Attr->args_size()) { 5108 ForbiddenNullArgs.set(); 5109 break; 5110 } else 5111 for (auto Idx : Attr->args()) { 5112 unsigned ASTIdx = Idx.getASTIndex(); 5113 if (ASTIdx >= Args.size()) 5114 continue; 5115 ForbiddenNullArgs[ASTIdx] = 1; 5116 } 5117 } 5118 } 5119 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 5120 I != E; ++I) { 5121 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 5122 // If we're checking for a potential constant expression, evaluate all 5123 // initializers even if some of them fail. 5124 if (!Info.noteFailure()) 5125 return false; 5126 Success = false; 5127 } else if (!ForbiddenNullArgs.empty() && 5128 ForbiddenNullArgs[I - Args.begin()] && 5129 ArgValues[I - Args.begin()].isNullPointer()) { 5130 Info.CCEDiag(*I, diag::note_non_null_attribute_failed); 5131 if (!Info.noteFailure()) 5132 return false; 5133 Success = false; 5134 } 5135 } 5136 return Success; 5137 } 5138 5139 /// Evaluate a function call. 5140 static bool HandleFunctionCall(SourceLocation CallLoc, 5141 const FunctionDecl *Callee, const LValue *This, 5142 ArrayRef<const Expr*> Args, const Stmt *Body, 5143 EvalInfo &Info, APValue &Result, 5144 const LValue *ResultSlot) { 5145 ArgVector ArgValues(Args.size()); 5146 if (!EvaluateArgs(Args, ArgValues, Info, Callee)) 5147 return false; 5148 5149 if (!Info.CheckCallLimit(CallLoc)) 5150 return false; 5151 5152 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 5153 5154 // For a trivial copy or move assignment, perform an APValue copy. This is 5155 // essential for unions, where the operations performed by the assignment 5156 // operator cannot be represented as statements. 5157 // 5158 // Skip this for non-union classes with no fields; in that case, the defaulted 5159 // copy/move does not actually read the object. 5160 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5161 if (MD && MD->isDefaulted() && 5162 (MD->getParent()->isUnion() || 5163 (MD->isTrivial() && hasFields(MD->getParent())))) { 5164 assert(This && 5165 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5166 LValue RHS; 5167 RHS.setFrom(Info.Ctx, ArgValues[0]); 5168 APValue RHSValue; 5169 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 5170 RHS, RHSValue)) 5171 return false; 5172 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() && 5173 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5174 return false; 5175 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5176 RHSValue)) 5177 return false; 5178 This->moveInto(Result); 5179 return true; 5180 } else if (MD && isLambdaCallOperator(MD)) { 5181 // We're in a lambda; determine the lambda capture field maps unless we're 5182 // just constexpr checking a lambda's call operator. constexpr checking is 5183 // done before the captures have been added to the closure object (unless 5184 // we're inferring constexpr-ness), so we don't have access to them in this 5185 // case. But since we don't need the captures to constexpr check, we can 5186 // just ignore them. 5187 if (!Info.checkingPotentialConstantExpression()) 5188 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5189 Frame.LambdaThisCaptureField); 5190 } 5191 5192 StmtResult Ret = {Result, ResultSlot}; 5193 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5194 if (ESR == ESR_Succeeded) { 5195 if (Callee->getReturnType()->isVoidType()) 5196 return true; 5197 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5198 } 5199 return ESR == ESR_Returned; 5200 } 5201 5202 /// Evaluate a constructor call. 5203 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5204 APValue *ArgValues, 5205 const CXXConstructorDecl *Definition, 5206 EvalInfo &Info, APValue &Result) { 5207 SourceLocation CallLoc = E->getExprLoc(); 5208 if (!Info.CheckCallLimit(CallLoc)) 5209 return false; 5210 5211 const CXXRecordDecl *RD = Definition->getParent(); 5212 if (RD->getNumVBases()) { 5213 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5214 return false; 5215 } 5216 5217 EvalInfo::EvaluatingConstructorRAII EvalObj( 5218 Info, 5219 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5220 RD->getNumBases()); 5221 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5222 5223 // FIXME: Creating an APValue just to hold a nonexistent return value is 5224 // wasteful. 5225 APValue RetVal; 5226 StmtResult Ret = {RetVal, nullptr}; 5227 5228 // If it's a delegating constructor, delegate. 5229 if (Definition->isDelegatingConstructor()) { 5230 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5231 { 5232 FullExpressionRAII InitScope(Info); 5233 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 5234 return false; 5235 } 5236 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5237 } 5238 5239 // For a trivial copy or move constructor, perform an APValue copy. This is 5240 // essential for unions (or classes with anonymous union members), where the 5241 // operations performed by the constructor cannot be represented by 5242 // ctor-initializers. 5243 // 5244 // Skip this for empty non-union classes; we should not perform an 5245 // lvalue-to-rvalue conversion on them because their copy constructor does not 5246 // actually read them. 5247 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5248 (Definition->getParent()->isUnion() || 5249 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 5250 LValue RHS; 5251 RHS.setFrom(Info.Ctx, ArgValues[0]); 5252 return handleLValueToRValueConversion( 5253 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5254 RHS, Result); 5255 } 5256 5257 // Reserve space for the struct members. 5258 if (!RD->isUnion() && !Result.hasValue()) 5259 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5260 std::distance(RD->field_begin(), RD->field_end())); 5261 5262 if (RD->isInvalidDecl()) return false; 5263 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5264 5265 // A scope for temporaries lifetime-extended by reference members. 5266 BlockScopeRAII LifetimeExtendedScope(Info); 5267 5268 bool Success = true; 5269 unsigned BasesSeen = 0; 5270 #ifndef NDEBUG 5271 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5272 #endif 5273 for (const auto *I : Definition->inits()) { 5274 LValue Subobject = This; 5275 LValue SubobjectParent = This; 5276 APValue *Value = &Result; 5277 5278 // Determine the subobject to initialize. 5279 FieldDecl *FD = nullptr; 5280 if (I->isBaseInitializer()) { 5281 QualType BaseType(I->getBaseClass(), 0); 5282 #ifndef NDEBUG 5283 // Non-virtual base classes are initialized in the order in the class 5284 // definition. We have already checked for virtual base classes. 5285 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 5286 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 5287 "base class initializers not in expected order"); 5288 ++BaseIt; 5289 #endif 5290 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 5291 BaseType->getAsCXXRecordDecl(), &Layout)) 5292 return false; 5293 Value = &Result.getStructBase(BasesSeen++); 5294 } else if ((FD = I->getMember())) { 5295 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 5296 return false; 5297 if (RD->isUnion()) { 5298 Result = APValue(FD); 5299 Value = &Result.getUnionValue(); 5300 } else { 5301 Value = &Result.getStructField(FD->getFieldIndex()); 5302 } 5303 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 5304 // Walk the indirect field decl's chain to find the object to initialize, 5305 // and make sure we've initialized every step along it. 5306 auto IndirectFieldChain = IFD->chain(); 5307 for (auto *C : IndirectFieldChain) { 5308 FD = cast<FieldDecl>(C); 5309 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 5310 // Switch the union field if it differs. This happens if we had 5311 // preceding zero-initialization, and we're now initializing a union 5312 // subobject other than the first. 5313 // FIXME: In this case, the values of the other subobjects are 5314 // specified, since zero-initialization sets all padding bits to zero. 5315 if (!Value->hasValue() || 5316 (Value->isUnion() && Value->getUnionField() != FD)) { 5317 if (CD->isUnion()) 5318 *Value = APValue(FD); 5319 else 5320 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 5321 std::distance(CD->field_begin(), CD->field_end())); 5322 } 5323 // Store Subobject as its parent before updating it for the last element 5324 // in the chain. 5325 if (C == IndirectFieldChain.back()) 5326 SubobjectParent = Subobject; 5327 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 5328 return false; 5329 if (CD->isUnion()) 5330 Value = &Value->getUnionValue(); 5331 else 5332 Value = &Value->getStructField(FD->getFieldIndex()); 5333 } 5334 } else { 5335 llvm_unreachable("unknown base initializer kind"); 5336 } 5337 5338 // Need to override This for implicit field initializers as in this case 5339 // This refers to innermost anonymous struct/union containing initializer, 5340 // not to currently constructed class. 5341 const Expr *Init = I->getInit(); 5342 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 5343 isa<CXXDefaultInitExpr>(Init)); 5344 FullExpressionRAII InitScope(Info); 5345 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 5346 (FD && FD->isBitField() && 5347 !truncateBitfieldValue(Info, Init, *Value, FD))) { 5348 // If we're checking for a potential constant expression, evaluate all 5349 // initializers even if some of them fail. 5350 if (!Info.noteFailure()) 5351 return false; 5352 Success = false; 5353 } 5354 5355 // This is the point at which the dynamic type of the object becomes this 5356 // class type. 5357 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 5358 EvalObj.finishedConstructingBases(); 5359 } 5360 5361 return Success && 5362 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5363 } 5364 5365 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5366 ArrayRef<const Expr*> Args, 5367 const CXXConstructorDecl *Definition, 5368 EvalInfo &Info, APValue &Result) { 5369 ArgVector ArgValues(Args.size()); 5370 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 5371 return false; 5372 5373 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 5374 Info, Result); 5375 } 5376 5377 //===----------------------------------------------------------------------===// 5378 // Generic Evaluation 5379 //===----------------------------------------------------------------------===// 5380 namespace { 5381 5382 class BitCastBuffer { 5383 // FIXME: We're going to need bit-level granularity when we support 5384 // bit-fields. 5385 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 5386 // we don't support a host or target where that is the case. Still, we should 5387 // use a more generic type in case we ever do. 5388 SmallVector<Optional<unsigned char>, 32> Bytes; 5389 5390 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 5391 "Need at least 8 bit unsigned char"); 5392 5393 bool TargetIsLittleEndian; 5394 5395 public: 5396 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 5397 : Bytes(Width.getQuantity()), 5398 TargetIsLittleEndian(TargetIsLittleEndian) {} 5399 5400 LLVM_NODISCARD 5401 bool readObject(CharUnits Offset, CharUnits Width, 5402 SmallVectorImpl<unsigned char> &Output) const { 5403 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 5404 // If a byte of an integer is uninitialized, then the whole integer is 5405 // uninitalized. 5406 if (!Bytes[I.getQuantity()]) 5407 return false; 5408 Output.push_back(*Bytes[I.getQuantity()]); 5409 } 5410 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 5411 std::reverse(Output.begin(), Output.end()); 5412 return true; 5413 } 5414 5415 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 5416 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 5417 std::reverse(Input.begin(), Input.end()); 5418 5419 size_t Index = 0; 5420 for (unsigned char Byte : Input) { 5421 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 5422 Bytes[Offset.getQuantity() + Index] = Byte; 5423 ++Index; 5424 } 5425 } 5426 5427 size_t size() { return Bytes.size(); } 5428 }; 5429 5430 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 5431 /// target would represent the value at runtime. 5432 class APValueToBufferConverter { 5433 EvalInfo &Info; 5434 BitCastBuffer Buffer; 5435 const CastExpr *BCE; 5436 5437 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 5438 const CastExpr *BCE) 5439 : Info(Info), 5440 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 5441 BCE(BCE) {} 5442 5443 bool visit(const APValue &Val, QualType Ty) { 5444 return visit(Val, Ty, CharUnits::fromQuantity(0)); 5445 } 5446 5447 // Write out Val with type Ty into Buffer starting at Offset. 5448 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 5449 assert((size_t)Offset.getQuantity() <= Buffer.size()); 5450 5451 // As a special case, nullptr_t has an indeterminate value. 5452 if (Ty->isNullPtrType()) 5453 return true; 5454 5455 // Dig through Src to find the byte at SrcOffset. 5456 switch (Val.getKind()) { 5457 case APValue::Indeterminate: 5458 case APValue::None: 5459 return true; 5460 5461 case APValue::Int: 5462 return visitInt(Val.getInt(), Ty, Offset); 5463 case APValue::Float: 5464 return visitFloat(Val.getFloat(), Ty, Offset); 5465 case APValue::Array: 5466 return visitArray(Val, Ty, Offset); 5467 case APValue::Struct: 5468 return visitRecord(Val, Ty, Offset); 5469 5470 case APValue::ComplexInt: 5471 case APValue::ComplexFloat: 5472 case APValue::Vector: 5473 case APValue::FixedPoint: 5474 // FIXME: We should support these. 5475 5476 case APValue::Union: 5477 case APValue::MemberPointer: 5478 case APValue::AddrLabelDiff: { 5479 Info.FFDiag(BCE->getBeginLoc(), 5480 diag::note_constexpr_bit_cast_unsupported_type) 5481 << Ty; 5482 return false; 5483 } 5484 5485 case APValue::LValue: 5486 llvm_unreachable("LValue subobject in bit_cast?"); 5487 } 5488 llvm_unreachable("Unhandled APValue::ValueKind"); 5489 } 5490 5491 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 5492 const RecordDecl *RD = Ty->getAsRecordDecl(); 5493 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5494 5495 // Visit the base classes. 5496 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5497 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 5498 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 5499 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 5500 5501 if (!visitRecord(Val.getStructBase(I), BS.getType(), 5502 Layout.getBaseClassOffset(BaseDecl) + Offset)) 5503 return false; 5504 } 5505 } 5506 5507 // Visit the fields. 5508 unsigned FieldIdx = 0; 5509 for (FieldDecl *FD : RD->fields()) { 5510 if (FD->isBitField()) { 5511 Info.FFDiag(BCE->getBeginLoc(), 5512 diag::note_constexpr_bit_cast_unsupported_bitfield); 5513 return false; 5514 } 5515 5516 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 5517 5518 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 5519 "only bit-fields can have sub-char alignment"); 5520 CharUnits FieldOffset = 5521 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 5522 QualType FieldTy = FD->getType(); 5523 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 5524 return false; 5525 ++FieldIdx; 5526 } 5527 5528 return true; 5529 } 5530 5531 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 5532 const auto *CAT = 5533 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 5534 if (!CAT) 5535 return false; 5536 5537 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 5538 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 5539 unsigned ArraySize = Val.getArraySize(); 5540 // First, initialize the initialized elements. 5541 for (unsigned I = 0; I != NumInitializedElts; ++I) { 5542 const APValue &SubObj = Val.getArrayInitializedElt(I); 5543 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 5544 return false; 5545 } 5546 5547 // Next, initialize the rest of the array using the filler. 5548 if (Val.hasArrayFiller()) { 5549 const APValue &Filler = Val.getArrayFiller(); 5550 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 5551 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 5552 return false; 5553 } 5554 } 5555 5556 return true; 5557 } 5558 5559 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 5560 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty); 5561 SmallVector<unsigned char, 8> Bytes(Width.getQuantity()); 5562 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity()); 5563 Buffer.writeObject(Offset, Bytes); 5564 return true; 5565 } 5566 5567 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 5568 APSInt AsInt(Val.bitcastToAPInt()); 5569 return visitInt(AsInt, Ty, Offset); 5570 } 5571 5572 public: 5573 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 5574 const CastExpr *BCE) { 5575 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 5576 APValueToBufferConverter Converter(Info, DstSize, BCE); 5577 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 5578 return None; 5579 return Converter.Buffer; 5580 } 5581 }; 5582 5583 /// Write an BitCastBuffer into an APValue. 5584 class BufferToAPValueConverter { 5585 EvalInfo &Info; 5586 const BitCastBuffer &Buffer; 5587 const CastExpr *BCE; 5588 5589 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 5590 const CastExpr *BCE) 5591 : Info(Info), Buffer(Buffer), BCE(BCE) {} 5592 5593 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 5594 // with an invalid type, so anything left is a deficiency on our part (FIXME). 5595 // Ideally this will be unreachable. 5596 llvm::NoneType unsupportedType(QualType Ty) { 5597 Info.FFDiag(BCE->getBeginLoc(), 5598 diag::note_constexpr_bit_cast_unsupported_type) 5599 << Ty; 5600 return None; 5601 } 5602 5603 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 5604 const EnumType *EnumSugar = nullptr) { 5605 if (T->isNullPtrType()) { 5606 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 5607 return APValue((Expr *)nullptr, 5608 /*Offset=*/CharUnits::fromQuantity(NullValue), 5609 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 5610 } 5611 5612 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 5613 SmallVector<uint8_t, 8> Bytes; 5614 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 5615 // If this is std::byte or unsigned char, then its okay to store an 5616 // indeterminate value. 5617 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 5618 bool IsUChar = 5619 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 5620 T->isSpecificBuiltinType(BuiltinType::Char_U)); 5621 if (!IsStdByte && !IsUChar) { 5622 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 5623 Info.FFDiag(BCE->getExprLoc(), 5624 diag::note_constexpr_bit_cast_indet_dest) 5625 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 5626 return None; 5627 } 5628 5629 return APValue::IndeterminateValue(); 5630 } 5631 5632 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 5633 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 5634 5635 if (T->isIntegralOrEnumerationType()) { 5636 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 5637 return APValue(Val); 5638 } 5639 5640 if (T->isRealFloatingType()) { 5641 const llvm::fltSemantics &Semantics = 5642 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 5643 return APValue(APFloat(Semantics, Val)); 5644 } 5645 5646 return unsupportedType(QualType(T, 0)); 5647 } 5648 5649 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 5650 const RecordDecl *RD = RTy->getAsRecordDecl(); 5651 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5652 5653 unsigned NumBases = 0; 5654 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 5655 NumBases = CXXRD->getNumBases(); 5656 5657 APValue ResultVal(APValue::UninitStruct(), NumBases, 5658 std::distance(RD->field_begin(), RD->field_end())); 5659 5660 // Visit the base classes. 5661 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5662 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 5663 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 5664 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 5665 if (BaseDecl->isEmpty() || 5666 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 5667 continue; 5668 5669 Optional<APValue> SubObj = visitType( 5670 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 5671 if (!SubObj) 5672 return None; 5673 ResultVal.getStructBase(I) = *SubObj; 5674 } 5675 } 5676 5677 // Visit the fields. 5678 unsigned FieldIdx = 0; 5679 for (FieldDecl *FD : RD->fields()) { 5680 // FIXME: We don't currently support bit-fields. A lot of the logic for 5681 // this is in CodeGen, so we need to factor it around. 5682 if (FD->isBitField()) { 5683 Info.FFDiag(BCE->getBeginLoc(), 5684 diag::note_constexpr_bit_cast_unsupported_bitfield); 5685 return None; 5686 } 5687 5688 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 5689 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 5690 5691 CharUnits FieldOffset = 5692 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 5693 Offset; 5694 QualType FieldTy = FD->getType(); 5695 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 5696 if (!SubObj) 5697 return None; 5698 ResultVal.getStructField(FieldIdx) = *SubObj; 5699 ++FieldIdx; 5700 } 5701 5702 return ResultVal; 5703 } 5704 5705 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 5706 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 5707 assert(!RepresentationType.isNull() && 5708 "enum forward decl should be caught by Sema"); 5709 const BuiltinType *AsBuiltin = 5710 RepresentationType.getCanonicalType()->getAs<BuiltinType>(); 5711 assert(AsBuiltin && "non-integral enum underlying type?"); 5712 // Recurse into the underlying type. Treat std::byte transparently as 5713 // unsigned char. 5714 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 5715 } 5716 5717 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 5718 size_t Size = Ty->getSize().getLimitedValue(); 5719 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 5720 5721 APValue ArrayValue(APValue::UninitArray(), Size, Size); 5722 for (size_t I = 0; I != Size; ++I) { 5723 Optional<APValue> ElementValue = 5724 visitType(Ty->getElementType(), Offset + I * ElementWidth); 5725 if (!ElementValue) 5726 return None; 5727 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 5728 } 5729 5730 return ArrayValue; 5731 } 5732 5733 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 5734 return unsupportedType(QualType(Ty, 0)); 5735 } 5736 5737 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 5738 QualType Can = Ty.getCanonicalType(); 5739 5740 switch (Can->getTypeClass()) { 5741 #define TYPE(Class, Base) \ 5742 case Type::Class: \ 5743 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 5744 #define ABSTRACT_TYPE(Class, Base) 5745 #define NON_CANONICAL_TYPE(Class, Base) \ 5746 case Type::Class: \ 5747 llvm_unreachable("non-canonical type should be impossible!"); 5748 #define DEPENDENT_TYPE(Class, Base) \ 5749 case Type::Class: \ 5750 llvm_unreachable( \ 5751 "dependent types aren't supported in the constant evaluator!"); 5752 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 5753 case Type::Class: \ 5754 llvm_unreachable("either dependent or not canonical!"); 5755 #include "clang/AST/TypeNodes.def" 5756 } 5757 llvm_unreachable("Unhandled Type::TypeClass"); 5758 } 5759 5760 public: 5761 // Pull out a full value of type DstType. 5762 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 5763 const CastExpr *BCE) { 5764 BufferToAPValueConverter Converter(Info, Buffer, BCE); 5765 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 5766 } 5767 }; 5768 5769 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 5770 QualType Ty, EvalInfo *Info, 5771 const ASTContext &Ctx, 5772 bool CheckingDest) { 5773 Ty = Ty.getCanonicalType(); 5774 5775 auto diag = [&](int Reason) { 5776 if (Info) 5777 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 5778 << CheckingDest << (Reason == 4) << Reason; 5779 return false; 5780 }; 5781 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 5782 if (Info) 5783 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 5784 << NoteTy << Construct << Ty; 5785 return false; 5786 }; 5787 5788 if (Ty->isUnionType()) 5789 return diag(0); 5790 if (Ty->isPointerType()) 5791 return diag(1); 5792 if (Ty->isMemberPointerType()) 5793 return diag(2); 5794 if (Ty.isVolatileQualified()) 5795 return diag(3); 5796 5797 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 5798 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 5799 for (CXXBaseSpecifier &BS : CXXRD->bases()) 5800 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 5801 CheckingDest)) 5802 return note(1, BS.getType(), BS.getBeginLoc()); 5803 } 5804 for (FieldDecl *FD : Record->fields()) { 5805 if (FD->getType()->isReferenceType()) 5806 return diag(4); 5807 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 5808 CheckingDest)) 5809 return note(0, FD->getType(), FD->getBeginLoc()); 5810 } 5811 } 5812 5813 if (Ty->isArrayType() && 5814 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 5815 Info, Ctx, CheckingDest)) 5816 return false; 5817 5818 return true; 5819 } 5820 5821 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 5822 const ASTContext &Ctx, 5823 const CastExpr *BCE) { 5824 bool DestOK = checkBitCastConstexprEligibilityType( 5825 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 5826 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 5827 BCE->getBeginLoc(), 5828 BCE->getSubExpr()->getType(), Info, Ctx, false); 5829 return SourceOK; 5830 } 5831 5832 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 5833 APValue &SourceValue, 5834 const CastExpr *BCE) { 5835 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 5836 "no host or target supports non 8-bit chars"); 5837 assert(SourceValue.isLValue() && 5838 "LValueToRValueBitcast requires an lvalue operand!"); 5839 5840 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 5841 return false; 5842 5843 LValue SourceLValue; 5844 APValue SourceRValue; 5845 SourceLValue.setFrom(Info.Ctx, SourceValue); 5846 if (!handleLValueToRValueConversion(Info, BCE, 5847 BCE->getSubExpr()->getType().withConst(), 5848 SourceLValue, SourceRValue)) 5849 return false; 5850 5851 // Read out SourceValue into a char buffer. 5852 Optional<BitCastBuffer> Buffer = 5853 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 5854 if (!Buffer) 5855 return false; 5856 5857 // Write out the buffer into a new APValue. 5858 Optional<APValue> MaybeDestValue = 5859 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 5860 if (!MaybeDestValue) 5861 return false; 5862 5863 DestValue = std::move(*MaybeDestValue); 5864 return true; 5865 } 5866 5867 template <class Derived> 5868 class ExprEvaluatorBase 5869 : public ConstStmtVisitor<Derived, bool> { 5870 private: 5871 Derived &getDerived() { return static_cast<Derived&>(*this); } 5872 bool DerivedSuccess(const APValue &V, const Expr *E) { 5873 return getDerived().Success(V, E); 5874 } 5875 bool DerivedZeroInitialization(const Expr *E) { 5876 return getDerived().ZeroInitialization(E); 5877 } 5878 5879 // Check whether a conditional operator with a non-constant condition is a 5880 // potential constant expression. If neither arm is a potential constant 5881 // expression, then the conditional operator is not either. 5882 template<typename ConditionalOperator> 5883 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 5884 assert(Info.checkingPotentialConstantExpression()); 5885 5886 // Speculatively evaluate both arms. 5887 SmallVector<PartialDiagnosticAt, 8> Diag; 5888 { 5889 SpeculativeEvaluationRAII Speculate(Info, &Diag); 5890 StmtVisitorTy::Visit(E->getFalseExpr()); 5891 if (Diag.empty()) 5892 return; 5893 } 5894 5895 { 5896 SpeculativeEvaluationRAII Speculate(Info, &Diag); 5897 Diag.clear(); 5898 StmtVisitorTy::Visit(E->getTrueExpr()); 5899 if (Diag.empty()) 5900 return; 5901 } 5902 5903 Error(E, diag::note_constexpr_conditional_never_const); 5904 } 5905 5906 5907 template<typename ConditionalOperator> 5908 bool HandleConditionalOperator(const ConditionalOperator *E) { 5909 bool BoolResult; 5910 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 5911 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 5912 CheckPotentialConstantConditional(E); 5913 return false; 5914 } 5915 if (Info.noteFailure()) { 5916 StmtVisitorTy::Visit(E->getTrueExpr()); 5917 StmtVisitorTy::Visit(E->getFalseExpr()); 5918 } 5919 return false; 5920 } 5921 5922 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 5923 return StmtVisitorTy::Visit(EvalExpr); 5924 } 5925 5926 protected: 5927 EvalInfo &Info; 5928 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 5929 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 5930 5931 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 5932 return Info.CCEDiag(E, D); 5933 } 5934 5935 bool ZeroInitialization(const Expr *E) { return Error(E); } 5936 5937 public: 5938 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 5939 5940 EvalInfo &getEvalInfo() { return Info; } 5941 5942 /// Report an evaluation error. This should only be called when an error is 5943 /// first discovered. When propagating an error, just return false. 5944 bool Error(const Expr *E, diag::kind D) { 5945 Info.FFDiag(E, D); 5946 return false; 5947 } 5948 bool Error(const Expr *E) { 5949 return Error(E, diag::note_invalid_subexpr_in_const_expr); 5950 } 5951 5952 bool VisitStmt(const Stmt *) { 5953 llvm_unreachable("Expression evaluator should not be called on stmts"); 5954 } 5955 bool VisitExpr(const Expr *E) { 5956 return Error(E); 5957 } 5958 5959 bool VisitConstantExpr(const ConstantExpr *E) 5960 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5961 bool VisitParenExpr(const ParenExpr *E) 5962 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5963 bool VisitUnaryExtension(const UnaryOperator *E) 5964 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5965 bool VisitUnaryPlus(const UnaryOperator *E) 5966 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5967 bool VisitChooseExpr(const ChooseExpr *E) 5968 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 5969 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 5970 { return StmtVisitorTy::Visit(E->getResultExpr()); } 5971 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 5972 { return StmtVisitorTy::Visit(E->getReplacement()); } 5973 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 5974 TempVersionRAII RAII(*Info.CurrentCall); 5975 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 5976 return StmtVisitorTy::Visit(E->getExpr()); 5977 } 5978 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 5979 TempVersionRAII RAII(*Info.CurrentCall); 5980 // The initializer may not have been parsed yet, or might be erroneous. 5981 if (!E->getExpr()) 5982 return Error(E); 5983 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 5984 return StmtVisitorTy::Visit(E->getExpr()); 5985 } 5986 5987 // We cannot create any objects for which cleanups are required, so there is 5988 // nothing to do here; all cleanups must come from unevaluated subexpressions. 5989 bool VisitExprWithCleanups(const ExprWithCleanups *E) 5990 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5991 5992 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 5993 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 5994 return static_cast<Derived*>(this)->VisitCastExpr(E); 5995 } 5996 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 5997 if (!Info.Ctx.getLangOpts().CPlusPlus2a) 5998 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 5999 return static_cast<Derived*>(this)->VisitCastExpr(E); 6000 } 6001 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 6002 return static_cast<Derived*>(this)->VisitCastExpr(E); 6003 } 6004 6005 bool VisitBinaryOperator(const BinaryOperator *E) { 6006 switch (E->getOpcode()) { 6007 default: 6008 return Error(E); 6009 6010 case BO_Comma: 6011 VisitIgnoredValue(E->getLHS()); 6012 return StmtVisitorTy::Visit(E->getRHS()); 6013 6014 case BO_PtrMemD: 6015 case BO_PtrMemI: { 6016 LValue Obj; 6017 if (!HandleMemberPointerAccess(Info, E, Obj)) 6018 return false; 6019 APValue Result; 6020 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 6021 return false; 6022 return DerivedSuccess(Result, E); 6023 } 6024 } 6025 } 6026 6027 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 6028 // Evaluate and cache the common expression. We treat it as a temporary, 6029 // even though it's not quite the same thing. 6030 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 6031 Info, E->getCommon())) 6032 return false; 6033 6034 return HandleConditionalOperator(E); 6035 } 6036 6037 bool VisitConditionalOperator(const ConditionalOperator *E) { 6038 bool IsBcpCall = false; 6039 // If the condition (ignoring parens) is a __builtin_constant_p call, 6040 // the result is a constant expression if it can be folded without 6041 // side-effects. This is an important GNU extension. See GCC PR38377 6042 // for discussion. 6043 if (const CallExpr *CallCE = 6044 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 6045 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 6046 IsBcpCall = true; 6047 6048 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 6049 // constant expression; we can't check whether it's potentially foldable. 6050 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 6051 return false; 6052 6053 FoldConstant Fold(Info, IsBcpCall); 6054 if (!HandleConditionalOperator(E)) { 6055 Fold.keepDiagnostics(); 6056 return false; 6057 } 6058 6059 return true; 6060 } 6061 6062 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 6063 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 6064 return DerivedSuccess(*Value, E); 6065 6066 const Expr *Source = E->getSourceExpr(); 6067 if (!Source) 6068 return Error(E); 6069 if (Source == E) { // sanity checking. 6070 assert(0 && "OpaqueValueExpr recursively refers to itself"); 6071 return Error(E); 6072 } 6073 return StmtVisitorTy::Visit(Source); 6074 } 6075 6076 bool VisitCallExpr(const CallExpr *E) { 6077 APValue Result; 6078 if (!handleCallExpr(E, Result, nullptr)) 6079 return false; 6080 return DerivedSuccess(Result, E); 6081 } 6082 6083 bool handleCallExpr(const CallExpr *E, APValue &Result, 6084 const LValue *ResultSlot) { 6085 const Expr *Callee = E->getCallee()->IgnoreParens(); 6086 QualType CalleeType = Callee->getType(); 6087 6088 const FunctionDecl *FD = nullptr; 6089 LValue *This = nullptr, ThisVal; 6090 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 6091 bool HasQualifier = false; 6092 6093 // Extract function decl and 'this' pointer from the callee. 6094 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 6095 const CXXMethodDecl *Member = nullptr; 6096 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 6097 // Explicit bound member calls, such as x.f() or p->g(); 6098 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 6099 return false; 6100 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 6101 if (!Member) 6102 return Error(Callee); 6103 This = &ThisVal; 6104 HasQualifier = ME->hasQualifier(); 6105 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 6106 // Indirect bound member calls ('.*' or '->*'). 6107 Member = dyn_cast_or_null<CXXMethodDecl>( 6108 HandleMemberPointerAccess(Info, BE, ThisVal, false)); 6109 if (!Member) 6110 return Error(Callee); 6111 This = &ThisVal; 6112 } else 6113 return Error(Callee); 6114 FD = Member; 6115 } else if (CalleeType->isFunctionPointerType()) { 6116 LValue Call; 6117 if (!EvaluatePointer(Callee, Call, Info)) 6118 return false; 6119 6120 if (!Call.getLValueOffset().isZero()) 6121 return Error(Callee); 6122 FD = dyn_cast_or_null<FunctionDecl>( 6123 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 6124 if (!FD) 6125 return Error(Callee); 6126 // Don't call function pointers which have been cast to some other type. 6127 // Per DR (no number yet), the caller and callee can differ in noexcept. 6128 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 6129 CalleeType->getPointeeType(), FD->getType())) { 6130 return Error(E); 6131 } 6132 6133 // Overloaded operator calls to member functions are represented as normal 6134 // calls with '*this' as the first argument. 6135 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6136 if (MD && !MD->isStatic()) { 6137 // FIXME: When selecting an implicit conversion for an overloaded 6138 // operator delete, we sometimes try to evaluate calls to conversion 6139 // operators without a 'this' parameter! 6140 if (Args.empty()) 6141 return Error(E); 6142 6143 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 6144 return false; 6145 This = &ThisVal; 6146 Args = Args.slice(1); 6147 } else if (MD && MD->isLambdaStaticInvoker()) { 6148 // Map the static invoker for the lambda back to the call operator. 6149 // Conveniently, we don't have to slice out the 'this' argument (as is 6150 // being done for the non-static case), since a static member function 6151 // doesn't have an implicit argument passed in. 6152 const CXXRecordDecl *ClosureClass = MD->getParent(); 6153 assert( 6154 ClosureClass->captures_begin() == ClosureClass->captures_end() && 6155 "Number of captures must be zero for conversion to function-ptr"); 6156 6157 const CXXMethodDecl *LambdaCallOp = 6158 ClosureClass->getLambdaCallOperator(); 6159 6160 // Set 'FD', the function that will be called below, to the call 6161 // operator. If the closure object represents a generic lambda, find 6162 // the corresponding specialization of the call operator. 6163 6164 if (ClosureClass->isGenericLambda()) { 6165 assert(MD->isFunctionTemplateSpecialization() && 6166 "A generic lambda's static-invoker function must be a " 6167 "template specialization"); 6168 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 6169 FunctionTemplateDecl *CallOpTemplate = 6170 LambdaCallOp->getDescribedFunctionTemplate(); 6171 void *InsertPos = nullptr; 6172 FunctionDecl *CorrespondingCallOpSpecialization = 6173 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 6174 assert(CorrespondingCallOpSpecialization && 6175 "We must always have a function call operator specialization " 6176 "that corresponds to our static invoker specialization"); 6177 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 6178 } else 6179 FD = LambdaCallOp; 6180 } 6181 } else 6182 return Error(E); 6183 6184 SmallVector<QualType, 4> CovariantAdjustmentPath; 6185 if (This) { 6186 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 6187 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 6188 // Perform virtual dispatch, if necessary. 6189 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 6190 CovariantAdjustmentPath); 6191 if (!FD) 6192 return false; 6193 } else { 6194 // Check that the 'this' pointer points to an object of the right type. 6195 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This)) 6196 return false; 6197 } 6198 } 6199 6200 const FunctionDecl *Definition = nullptr; 6201 Stmt *Body = FD->getBody(Definition); 6202 6203 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 6204 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 6205 Result, ResultSlot)) 6206 return false; 6207 6208 if (!CovariantAdjustmentPath.empty() && 6209 !HandleCovariantReturnAdjustment(Info, E, Result, 6210 CovariantAdjustmentPath)) 6211 return false; 6212 6213 return true; 6214 } 6215 6216 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 6217 return StmtVisitorTy::Visit(E->getInitializer()); 6218 } 6219 bool VisitInitListExpr(const InitListExpr *E) { 6220 if (E->getNumInits() == 0) 6221 return DerivedZeroInitialization(E); 6222 if (E->getNumInits() == 1) 6223 return StmtVisitorTy::Visit(E->getInit(0)); 6224 return Error(E); 6225 } 6226 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 6227 return DerivedZeroInitialization(E); 6228 } 6229 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 6230 return DerivedZeroInitialization(E); 6231 } 6232 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 6233 return DerivedZeroInitialization(E); 6234 } 6235 6236 /// A member expression where the object is a prvalue is itself a prvalue. 6237 bool VisitMemberExpr(const MemberExpr *E) { 6238 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 6239 "missing temporary materialization conversion"); 6240 assert(!E->isArrow() && "missing call to bound member function?"); 6241 6242 APValue Val; 6243 if (!Evaluate(Val, Info, E->getBase())) 6244 return false; 6245 6246 QualType BaseTy = E->getBase()->getType(); 6247 6248 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 6249 if (!FD) return Error(E); 6250 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 6251 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 6252 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 6253 6254 // Note: there is no lvalue base here. But this case should only ever 6255 // happen in C or in C++98, where we cannot be evaluating a constexpr 6256 // constructor, which is the only case the base matters. 6257 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 6258 SubobjectDesignator Designator(BaseTy); 6259 Designator.addDeclUnchecked(FD); 6260 6261 APValue Result; 6262 return extractSubobject(Info, E, Obj, Designator, Result) && 6263 DerivedSuccess(Result, E); 6264 } 6265 6266 bool VisitCastExpr(const CastExpr *E) { 6267 switch (E->getCastKind()) { 6268 default: 6269 break; 6270 6271 case CK_AtomicToNonAtomic: { 6272 APValue AtomicVal; 6273 // This does not need to be done in place even for class/array types: 6274 // atomic-to-non-atomic conversion implies copying the object 6275 // representation. 6276 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 6277 return false; 6278 return DerivedSuccess(AtomicVal, E); 6279 } 6280 6281 case CK_NoOp: 6282 case CK_UserDefinedConversion: 6283 return StmtVisitorTy::Visit(E->getSubExpr()); 6284 6285 case CK_LValueToRValue: { 6286 LValue LVal; 6287 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 6288 return false; 6289 APValue RVal; 6290 // Note, we use the subexpression's type in order to retain cv-qualifiers. 6291 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 6292 LVal, RVal)) 6293 return false; 6294 return DerivedSuccess(RVal, E); 6295 } 6296 case CK_LValueToRValueBitCast: { 6297 APValue DestValue, SourceValue; 6298 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 6299 return false; 6300 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 6301 return false; 6302 return DerivedSuccess(DestValue, E); 6303 } 6304 } 6305 6306 return Error(E); 6307 } 6308 6309 bool VisitUnaryPostInc(const UnaryOperator *UO) { 6310 return VisitUnaryPostIncDec(UO); 6311 } 6312 bool VisitUnaryPostDec(const UnaryOperator *UO) { 6313 return VisitUnaryPostIncDec(UO); 6314 } 6315 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 6316 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6317 return Error(UO); 6318 6319 LValue LVal; 6320 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 6321 return false; 6322 APValue RVal; 6323 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 6324 UO->isIncrementOp(), &RVal)) 6325 return false; 6326 return DerivedSuccess(RVal, UO); 6327 } 6328 6329 bool VisitStmtExpr(const StmtExpr *E) { 6330 // We will have checked the full-expressions inside the statement expression 6331 // when they were completed, and don't need to check them again now. 6332 if (Info.checkingForOverflow()) 6333 return Error(E); 6334 6335 BlockScopeRAII Scope(Info); 6336 const CompoundStmt *CS = E->getSubStmt(); 6337 if (CS->body_empty()) 6338 return true; 6339 6340 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 6341 BE = CS->body_end(); 6342 /**/; ++BI) { 6343 if (BI + 1 == BE) { 6344 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 6345 if (!FinalExpr) { 6346 Info.FFDiag((*BI)->getBeginLoc(), 6347 diag::note_constexpr_stmt_expr_unsupported); 6348 return false; 6349 } 6350 return this->Visit(FinalExpr); 6351 } 6352 6353 APValue ReturnValue; 6354 StmtResult Result = { ReturnValue, nullptr }; 6355 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 6356 if (ESR != ESR_Succeeded) { 6357 // FIXME: If the statement-expression terminated due to 'return', 6358 // 'break', or 'continue', it would be nice to propagate that to 6359 // the outer statement evaluation rather than bailing out. 6360 if (ESR != ESR_Failed) 6361 Info.FFDiag((*BI)->getBeginLoc(), 6362 diag::note_constexpr_stmt_expr_unsupported); 6363 return false; 6364 } 6365 } 6366 6367 llvm_unreachable("Return from function from the loop above."); 6368 } 6369 6370 /// Visit a value which is evaluated, but whose value is ignored. 6371 void VisitIgnoredValue(const Expr *E) { 6372 EvaluateIgnoredValue(Info, E); 6373 } 6374 6375 /// Potentially visit a MemberExpr's base expression. 6376 void VisitIgnoredBaseExpression(const Expr *E) { 6377 // While MSVC doesn't evaluate the base expression, it does diagnose the 6378 // presence of side-effecting behavior. 6379 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 6380 return; 6381 VisitIgnoredValue(E); 6382 } 6383 }; 6384 6385 } // namespace 6386 6387 //===----------------------------------------------------------------------===// 6388 // Common base class for lvalue and temporary evaluation. 6389 //===----------------------------------------------------------------------===// 6390 namespace { 6391 template<class Derived> 6392 class LValueExprEvaluatorBase 6393 : public ExprEvaluatorBase<Derived> { 6394 protected: 6395 LValue &Result; 6396 bool InvalidBaseOK; 6397 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 6398 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 6399 6400 bool Success(APValue::LValueBase B) { 6401 Result.set(B); 6402 return true; 6403 } 6404 6405 bool evaluatePointer(const Expr *E, LValue &Result) { 6406 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 6407 } 6408 6409 public: 6410 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 6411 : ExprEvaluatorBaseTy(Info), Result(Result), 6412 InvalidBaseOK(InvalidBaseOK) {} 6413 6414 bool Success(const APValue &V, const Expr *E) { 6415 Result.setFrom(this->Info.Ctx, V); 6416 return true; 6417 } 6418 6419 bool VisitMemberExpr(const MemberExpr *E) { 6420 // Handle non-static data members. 6421 QualType BaseTy; 6422 bool EvalOK; 6423 if (E->isArrow()) { 6424 EvalOK = evaluatePointer(E->getBase(), Result); 6425 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 6426 } else if (E->getBase()->isRValue()) { 6427 assert(E->getBase()->getType()->isRecordType()); 6428 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 6429 BaseTy = E->getBase()->getType(); 6430 } else { 6431 EvalOK = this->Visit(E->getBase()); 6432 BaseTy = E->getBase()->getType(); 6433 } 6434 if (!EvalOK) { 6435 if (!InvalidBaseOK) 6436 return false; 6437 Result.setInvalid(E); 6438 return true; 6439 } 6440 6441 const ValueDecl *MD = E->getMemberDecl(); 6442 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 6443 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 6444 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 6445 (void)BaseTy; 6446 if (!HandleLValueMember(this->Info, E, Result, FD)) 6447 return false; 6448 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 6449 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 6450 return false; 6451 } else 6452 return this->Error(E); 6453 6454 if (MD->getType()->isReferenceType()) { 6455 APValue RefValue; 6456 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 6457 RefValue)) 6458 return false; 6459 return Success(RefValue, E); 6460 } 6461 return true; 6462 } 6463 6464 bool VisitBinaryOperator(const BinaryOperator *E) { 6465 switch (E->getOpcode()) { 6466 default: 6467 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 6468 6469 case BO_PtrMemD: 6470 case BO_PtrMemI: 6471 return HandleMemberPointerAccess(this->Info, E, Result); 6472 } 6473 } 6474 6475 bool VisitCastExpr(const CastExpr *E) { 6476 switch (E->getCastKind()) { 6477 default: 6478 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6479 6480 case CK_DerivedToBase: 6481 case CK_UncheckedDerivedToBase: 6482 if (!this->Visit(E->getSubExpr())) 6483 return false; 6484 6485 // Now figure out the necessary offset to add to the base LV to get from 6486 // the derived class to the base class. 6487 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 6488 Result); 6489 } 6490 } 6491 }; 6492 } 6493 6494 //===----------------------------------------------------------------------===// 6495 // LValue Evaluation 6496 // 6497 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 6498 // function designators (in C), decl references to void objects (in C), and 6499 // temporaries (if building with -Wno-address-of-temporary). 6500 // 6501 // LValue evaluation produces values comprising a base expression of one of the 6502 // following types: 6503 // - Declarations 6504 // * VarDecl 6505 // * FunctionDecl 6506 // - Literals 6507 // * CompoundLiteralExpr in C (and in global scope in C++) 6508 // * StringLiteral 6509 // * PredefinedExpr 6510 // * ObjCStringLiteralExpr 6511 // * ObjCEncodeExpr 6512 // * AddrLabelExpr 6513 // * BlockExpr 6514 // * CallExpr for a MakeStringConstant builtin 6515 // - typeid(T) expressions, as TypeInfoLValues 6516 // - Locals and temporaries 6517 // * MaterializeTemporaryExpr 6518 // * Any Expr, with a CallIndex indicating the function in which the temporary 6519 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 6520 // from the AST (FIXME). 6521 // * A MaterializeTemporaryExpr that has static storage duration, with no 6522 // CallIndex, for a lifetime-extended temporary. 6523 // plus an offset in bytes. 6524 //===----------------------------------------------------------------------===// 6525 namespace { 6526 class LValueExprEvaluator 6527 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 6528 public: 6529 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 6530 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 6531 6532 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 6533 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 6534 6535 bool VisitDeclRefExpr(const DeclRefExpr *E); 6536 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 6537 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 6538 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 6539 bool VisitMemberExpr(const MemberExpr *E); 6540 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 6541 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 6542 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 6543 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 6544 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 6545 bool VisitUnaryDeref(const UnaryOperator *E); 6546 bool VisitUnaryReal(const UnaryOperator *E); 6547 bool VisitUnaryImag(const UnaryOperator *E); 6548 bool VisitUnaryPreInc(const UnaryOperator *UO) { 6549 return VisitUnaryPreIncDec(UO); 6550 } 6551 bool VisitUnaryPreDec(const UnaryOperator *UO) { 6552 return VisitUnaryPreIncDec(UO); 6553 } 6554 bool VisitBinAssign(const BinaryOperator *BO); 6555 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 6556 6557 bool VisitCastExpr(const CastExpr *E) { 6558 switch (E->getCastKind()) { 6559 default: 6560 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 6561 6562 case CK_LValueBitCast: 6563 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 6564 if (!Visit(E->getSubExpr())) 6565 return false; 6566 Result.Designator.setInvalid(); 6567 return true; 6568 6569 case CK_BaseToDerived: 6570 if (!Visit(E->getSubExpr())) 6571 return false; 6572 return HandleBaseToDerivedCast(Info, E, Result); 6573 6574 case CK_Dynamic: 6575 if (!Visit(E->getSubExpr())) 6576 return false; 6577 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 6578 } 6579 } 6580 }; 6581 } // end anonymous namespace 6582 6583 /// Evaluate an expression as an lvalue. This can be legitimately called on 6584 /// expressions which are not glvalues, in three cases: 6585 /// * function designators in C, and 6586 /// * "extern void" objects 6587 /// * @selector() expressions in Objective-C 6588 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 6589 bool InvalidBaseOK) { 6590 assert(E->isGLValue() || E->getType()->isFunctionType() || 6591 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 6592 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 6593 } 6594 6595 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 6596 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 6597 return Success(FD); 6598 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 6599 return VisitVarDecl(E, VD); 6600 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 6601 return Visit(BD->getBinding()); 6602 return Error(E); 6603 } 6604 6605 6606 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 6607 6608 // If we are within a lambda's call operator, check whether the 'VD' referred 6609 // to within 'E' actually represents a lambda-capture that maps to a 6610 // data-member/field within the closure object, and if so, evaluate to the 6611 // field or what the field refers to. 6612 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 6613 isa<DeclRefExpr>(E) && 6614 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 6615 // We don't always have a complete capture-map when checking or inferring if 6616 // the function call operator meets the requirements of a constexpr function 6617 // - but we don't need to evaluate the captures to determine constexprness 6618 // (dcl.constexpr C++17). 6619 if (Info.checkingPotentialConstantExpression()) 6620 return false; 6621 6622 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 6623 // Start with 'Result' referring to the complete closure object... 6624 Result = *Info.CurrentCall->This; 6625 // ... then update it to refer to the field of the closure object 6626 // that represents the capture. 6627 if (!HandleLValueMember(Info, E, Result, FD)) 6628 return false; 6629 // And if the field is of reference type, update 'Result' to refer to what 6630 // the field refers to. 6631 if (FD->getType()->isReferenceType()) { 6632 APValue RVal; 6633 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 6634 RVal)) 6635 return false; 6636 Result.setFrom(Info.Ctx, RVal); 6637 } 6638 return true; 6639 } 6640 } 6641 CallStackFrame *Frame = nullptr; 6642 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 6643 // Only if a local variable was declared in the function currently being 6644 // evaluated, do we expect to be able to find its value in the current 6645 // frame. (Otherwise it was likely declared in an enclosing context and 6646 // could either have a valid evaluatable value (for e.g. a constexpr 6647 // variable) or be ill-formed (and trigger an appropriate evaluation 6648 // diagnostic)). 6649 if (Info.CurrentCall->Callee && 6650 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 6651 Frame = Info.CurrentCall; 6652 } 6653 } 6654 6655 if (!VD->getType()->isReferenceType()) { 6656 if (Frame) { 6657 Result.set({VD, Frame->Index, 6658 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 6659 return true; 6660 } 6661 return Success(VD); 6662 } 6663 6664 APValue *V; 6665 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 6666 return false; 6667 if (!V->hasValue()) { 6668 // FIXME: Is it possible for V to be indeterminate here? If so, we should 6669 // adjust the diagnostic to say that. 6670 if (!Info.checkingPotentialConstantExpression()) 6671 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 6672 return false; 6673 } 6674 return Success(*V, E); 6675 } 6676 6677 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 6678 const MaterializeTemporaryExpr *E) { 6679 // Walk through the expression to find the materialized temporary itself. 6680 SmallVector<const Expr *, 2> CommaLHSs; 6681 SmallVector<SubobjectAdjustment, 2> Adjustments; 6682 const Expr *Inner = E->GetTemporaryExpr()-> 6683 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 6684 6685 // If we passed any comma operators, evaluate their LHSs. 6686 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 6687 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 6688 return false; 6689 6690 // A materialized temporary with static storage duration can appear within the 6691 // result of a constant expression evaluation, so we need to preserve its 6692 // value for use outside this evaluation. 6693 APValue *Value; 6694 if (E->getStorageDuration() == SD_Static) { 6695 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 6696 *Value = APValue(); 6697 Result.set(E); 6698 } else { 6699 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result, 6700 *Info.CurrentCall); 6701 } 6702 6703 QualType Type = Inner->getType(); 6704 6705 // Materialize the temporary itself. 6706 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 6707 (E->getStorageDuration() == SD_Static && 6708 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 6709 *Value = APValue(); 6710 return false; 6711 } 6712 6713 // Adjust our lvalue to refer to the desired subobject. 6714 for (unsigned I = Adjustments.size(); I != 0; /**/) { 6715 --I; 6716 switch (Adjustments[I].Kind) { 6717 case SubobjectAdjustment::DerivedToBaseAdjustment: 6718 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 6719 Type, Result)) 6720 return false; 6721 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 6722 break; 6723 6724 case SubobjectAdjustment::FieldAdjustment: 6725 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 6726 return false; 6727 Type = Adjustments[I].Field->getType(); 6728 break; 6729 6730 case SubobjectAdjustment::MemberPointerAdjustment: 6731 if (!HandleMemberPointerAccess(this->Info, Type, Result, 6732 Adjustments[I].Ptr.RHS)) 6733 return false; 6734 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 6735 break; 6736 } 6737 } 6738 6739 return true; 6740 } 6741 6742 bool 6743 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 6744 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 6745 "lvalue compound literal in c++?"); 6746 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 6747 // only see this when folding in C, so there's no standard to follow here. 6748 return Success(E); 6749 } 6750 6751 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 6752 TypeInfoLValue TypeInfo; 6753 6754 if (!E->isPotentiallyEvaluated()) { 6755 if (E->isTypeOperand()) 6756 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 6757 else 6758 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 6759 } else { 6760 if (!Info.Ctx.getLangOpts().CPlusPlus2a) { 6761 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 6762 << E->getExprOperand()->getType() 6763 << E->getExprOperand()->getSourceRange(); 6764 } 6765 6766 if (!Visit(E->getExprOperand())) 6767 return false; 6768 6769 Optional<DynamicType> DynType = 6770 ComputeDynamicType(Info, E, Result, AK_TypeId); 6771 if (!DynType) 6772 return false; 6773 6774 TypeInfo = 6775 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 6776 } 6777 6778 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 6779 } 6780 6781 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 6782 return Success(E); 6783 } 6784 6785 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 6786 // Handle static data members. 6787 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 6788 VisitIgnoredBaseExpression(E->getBase()); 6789 return VisitVarDecl(E, VD); 6790 } 6791 6792 // Handle static member functions. 6793 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 6794 if (MD->isStatic()) { 6795 VisitIgnoredBaseExpression(E->getBase()); 6796 return Success(MD); 6797 } 6798 } 6799 6800 // Handle non-static data members. 6801 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 6802 } 6803 6804 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 6805 // FIXME: Deal with vectors as array subscript bases. 6806 if (E->getBase()->getType()->isVectorType()) 6807 return Error(E); 6808 6809 bool Success = true; 6810 if (!evaluatePointer(E->getBase(), Result)) { 6811 if (!Info.noteFailure()) 6812 return false; 6813 Success = false; 6814 } 6815 6816 APSInt Index; 6817 if (!EvaluateInteger(E->getIdx(), Index, Info)) 6818 return false; 6819 6820 return Success && 6821 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 6822 } 6823 6824 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 6825 return evaluatePointer(E->getSubExpr(), Result); 6826 } 6827 6828 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 6829 if (!Visit(E->getSubExpr())) 6830 return false; 6831 // __real is a no-op on scalar lvalues. 6832 if (E->getSubExpr()->getType()->isAnyComplexType()) 6833 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 6834 return true; 6835 } 6836 6837 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 6838 assert(E->getSubExpr()->getType()->isAnyComplexType() && 6839 "lvalue __imag__ on scalar?"); 6840 if (!Visit(E->getSubExpr())) 6841 return false; 6842 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 6843 return true; 6844 } 6845 6846 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 6847 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6848 return Error(UO); 6849 6850 if (!this->Visit(UO->getSubExpr())) 6851 return false; 6852 6853 return handleIncDec( 6854 this->Info, UO, Result, UO->getSubExpr()->getType(), 6855 UO->isIncrementOp(), nullptr); 6856 } 6857 6858 bool LValueExprEvaluator::VisitCompoundAssignOperator( 6859 const CompoundAssignOperator *CAO) { 6860 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6861 return Error(CAO); 6862 6863 APValue RHS; 6864 6865 // The overall lvalue result is the result of evaluating the LHS. 6866 if (!this->Visit(CAO->getLHS())) { 6867 if (Info.noteFailure()) 6868 Evaluate(RHS, this->Info, CAO->getRHS()); 6869 return false; 6870 } 6871 6872 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 6873 return false; 6874 6875 return handleCompoundAssignment( 6876 this->Info, CAO, 6877 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 6878 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 6879 } 6880 6881 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 6882 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6883 return Error(E); 6884 6885 APValue NewVal; 6886 6887 if (!this->Visit(E->getLHS())) { 6888 if (Info.noteFailure()) 6889 Evaluate(NewVal, this->Info, E->getRHS()); 6890 return false; 6891 } 6892 6893 if (!Evaluate(NewVal, this->Info, E->getRHS())) 6894 return false; 6895 6896 if (Info.getLangOpts().CPlusPlus2a && 6897 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 6898 return false; 6899 6900 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 6901 NewVal); 6902 } 6903 6904 //===----------------------------------------------------------------------===// 6905 // Pointer Evaluation 6906 //===----------------------------------------------------------------------===// 6907 6908 /// Attempts to compute the number of bytes available at the pointer 6909 /// returned by a function with the alloc_size attribute. Returns true if we 6910 /// were successful. Places an unsigned number into `Result`. 6911 /// 6912 /// This expects the given CallExpr to be a call to a function with an 6913 /// alloc_size attribute. 6914 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 6915 const CallExpr *Call, 6916 llvm::APInt &Result) { 6917 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 6918 6919 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 6920 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 6921 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 6922 if (Call->getNumArgs() <= SizeArgNo) 6923 return false; 6924 6925 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 6926 Expr::EvalResult ExprResult; 6927 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 6928 return false; 6929 Into = ExprResult.Val.getInt(); 6930 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 6931 return false; 6932 Into = Into.zextOrSelf(BitsInSizeT); 6933 return true; 6934 }; 6935 6936 APSInt SizeOfElem; 6937 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 6938 return false; 6939 6940 if (!AllocSize->getNumElemsParam().isValid()) { 6941 Result = std::move(SizeOfElem); 6942 return true; 6943 } 6944 6945 APSInt NumberOfElems; 6946 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 6947 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 6948 return false; 6949 6950 bool Overflow; 6951 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 6952 if (Overflow) 6953 return false; 6954 6955 Result = std::move(BytesAvailable); 6956 return true; 6957 } 6958 6959 /// Convenience function. LVal's base must be a call to an alloc_size 6960 /// function. 6961 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 6962 const LValue &LVal, 6963 llvm::APInt &Result) { 6964 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 6965 "Can't get the size of a non alloc_size function"); 6966 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 6967 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 6968 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 6969 } 6970 6971 /// Attempts to evaluate the given LValueBase as the result of a call to 6972 /// a function with the alloc_size attribute. If it was possible to do so, this 6973 /// function will return true, make Result's Base point to said function call, 6974 /// and mark Result's Base as invalid. 6975 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 6976 LValue &Result) { 6977 if (Base.isNull()) 6978 return false; 6979 6980 // Because we do no form of static analysis, we only support const variables. 6981 // 6982 // Additionally, we can't support parameters, nor can we support static 6983 // variables (in the latter case, use-before-assign isn't UB; in the former, 6984 // we have no clue what they'll be assigned to). 6985 const auto *VD = 6986 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 6987 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 6988 return false; 6989 6990 const Expr *Init = VD->getAnyInitializer(); 6991 if (!Init) 6992 return false; 6993 6994 const Expr *E = Init->IgnoreParens(); 6995 if (!tryUnwrapAllocSizeCall(E)) 6996 return false; 6997 6998 // Store E instead of E unwrapped so that the type of the LValue's base is 6999 // what the user wanted. 7000 Result.setInvalid(E); 7001 7002 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 7003 Result.addUnsizedArray(Info, E, Pointee); 7004 return true; 7005 } 7006 7007 namespace { 7008 class PointerExprEvaluator 7009 : public ExprEvaluatorBase<PointerExprEvaluator> { 7010 LValue &Result; 7011 bool InvalidBaseOK; 7012 7013 bool Success(const Expr *E) { 7014 Result.set(E); 7015 return true; 7016 } 7017 7018 bool evaluateLValue(const Expr *E, LValue &Result) { 7019 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 7020 } 7021 7022 bool evaluatePointer(const Expr *E, LValue &Result) { 7023 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 7024 } 7025 7026 bool visitNonBuiltinCallExpr(const CallExpr *E); 7027 public: 7028 7029 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 7030 : ExprEvaluatorBaseTy(info), Result(Result), 7031 InvalidBaseOK(InvalidBaseOK) {} 7032 7033 bool Success(const APValue &V, const Expr *E) { 7034 Result.setFrom(Info.Ctx, V); 7035 return true; 7036 } 7037 bool ZeroInitialization(const Expr *E) { 7038 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 7039 Result.setNull(E->getType(), TargetVal); 7040 return true; 7041 } 7042 7043 bool VisitBinaryOperator(const BinaryOperator *E); 7044 bool VisitCastExpr(const CastExpr* E); 7045 bool VisitUnaryAddrOf(const UnaryOperator *E); 7046 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 7047 { return Success(E); } 7048 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 7049 if (E->isExpressibleAsConstantInitializer()) 7050 return Success(E); 7051 if (Info.noteFailure()) 7052 EvaluateIgnoredValue(Info, E->getSubExpr()); 7053 return Error(E); 7054 } 7055 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 7056 { return Success(E); } 7057 bool VisitCallExpr(const CallExpr *E); 7058 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 7059 bool VisitBlockExpr(const BlockExpr *E) { 7060 if (!E->getBlockDecl()->hasCaptures()) 7061 return Success(E); 7062 return Error(E); 7063 } 7064 bool VisitCXXThisExpr(const CXXThisExpr *E) { 7065 // Can't look at 'this' when checking a potential constant expression. 7066 if (Info.checkingPotentialConstantExpression()) 7067 return false; 7068 if (!Info.CurrentCall->This) { 7069 if (Info.getLangOpts().CPlusPlus11) 7070 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 7071 else 7072 Info.FFDiag(E); 7073 return false; 7074 } 7075 Result = *Info.CurrentCall->This; 7076 // If we are inside a lambda's call operator, the 'this' expression refers 7077 // to the enclosing '*this' object (either by value or reference) which is 7078 // either copied into the closure object's field that represents the '*this' 7079 // or refers to '*this'. 7080 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 7081 // Update 'Result' to refer to the data member/field of the closure object 7082 // that represents the '*this' capture. 7083 if (!HandleLValueMember(Info, E, Result, 7084 Info.CurrentCall->LambdaThisCaptureField)) 7085 return false; 7086 // If we captured '*this' by reference, replace the field with its referent. 7087 if (Info.CurrentCall->LambdaThisCaptureField->getType() 7088 ->isPointerType()) { 7089 APValue RVal; 7090 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 7091 RVal)) 7092 return false; 7093 7094 Result.setFrom(Info.Ctx, RVal); 7095 } 7096 } 7097 return true; 7098 } 7099 7100 bool VisitSourceLocExpr(const SourceLocExpr *E) { 7101 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 7102 APValue LValResult = E->EvaluateInContext( 7103 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 7104 Result.setFrom(Info.Ctx, LValResult); 7105 return true; 7106 } 7107 7108 // FIXME: Missing: @protocol, @selector 7109 }; 7110 } // end anonymous namespace 7111 7112 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 7113 bool InvalidBaseOK) { 7114 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 7115 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7116 } 7117 7118 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 7119 if (E->getOpcode() != BO_Add && 7120 E->getOpcode() != BO_Sub) 7121 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7122 7123 const Expr *PExp = E->getLHS(); 7124 const Expr *IExp = E->getRHS(); 7125 if (IExp->getType()->isPointerType()) 7126 std::swap(PExp, IExp); 7127 7128 bool EvalPtrOK = evaluatePointer(PExp, Result); 7129 if (!EvalPtrOK && !Info.noteFailure()) 7130 return false; 7131 7132 llvm::APSInt Offset; 7133 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 7134 return false; 7135 7136 if (E->getOpcode() == BO_Sub) 7137 negateAsSigned(Offset); 7138 7139 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 7140 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 7141 } 7142 7143 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 7144 return evaluateLValue(E->getSubExpr(), Result); 7145 } 7146 7147 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 7148 const Expr *SubExpr = E->getSubExpr(); 7149 7150 switch (E->getCastKind()) { 7151 default: 7152 break; 7153 case CK_BitCast: 7154 case CK_CPointerToObjCPointerCast: 7155 case CK_BlockPointerToObjCPointerCast: 7156 case CK_AnyPointerToBlockPointerCast: 7157 case CK_AddressSpaceConversion: 7158 if (!Visit(SubExpr)) 7159 return false; 7160 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 7161 // permitted in constant expressions in C++11. Bitcasts from cv void* are 7162 // also static_casts, but we disallow them as a resolution to DR1312. 7163 if (!E->getType()->isVoidPointerType()) { 7164 Result.Designator.setInvalid(); 7165 if (SubExpr->getType()->isVoidPointerType()) 7166 CCEDiag(E, diag::note_constexpr_invalid_cast) 7167 << 3 << SubExpr->getType(); 7168 else 7169 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7170 } 7171 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 7172 ZeroInitialization(E); 7173 return true; 7174 7175 case CK_DerivedToBase: 7176 case CK_UncheckedDerivedToBase: 7177 if (!evaluatePointer(E->getSubExpr(), Result)) 7178 return false; 7179 if (!Result.Base && Result.Offset.isZero()) 7180 return true; 7181 7182 // Now figure out the necessary offset to add to the base LV to get from 7183 // the derived class to the base class. 7184 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 7185 castAs<PointerType>()->getPointeeType(), 7186 Result); 7187 7188 case CK_BaseToDerived: 7189 if (!Visit(E->getSubExpr())) 7190 return false; 7191 if (!Result.Base && Result.Offset.isZero()) 7192 return true; 7193 return HandleBaseToDerivedCast(Info, E, Result); 7194 7195 case CK_Dynamic: 7196 if (!Visit(E->getSubExpr())) 7197 return false; 7198 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7199 7200 case CK_NullToPointer: 7201 VisitIgnoredValue(E->getSubExpr()); 7202 return ZeroInitialization(E); 7203 7204 case CK_IntegralToPointer: { 7205 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7206 7207 APValue Value; 7208 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 7209 break; 7210 7211 if (Value.isInt()) { 7212 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 7213 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 7214 Result.Base = (Expr*)nullptr; 7215 Result.InvalidBase = false; 7216 Result.Offset = CharUnits::fromQuantity(N); 7217 Result.Designator.setInvalid(); 7218 Result.IsNullPtr = false; 7219 return true; 7220 } else { 7221 // Cast is of an lvalue, no need to change value. 7222 Result.setFrom(Info.Ctx, Value); 7223 return true; 7224 } 7225 } 7226 7227 case CK_ArrayToPointerDecay: { 7228 if (SubExpr->isGLValue()) { 7229 if (!evaluateLValue(SubExpr, Result)) 7230 return false; 7231 } else { 7232 APValue &Value = createTemporary(SubExpr, false, Result, 7233 *Info.CurrentCall); 7234 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 7235 return false; 7236 } 7237 // The result is a pointer to the first element of the array. 7238 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 7239 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 7240 Result.addArray(Info, E, CAT); 7241 else 7242 Result.addUnsizedArray(Info, E, AT->getElementType()); 7243 return true; 7244 } 7245 7246 case CK_FunctionToPointerDecay: 7247 return evaluateLValue(SubExpr, Result); 7248 7249 case CK_LValueToRValue: { 7250 LValue LVal; 7251 if (!evaluateLValue(E->getSubExpr(), LVal)) 7252 return false; 7253 7254 APValue RVal; 7255 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7256 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7257 LVal, RVal)) 7258 return InvalidBaseOK && 7259 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 7260 return Success(RVal, E); 7261 } 7262 } 7263 7264 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7265 } 7266 7267 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 7268 UnaryExprOrTypeTrait ExprKind) { 7269 // C++ [expr.alignof]p3: 7270 // When alignof is applied to a reference type, the result is the 7271 // alignment of the referenced type. 7272 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 7273 T = Ref->getPointeeType(); 7274 7275 if (T.getQualifiers().hasUnaligned()) 7276 return CharUnits::One(); 7277 7278 const bool AlignOfReturnsPreferred = 7279 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 7280 7281 // __alignof is defined to return the preferred alignment. 7282 // Before 8, clang returned the preferred alignment for alignof and _Alignof 7283 // as well. 7284 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 7285 return Info.Ctx.toCharUnitsFromBits( 7286 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 7287 // alignof and _Alignof are defined to return the ABI alignment. 7288 else if (ExprKind == UETT_AlignOf) 7289 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 7290 else 7291 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 7292 } 7293 7294 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 7295 UnaryExprOrTypeTrait ExprKind) { 7296 E = E->IgnoreParens(); 7297 7298 // The kinds of expressions that we have special-case logic here for 7299 // should be kept up to date with the special checks for those 7300 // expressions in Sema. 7301 7302 // alignof decl is always accepted, even if it doesn't make sense: we default 7303 // to 1 in those cases. 7304 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 7305 return Info.Ctx.getDeclAlign(DRE->getDecl(), 7306 /*RefAsPointee*/true); 7307 7308 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 7309 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 7310 /*RefAsPointee*/true); 7311 7312 return GetAlignOfType(Info, E->getType(), ExprKind); 7313 } 7314 7315 // To be clear: this happily visits unsupported builtins. Better name welcomed. 7316 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 7317 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 7318 return true; 7319 7320 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 7321 return false; 7322 7323 Result.setInvalid(E); 7324 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 7325 Result.addUnsizedArray(Info, E, PointeeTy); 7326 return true; 7327 } 7328 7329 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 7330 if (IsStringLiteralCall(E)) 7331 return Success(E); 7332 7333 if (unsigned BuiltinOp = E->getBuiltinCallee()) 7334 return VisitBuiltinCallExpr(E, BuiltinOp); 7335 7336 return visitNonBuiltinCallExpr(E); 7337 } 7338 7339 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 7340 unsigned BuiltinOp) { 7341 switch (BuiltinOp) { 7342 case Builtin::BI__builtin_addressof: 7343 return evaluateLValue(E->getArg(0), Result); 7344 case Builtin::BI__builtin_assume_aligned: { 7345 // We need to be very careful here because: if the pointer does not have the 7346 // asserted alignment, then the behavior is undefined, and undefined 7347 // behavior is non-constant. 7348 if (!evaluatePointer(E->getArg(0), Result)) 7349 return false; 7350 7351 LValue OffsetResult(Result); 7352 APSInt Alignment; 7353 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 7354 return false; 7355 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 7356 7357 if (E->getNumArgs() > 2) { 7358 APSInt Offset; 7359 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 7360 return false; 7361 7362 int64_t AdditionalOffset = -Offset.getZExtValue(); 7363 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 7364 } 7365 7366 // If there is a base object, then it must have the correct alignment. 7367 if (OffsetResult.Base) { 7368 CharUnits BaseAlignment; 7369 if (const ValueDecl *VD = 7370 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 7371 BaseAlignment = Info.Ctx.getDeclAlign(VD); 7372 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) { 7373 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf); 7374 } else { 7375 BaseAlignment = GetAlignOfType( 7376 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf); 7377 } 7378 7379 if (BaseAlignment < Align) { 7380 Result.Designator.setInvalid(); 7381 // FIXME: Add support to Diagnostic for long / long long. 7382 CCEDiag(E->getArg(0), 7383 diag::note_constexpr_baa_insufficient_alignment) << 0 7384 << (unsigned)BaseAlignment.getQuantity() 7385 << (unsigned)Align.getQuantity(); 7386 return false; 7387 } 7388 } 7389 7390 // The offset must also have the correct alignment. 7391 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 7392 Result.Designator.setInvalid(); 7393 7394 (OffsetResult.Base 7395 ? CCEDiag(E->getArg(0), 7396 diag::note_constexpr_baa_insufficient_alignment) << 1 7397 : CCEDiag(E->getArg(0), 7398 diag::note_constexpr_baa_value_insufficient_alignment)) 7399 << (int)OffsetResult.Offset.getQuantity() 7400 << (unsigned)Align.getQuantity(); 7401 return false; 7402 } 7403 7404 return true; 7405 } 7406 case Builtin::BI__builtin_launder: 7407 return evaluatePointer(E->getArg(0), Result); 7408 case Builtin::BIstrchr: 7409 case Builtin::BIwcschr: 7410 case Builtin::BImemchr: 7411 case Builtin::BIwmemchr: 7412 if (Info.getLangOpts().CPlusPlus11) 7413 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7414 << /*isConstexpr*/0 << /*isConstructor*/0 7415 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7416 else 7417 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7418 LLVM_FALLTHROUGH; 7419 case Builtin::BI__builtin_strchr: 7420 case Builtin::BI__builtin_wcschr: 7421 case Builtin::BI__builtin_memchr: 7422 case Builtin::BI__builtin_char_memchr: 7423 case Builtin::BI__builtin_wmemchr: { 7424 if (!Visit(E->getArg(0))) 7425 return false; 7426 APSInt Desired; 7427 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 7428 return false; 7429 uint64_t MaxLength = uint64_t(-1); 7430 if (BuiltinOp != Builtin::BIstrchr && 7431 BuiltinOp != Builtin::BIwcschr && 7432 BuiltinOp != Builtin::BI__builtin_strchr && 7433 BuiltinOp != Builtin::BI__builtin_wcschr) { 7434 APSInt N; 7435 if (!EvaluateInteger(E->getArg(2), N, Info)) 7436 return false; 7437 MaxLength = N.getExtValue(); 7438 } 7439 // We cannot find the value if there are no candidates to match against. 7440 if (MaxLength == 0u) 7441 return ZeroInitialization(E); 7442 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 7443 Result.Designator.Invalid) 7444 return false; 7445 QualType CharTy = Result.Designator.getType(Info.Ctx); 7446 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 7447 BuiltinOp == Builtin::BI__builtin_memchr; 7448 assert(IsRawByte || 7449 Info.Ctx.hasSameUnqualifiedType( 7450 CharTy, E->getArg(0)->getType()->getPointeeType())); 7451 // Pointers to const void may point to objects of incomplete type. 7452 if (IsRawByte && CharTy->isIncompleteType()) { 7453 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 7454 return false; 7455 } 7456 // Give up on byte-oriented matching against multibyte elements. 7457 // FIXME: We can compare the bytes in the correct order. 7458 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One()) 7459 return false; 7460 // Figure out what value we're actually looking for (after converting to 7461 // the corresponding unsigned type if necessary). 7462 uint64_t DesiredVal; 7463 bool StopAtNull = false; 7464 switch (BuiltinOp) { 7465 case Builtin::BIstrchr: 7466 case Builtin::BI__builtin_strchr: 7467 // strchr compares directly to the passed integer, and therefore 7468 // always fails if given an int that is not a char. 7469 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 7470 E->getArg(1)->getType(), 7471 Desired), 7472 Desired)) 7473 return ZeroInitialization(E); 7474 StopAtNull = true; 7475 LLVM_FALLTHROUGH; 7476 case Builtin::BImemchr: 7477 case Builtin::BI__builtin_memchr: 7478 case Builtin::BI__builtin_char_memchr: 7479 // memchr compares by converting both sides to unsigned char. That's also 7480 // correct for strchr if we get this far (to cope with plain char being 7481 // unsigned in the strchr case). 7482 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 7483 break; 7484 7485 case Builtin::BIwcschr: 7486 case Builtin::BI__builtin_wcschr: 7487 StopAtNull = true; 7488 LLVM_FALLTHROUGH; 7489 case Builtin::BIwmemchr: 7490 case Builtin::BI__builtin_wmemchr: 7491 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 7492 DesiredVal = Desired.getZExtValue(); 7493 break; 7494 } 7495 7496 for (; MaxLength; --MaxLength) { 7497 APValue Char; 7498 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 7499 !Char.isInt()) 7500 return false; 7501 if (Char.getInt().getZExtValue() == DesiredVal) 7502 return true; 7503 if (StopAtNull && !Char.getInt()) 7504 break; 7505 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 7506 return false; 7507 } 7508 // Not found: return nullptr. 7509 return ZeroInitialization(E); 7510 } 7511 7512 case Builtin::BImemcpy: 7513 case Builtin::BImemmove: 7514 case Builtin::BIwmemcpy: 7515 case Builtin::BIwmemmove: 7516 if (Info.getLangOpts().CPlusPlus11) 7517 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7518 << /*isConstexpr*/0 << /*isConstructor*/0 7519 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7520 else 7521 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7522 LLVM_FALLTHROUGH; 7523 case Builtin::BI__builtin_memcpy: 7524 case Builtin::BI__builtin_memmove: 7525 case Builtin::BI__builtin_wmemcpy: 7526 case Builtin::BI__builtin_wmemmove: { 7527 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 7528 BuiltinOp == Builtin::BIwmemmove || 7529 BuiltinOp == Builtin::BI__builtin_wmemcpy || 7530 BuiltinOp == Builtin::BI__builtin_wmemmove; 7531 bool Move = BuiltinOp == Builtin::BImemmove || 7532 BuiltinOp == Builtin::BIwmemmove || 7533 BuiltinOp == Builtin::BI__builtin_memmove || 7534 BuiltinOp == Builtin::BI__builtin_wmemmove; 7535 7536 // The result of mem* is the first argument. 7537 if (!Visit(E->getArg(0))) 7538 return false; 7539 LValue Dest = Result; 7540 7541 LValue Src; 7542 if (!EvaluatePointer(E->getArg(1), Src, Info)) 7543 return false; 7544 7545 APSInt N; 7546 if (!EvaluateInteger(E->getArg(2), N, Info)) 7547 return false; 7548 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 7549 7550 // If the size is zero, we treat this as always being a valid no-op. 7551 // (Even if one of the src and dest pointers is null.) 7552 if (!N) 7553 return true; 7554 7555 // Otherwise, if either of the operands is null, we can't proceed. Don't 7556 // try to determine the type of the copied objects, because there aren't 7557 // any. 7558 if (!Src.Base || !Dest.Base) { 7559 APValue Val; 7560 (!Src.Base ? Src : Dest).moveInto(Val); 7561 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 7562 << Move << WChar << !!Src.Base 7563 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 7564 return false; 7565 } 7566 if (Src.Designator.Invalid || Dest.Designator.Invalid) 7567 return false; 7568 7569 // We require that Src and Dest are both pointers to arrays of 7570 // trivially-copyable type. (For the wide version, the designator will be 7571 // invalid if the designated object is not a wchar_t.) 7572 QualType T = Dest.Designator.getType(Info.Ctx); 7573 QualType SrcT = Src.Designator.getType(Info.Ctx); 7574 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 7575 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 7576 return false; 7577 } 7578 if (T->isIncompleteType()) { 7579 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 7580 return false; 7581 } 7582 if (!T.isTriviallyCopyableType(Info.Ctx)) { 7583 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 7584 return false; 7585 } 7586 7587 // Figure out how many T's we're copying. 7588 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 7589 if (!WChar) { 7590 uint64_t Remainder; 7591 llvm::APInt OrigN = N; 7592 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 7593 if (Remainder) { 7594 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 7595 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 7596 << (unsigned)TSize; 7597 return false; 7598 } 7599 } 7600 7601 // Check that the copying will remain within the arrays, just so that we 7602 // can give a more meaningful diagnostic. This implicitly also checks that 7603 // N fits into 64 bits. 7604 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 7605 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 7606 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 7607 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 7608 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 7609 << N.toString(10, /*Signed*/false); 7610 return false; 7611 } 7612 uint64_t NElems = N.getZExtValue(); 7613 uint64_t NBytes = NElems * TSize; 7614 7615 // Check for overlap. 7616 int Direction = 1; 7617 if (HasSameBase(Src, Dest)) { 7618 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 7619 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 7620 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 7621 // Dest is inside the source region. 7622 if (!Move) { 7623 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 7624 return false; 7625 } 7626 // For memmove and friends, copy backwards. 7627 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 7628 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 7629 return false; 7630 Direction = -1; 7631 } else if (!Move && SrcOffset >= DestOffset && 7632 SrcOffset - DestOffset < NBytes) { 7633 // Src is inside the destination region for memcpy: invalid. 7634 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 7635 return false; 7636 } 7637 } 7638 7639 while (true) { 7640 APValue Val; 7641 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 7642 !handleAssignment(Info, E, Dest, T, Val)) 7643 return false; 7644 // Do not iterate past the last element; if we're copying backwards, that 7645 // might take us off the start of the array. 7646 if (--NElems == 0) 7647 return true; 7648 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 7649 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 7650 return false; 7651 } 7652 } 7653 7654 default: 7655 return visitNonBuiltinCallExpr(E); 7656 } 7657 } 7658 7659 //===----------------------------------------------------------------------===// 7660 // Member Pointer Evaluation 7661 //===----------------------------------------------------------------------===// 7662 7663 namespace { 7664 class MemberPointerExprEvaluator 7665 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 7666 MemberPtr &Result; 7667 7668 bool Success(const ValueDecl *D) { 7669 Result = MemberPtr(D); 7670 return true; 7671 } 7672 public: 7673 7674 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 7675 : ExprEvaluatorBaseTy(Info), Result(Result) {} 7676 7677 bool Success(const APValue &V, const Expr *E) { 7678 Result.setFrom(V); 7679 return true; 7680 } 7681 bool ZeroInitialization(const Expr *E) { 7682 return Success((const ValueDecl*)nullptr); 7683 } 7684 7685 bool VisitCastExpr(const CastExpr *E); 7686 bool VisitUnaryAddrOf(const UnaryOperator *E); 7687 }; 7688 } // end anonymous namespace 7689 7690 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 7691 EvalInfo &Info) { 7692 assert(E->isRValue() && E->getType()->isMemberPointerType()); 7693 return MemberPointerExprEvaluator(Info, Result).Visit(E); 7694 } 7695 7696 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 7697 switch (E->getCastKind()) { 7698 default: 7699 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7700 7701 case CK_NullToMemberPointer: 7702 VisitIgnoredValue(E->getSubExpr()); 7703 return ZeroInitialization(E); 7704 7705 case CK_BaseToDerivedMemberPointer: { 7706 if (!Visit(E->getSubExpr())) 7707 return false; 7708 if (E->path_empty()) 7709 return true; 7710 // Base-to-derived member pointer casts store the path in derived-to-base 7711 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 7712 // the wrong end of the derived->base arc, so stagger the path by one class. 7713 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 7714 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 7715 PathI != PathE; ++PathI) { 7716 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 7717 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 7718 if (!Result.castToDerived(Derived)) 7719 return Error(E); 7720 } 7721 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 7722 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 7723 return Error(E); 7724 return true; 7725 } 7726 7727 case CK_DerivedToBaseMemberPointer: 7728 if (!Visit(E->getSubExpr())) 7729 return false; 7730 for (CastExpr::path_const_iterator PathI = E->path_begin(), 7731 PathE = E->path_end(); PathI != PathE; ++PathI) { 7732 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 7733 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 7734 if (!Result.castToBase(Base)) 7735 return Error(E); 7736 } 7737 return true; 7738 } 7739 } 7740 7741 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 7742 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 7743 // member can be formed. 7744 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 7745 } 7746 7747 //===----------------------------------------------------------------------===// 7748 // Record Evaluation 7749 //===----------------------------------------------------------------------===// 7750 7751 namespace { 7752 class RecordExprEvaluator 7753 : public ExprEvaluatorBase<RecordExprEvaluator> { 7754 const LValue &This; 7755 APValue &Result; 7756 public: 7757 7758 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 7759 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 7760 7761 bool Success(const APValue &V, const Expr *E) { 7762 Result = V; 7763 return true; 7764 } 7765 bool ZeroInitialization(const Expr *E) { 7766 return ZeroInitialization(E, E->getType()); 7767 } 7768 bool ZeroInitialization(const Expr *E, QualType T); 7769 7770 bool VisitCallExpr(const CallExpr *E) { 7771 return handleCallExpr(E, Result, &This); 7772 } 7773 bool VisitCastExpr(const CastExpr *E); 7774 bool VisitInitListExpr(const InitListExpr *E); 7775 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 7776 return VisitCXXConstructExpr(E, E->getType()); 7777 } 7778 bool VisitLambdaExpr(const LambdaExpr *E); 7779 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 7780 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 7781 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 7782 7783 bool VisitBinCmp(const BinaryOperator *E); 7784 }; 7785 } 7786 7787 /// Perform zero-initialization on an object of non-union class type. 7788 /// C++11 [dcl.init]p5: 7789 /// To zero-initialize an object or reference of type T means: 7790 /// [...] 7791 /// -- if T is a (possibly cv-qualified) non-union class type, 7792 /// each non-static data member and each base-class subobject is 7793 /// zero-initialized 7794 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 7795 const RecordDecl *RD, 7796 const LValue &This, APValue &Result) { 7797 assert(!RD->isUnion() && "Expected non-union class type"); 7798 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 7799 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 7800 std::distance(RD->field_begin(), RD->field_end())); 7801 7802 if (RD->isInvalidDecl()) return false; 7803 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7804 7805 if (CD) { 7806 unsigned Index = 0; 7807 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 7808 End = CD->bases_end(); I != End; ++I, ++Index) { 7809 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 7810 LValue Subobject = This; 7811 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 7812 return false; 7813 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 7814 Result.getStructBase(Index))) 7815 return false; 7816 } 7817 } 7818 7819 for (const auto *I : RD->fields()) { 7820 // -- if T is a reference type, no initialization is performed. 7821 if (I->getType()->isReferenceType()) 7822 continue; 7823 7824 LValue Subobject = This; 7825 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 7826 return false; 7827 7828 ImplicitValueInitExpr VIE(I->getType()); 7829 if (!EvaluateInPlace( 7830 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 7831 return false; 7832 } 7833 7834 return true; 7835 } 7836 7837 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 7838 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 7839 if (RD->isInvalidDecl()) return false; 7840 if (RD->isUnion()) { 7841 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 7842 // object's first non-static named data member is zero-initialized 7843 RecordDecl::field_iterator I = RD->field_begin(); 7844 if (I == RD->field_end()) { 7845 Result = APValue((const FieldDecl*)nullptr); 7846 return true; 7847 } 7848 7849 LValue Subobject = This; 7850 if (!HandleLValueMember(Info, E, Subobject, *I)) 7851 return false; 7852 Result = APValue(*I); 7853 ImplicitValueInitExpr VIE(I->getType()); 7854 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 7855 } 7856 7857 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 7858 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 7859 return false; 7860 } 7861 7862 return HandleClassZeroInitialization(Info, E, RD, This, Result); 7863 } 7864 7865 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 7866 switch (E->getCastKind()) { 7867 default: 7868 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7869 7870 case CK_ConstructorConversion: 7871 return Visit(E->getSubExpr()); 7872 7873 case CK_DerivedToBase: 7874 case CK_UncheckedDerivedToBase: { 7875 APValue DerivedObject; 7876 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 7877 return false; 7878 if (!DerivedObject.isStruct()) 7879 return Error(E->getSubExpr()); 7880 7881 // Derived-to-base rvalue conversion: just slice off the derived part. 7882 APValue *Value = &DerivedObject; 7883 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 7884 for (CastExpr::path_const_iterator PathI = E->path_begin(), 7885 PathE = E->path_end(); PathI != PathE; ++PathI) { 7886 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 7887 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 7888 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 7889 RD = Base; 7890 } 7891 Result = *Value; 7892 return true; 7893 } 7894 } 7895 } 7896 7897 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7898 if (E->isTransparent()) 7899 return Visit(E->getInit(0)); 7900 7901 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 7902 if (RD->isInvalidDecl()) return false; 7903 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7904 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 7905 7906 EvalInfo::EvaluatingConstructorRAII EvalObj( 7907 Info, 7908 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 7909 CXXRD && CXXRD->getNumBases()); 7910 7911 if (RD->isUnion()) { 7912 const FieldDecl *Field = E->getInitializedFieldInUnion(); 7913 Result = APValue(Field); 7914 if (!Field) 7915 return true; 7916 7917 // If the initializer list for a union does not contain any elements, the 7918 // first element of the union is value-initialized. 7919 // FIXME: The element should be initialized from an initializer list. 7920 // Is this difference ever observable for initializer lists which 7921 // we don't build? 7922 ImplicitValueInitExpr VIE(Field->getType()); 7923 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 7924 7925 LValue Subobject = This; 7926 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 7927 return false; 7928 7929 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 7930 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 7931 isa<CXXDefaultInitExpr>(InitExpr)); 7932 7933 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 7934 } 7935 7936 if (!Result.hasValue()) 7937 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 7938 std::distance(RD->field_begin(), RD->field_end())); 7939 unsigned ElementNo = 0; 7940 bool Success = true; 7941 7942 // Initialize base classes. 7943 if (CXXRD && CXXRD->getNumBases()) { 7944 for (const auto &Base : CXXRD->bases()) { 7945 assert(ElementNo < E->getNumInits() && "missing init for base class"); 7946 const Expr *Init = E->getInit(ElementNo); 7947 7948 LValue Subobject = This; 7949 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 7950 return false; 7951 7952 APValue &FieldVal = Result.getStructBase(ElementNo); 7953 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 7954 if (!Info.noteFailure()) 7955 return false; 7956 Success = false; 7957 } 7958 ++ElementNo; 7959 } 7960 7961 EvalObj.finishedConstructingBases(); 7962 } 7963 7964 // Initialize members. 7965 for (const auto *Field : RD->fields()) { 7966 // Anonymous bit-fields are not considered members of the class for 7967 // purposes of aggregate initialization. 7968 if (Field->isUnnamedBitfield()) 7969 continue; 7970 7971 LValue Subobject = This; 7972 7973 bool HaveInit = ElementNo < E->getNumInits(); 7974 7975 // FIXME: Diagnostics here should point to the end of the initializer 7976 // list, not the start. 7977 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 7978 Subobject, Field, &Layout)) 7979 return false; 7980 7981 // Perform an implicit value-initialization for members beyond the end of 7982 // the initializer list. 7983 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 7984 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 7985 7986 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 7987 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 7988 isa<CXXDefaultInitExpr>(Init)); 7989 7990 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 7991 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 7992 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 7993 FieldVal, Field))) { 7994 if (!Info.noteFailure()) 7995 return false; 7996 Success = false; 7997 } 7998 } 7999 8000 return Success; 8001 } 8002 8003 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 8004 QualType T) { 8005 // Note that E's type is not necessarily the type of our class here; we might 8006 // be initializing an array element instead. 8007 const CXXConstructorDecl *FD = E->getConstructor(); 8008 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 8009 8010 bool ZeroInit = E->requiresZeroInitialization(); 8011 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 8012 // If we've already performed zero-initialization, we're already done. 8013 if (Result.hasValue()) 8014 return true; 8015 8016 // We can get here in two different ways: 8017 // 1) We're performing value-initialization, and should zero-initialize 8018 // the object, or 8019 // 2) We're performing default-initialization of an object with a trivial 8020 // constexpr default constructor, in which case we should start the 8021 // lifetimes of all the base subobjects (there can be no data member 8022 // subobjects in this case) per [basic.life]p1. 8023 // Either way, ZeroInitialization is appropriate. 8024 return ZeroInitialization(E, T); 8025 } 8026 8027 const FunctionDecl *Definition = nullptr; 8028 auto Body = FD->getBody(Definition); 8029 8030 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 8031 return false; 8032 8033 // Avoid materializing a temporary for an elidable copy/move constructor. 8034 if (E->isElidable() && !ZeroInit) 8035 if (const MaterializeTemporaryExpr *ME 8036 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 8037 return Visit(ME->GetTemporaryExpr()); 8038 8039 if (ZeroInit && !ZeroInitialization(E, T)) 8040 return false; 8041 8042 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 8043 return HandleConstructorCall(E, This, Args, 8044 cast<CXXConstructorDecl>(Definition), Info, 8045 Result); 8046 } 8047 8048 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 8049 const CXXInheritedCtorInitExpr *E) { 8050 if (!Info.CurrentCall) { 8051 assert(Info.checkingPotentialConstantExpression()); 8052 return false; 8053 } 8054 8055 const CXXConstructorDecl *FD = E->getConstructor(); 8056 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 8057 return false; 8058 8059 const FunctionDecl *Definition = nullptr; 8060 auto Body = FD->getBody(Definition); 8061 8062 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 8063 return false; 8064 8065 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 8066 cast<CXXConstructorDecl>(Definition), Info, 8067 Result); 8068 } 8069 8070 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 8071 const CXXStdInitializerListExpr *E) { 8072 const ConstantArrayType *ArrayType = 8073 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 8074 8075 LValue Array; 8076 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 8077 return false; 8078 8079 // Get a pointer to the first element of the array. 8080 Array.addArray(Info, E, ArrayType); 8081 8082 // FIXME: Perform the checks on the field types in SemaInit. 8083 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 8084 RecordDecl::field_iterator Field = Record->field_begin(); 8085 if (Field == Record->field_end()) 8086 return Error(E); 8087 8088 // Start pointer. 8089 if (!Field->getType()->isPointerType() || 8090 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 8091 ArrayType->getElementType())) 8092 return Error(E); 8093 8094 // FIXME: What if the initializer_list type has base classes, etc? 8095 Result = APValue(APValue::UninitStruct(), 0, 2); 8096 Array.moveInto(Result.getStructField(0)); 8097 8098 if (++Field == Record->field_end()) 8099 return Error(E); 8100 8101 if (Field->getType()->isPointerType() && 8102 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 8103 ArrayType->getElementType())) { 8104 // End pointer. 8105 if (!HandleLValueArrayAdjustment(Info, E, Array, 8106 ArrayType->getElementType(), 8107 ArrayType->getSize().getZExtValue())) 8108 return false; 8109 Array.moveInto(Result.getStructField(1)); 8110 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 8111 // Length. 8112 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 8113 else 8114 return Error(E); 8115 8116 if (++Field != Record->field_end()) 8117 return Error(E); 8118 8119 return true; 8120 } 8121 8122 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 8123 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 8124 if (ClosureClass->isInvalidDecl()) return false; 8125 8126 if (Info.checkingPotentialConstantExpression()) return true; 8127 8128 const size_t NumFields = 8129 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 8130 8131 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 8132 E->capture_init_end()) && 8133 "The number of lambda capture initializers should equal the number of " 8134 "fields within the closure type"); 8135 8136 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 8137 // Iterate through all the lambda's closure object's fields and initialize 8138 // them. 8139 auto *CaptureInitIt = E->capture_init_begin(); 8140 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 8141 bool Success = true; 8142 for (const auto *Field : ClosureClass->fields()) { 8143 assert(CaptureInitIt != E->capture_init_end()); 8144 // Get the initializer for this field 8145 Expr *const CurFieldInit = *CaptureInitIt++; 8146 8147 // If there is no initializer, either this is a VLA or an error has 8148 // occurred. 8149 if (!CurFieldInit) 8150 return Error(E); 8151 8152 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 8153 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 8154 if (!Info.keepEvaluatingAfterFailure()) 8155 return false; 8156 Success = false; 8157 } 8158 ++CaptureIt; 8159 } 8160 return Success; 8161 } 8162 8163 static bool EvaluateRecord(const Expr *E, const LValue &This, 8164 APValue &Result, EvalInfo &Info) { 8165 assert(E->isRValue() && E->getType()->isRecordType() && 8166 "can't evaluate expression as a record rvalue"); 8167 return RecordExprEvaluator(Info, This, Result).Visit(E); 8168 } 8169 8170 //===----------------------------------------------------------------------===// 8171 // Temporary Evaluation 8172 // 8173 // Temporaries are represented in the AST as rvalues, but generally behave like 8174 // lvalues. The full-object of which the temporary is a subobject is implicitly 8175 // materialized so that a reference can bind to it. 8176 //===----------------------------------------------------------------------===// 8177 namespace { 8178 class TemporaryExprEvaluator 8179 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 8180 public: 8181 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 8182 LValueExprEvaluatorBaseTy(Info, Result, false) {} 8183 8184 /// Visit an expression which constructs the value of this temporary. 8185 bool VisitConstructExpr(const Expr *E) { 8186 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall); 8187 return EvaluateInPlace(Value, Info, Result, E); 8188 } 8189 8190 bool VisitCastExpr(const CastExpr *E) { 8191 switch (E->getCastKind()) { 8192 default: 8193 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8194 8195 case CK_ConstructorConversion: 8196 return VisitConstructExpr(E->getSubExpr()); 8197 } 8198 } 8199 bool VisitInitListExpr(const InitListExpr *E) { 8200 return VisitConstructExpr(E); 8201 } 8202 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 8203 return VisitConstructExpr(E); 8204 } 8205 bool VisitCallExpr(const CallExpr *E) { 8206 return VisitConstructExpr(E); 8207 } 8208 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 8209 return VisitConstructExpr(E); 8210 } 8211 bool VisitLambdaExpr(const LambdaExpr *E) { 8212 return VisitConstructExpr(E); 8213 } 8214 }; 8215 } // end anonymous namespace 8216 8217 /// Evaluate an expression of record type as a temporary. 8218 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 8219 assert(E->isRValue() && E->getType()->isRecordType()); 8220 return TemporaryExprEvaluator(Info, Result).Visit(E); 8221 } 8222 8223 //===----------------------------------------------------------------------===// 8224 // Vector Evaluation 8225 //===----------------------------------------------------------------------===// 8226 8227 namespace { 8228 class VectorExprEvaluator 8229 : public ExprEvaluatorBase<VectorExprEvaluator> { 8230 APValue &Result; 8231 public: 8232 8233 VectorExprEvaluator(EvalInfo &info, APValue &Result) 8234 : ExprEvaluatorBaseTy(info), Result(Result) {} 8235 8236 bool Success(ArrayRef<APValue> V, const Expr *E) { 8237 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 8238 // FIXME: remove this APValue copy. 8239 Result = APValue(V.data(), V.size()); 8240 return true; 8241 } 8242 bool Success(const APValue &V, const Expr *E) { 8243 assert(V.isVector()); 8244 Result = V; 8245 return true; 8246 } 8247 bool ZeroInitialization(const Expr *E); 8248 8249 bool VisitUnaryReal(const UnaryOperator *E) 8250 { return Visit(E->getSubExpr()); } 8251 bool VisitCastExpr(const CastExpr* E); 8252 bool VisitInitListExpr(const InitListExpr *E); 8253 bool VisitUnaryImag(const UnaryOperator *E); 8254 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 8255 // binary comparisons, binary and/or/xor, 8256 // shufflevector, ExtVectorElementExpr 8257 }; 8258 } // end anonymous namespace 8259 8260 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 8261 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 8262 return VectorExprEvaluator(Info, Result).Visit(E); 8263 } 8264 8265 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 8266 const VectorType *VTy = E->getType()->castAs<VectorType>(); 8267 unsigned NElts = VTy->getNumElements(); 8268 8269 const Expr *SE = E->getSubExpr(); 8270 QualType SETy = SE->getType(); 8271 8272 switch (E->getCastKind()) { 8273 case CK_VectorSplat: { 8274 APValue Val = APValue(); 8275 if (SETy->isIntegerType()) { 8276 APSInt IntResult; 8277 if (!EvaluateInteger(SE, IntResult, Info)) 8278 return false; 8279 Val = APValue(std::move(IntResult)); 8280 } else if (SETy->isRealFloatingType()) { 8281 APFloat FloatResult(0.0); 8282 if (!EvaluateFloat(SE, FloatResult, Info)) 8283 return false; 8284 Val = APValue(std::move(FloatResult)); 8285 } else { 8286 return Error(E); 8287 } 8288 8289 // Splat and create vector APValue. 8290 SmallVector<APValue, 4> Elts(NElts, Val); 8291 return Success(Elts, E); 8292 } 8293 case CK_BitCast: { 8294 // Evaluate the operand into an APInt we can extract from. 8295 llvm::APInt SValInt; 8296 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 8297 return false; 8298 // Extract the elements 8299 QualType EltTy = VTy->getElementType(); 8300 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 8301 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 8302 SmallVector<APValue, 4> Elts; 8303 if (EltTy->isRealFloatingType()) { 8304 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 8305 unsigned FloatEltSize = EltSize; 8306 if (&Sem == &APFloat::x87DoubleExtended()) 8307 FloatEltSize = 80; 8308 for (unsigned i = 0; i < NElts; i++) { 8309 llvm::APInt Elt; 8310 if (BigEndian) 8311 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 8312 else 8313 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 8314 Elts.push_back(APValue(APFloat(Sem, Elt))); 8315 } 8316 } else if (EltTy->isIntegerType()) { 8317 for (unsigned i = 0; i < NElts; i++) { 8318 llvm::APInt Elt; 8319 if (BigEndian) 8320 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 8321 else 8322 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 8323 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 8324 } 8325 } else { 8326 return Error(E); 8327 } 8328 return Success(Elts, E); 8329 } 8330 default: 8331 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8332 } 8333 } 8334 8335 bool 8336 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 8337 const VectorType *VT = E->getType()->castAs<VectorType>(); 8338 unsigned NumInits = E->getNumInits(); 8339 unsigned NumElements = VT->getNumElements(); 8340 8341 QualType EltTy = VT->getElementType(); 8342 SmallVector<APValue, 4> Elements; 8343 8344 // The number of initializers can be less than the number of 8345 // vector elements. For OpenCL, this can be due to nested vector 8346 // initialization. For GCC compatibility, missing trailing elements 8347 // should be initialized with zeroes. 8348 unsigned CountInits = 0, CountElts = 0; 8349 while (CountElts < NumElements) { 8350 // Handle nested vector initialization. 8351 if (CountInits < NumInits 8352 && E->getInit(CountInits)->getType()->isVectorType()) { 8353 APValue v; 8354 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 8355 return Error(E); 8356 unsigned vlen = v.getVectorLength(); 8357 for (unsigned j = 0; j < vlen; j++) 8358 Elements.push_back(v.getVectorElt(j)); 8359 CountElts += vlen; 8360 } else if (EltTy->isIntegerType()) { 8361 llvm::APSInt sInt(32); 8362 if (CountInits < NumInits) { 8363 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 8364 return false; 8365 } else // trailing integer zero. 8366 sInt = Info.Ctx.MakeIntValue(0, EltTy); 8367 Elements.push_back(APValue(sInt)); 8368 CountElts++; 8369 } else { 8370 llvm::APFloat f(0.0); 8371 if (CountInits < NumInits) { 8372 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 8373 return false; 8374 } else // trailing float zero. 8375 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 8376 Elements.push_back(APValue(f)); 8377 CountElts++; 8378 } 8379 CountInits++; 8380 } 8381 return Success(Elements, E); 8382 } 8383 8384 bool 8385 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 8386 const VectorType *VT = E->getType()->getAs<VectorType>(); 8387 QualType EltTy = VT->getElementType(); 8388 APValue ZeroElement; 8389 if (EltTy->isIntegerType()) 8390 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 8391 else 8392 ZeroElement = 8393 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 8394 8395 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 8396 return Success(Elements, E); 8397 } 8398 8399 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 8400 VisitIgnoredValue(E->getSubExpr()); 8401 return ZeroInitialization(E); 8402 } 8403 8404 //===----------------------------------------------------------------------===// 8405 // Array Evaluation 8406 //===----------------------------------------------------------------------===// 8407 8408 namespace { 8409 class ArrayExprEvaluator 8410 : public ExprEvaluatorBase<ArrayExprEvaluator> { 8411 const LValue &This; 8412 APValue &Result; 8413 public: 8414 8415 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 8416 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 8417 8418 bool Success(const APValue &V, const Expr *E) { 8419 assert(V.isArray() && "expected array"); 8420 Result = V; 8421 return true; 8422 } 8423 8424 bool ZeroInitialization(const Expr *E) { 8425 const ConstantArrayType *CAT = 8426 Info.Ctx.getAsConstantArrayType(E->getType()); 8427 if (!CAT) 8428 return Error(E); 8429 8430 Result = APValue(APValue::UninitArray(), 0, 8431 CAT->getSize().getZExtValue()); 8432 if (!Result.hasArrayFiller()) return true; 8433 8434 // Zero-initialize all elements. 8435 LValue Subobject = This; 8436 Subobject.addArray(Info, E, CAT); 8437 ImplicitValueInitExpr VIE(CAT->getElementType()); 8438 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 8439 } 8440 8441 bool VisitCallExpr(const CallExpr *E) { 8442 return handleCallExpr(E, Result, &This); 8443 } 8444 bool VisitInitListExpr(const InitListExpr *E); 8445 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 8446 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 8447 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 8448 const LValue &Subobject, 8449 APValue *Value, QualType Type); 8450 bool VisitStringLiteral(const StringLiteral *E) { 8451 expandStringLiteral(Info, E, Result); 8452 return true; 8453 } 8454 }; 8455 } // end anonymous namespace 8456 8457 static bool EvaluateArray(const Expr *E, const LValue &This, 8458 APValue &Result, EvalInfo &Info) { 8459 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 8460 return ArrayExprEvaluator(Info, This, Result).Visit(E); 8461 } 8462 8463 // Return true iff the given array filler may depend on the element index. 8464 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 8465 // For now, just whitelist non-class value-initialization and initialization 8466 // lists comprised of them. 8467 if (isa<ImplicitValueInitExpr>(FillerExpr)) 8468 return false; 8469 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 8470 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 8471 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 8472 return true; 8473 } 8474 return false; 8475 } 8476 return true; 8477 } 8478 8479 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 8480 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 8481 if (!CAT) 8482 return Error(E); 8483 8484 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 8485 // an appropriately-typed string literal enclosed in braces. 8486 if (E->isStringLiteralInit()) 8487 return Visit(E->getInit(0)); 8488 8489 bool Success = true; 8490 8491 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 8492 "zero-initialized array shouldn't have any initialized elts"); 8493 APValue Filler; 8494 if (Result.isArray() && Result.hasArrayFiller()) 8495 Filler = Result.getArrayFiller(); 8496 8497 unsigned NumEltsToInit = E->getNumInits(); 8498 unsigned NumElts = CAT->getSize().getZExtValue(); 8499 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 8500 8501 // If the initializer might depend on the array index, run it for each 8502 // array element. 8503 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 8504 NumEltsToInit = NumElts; 8505 8506 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 8507 << NumEltsToInit << ".\n"); 8508 8509 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 8510 8511 // If the array was previously zero-initialized, preserve the 8512 // zero-initialized values. 8513 if (Filler.hasValue()) { 8514 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 8515 Result.getArrayInitializedElt(I) = Filler; 8516 if (Result.hasArrayFiller()) 8517 Result.getArrayFiller() = Filler; 8518 } 8519 8520 LValue Subobject = This; 8521 Subobject.addArray(Info, E, CAT); 8522 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 8523 const Expr *Init = 8524 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 8525 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 8526 Info, Subobject, Init) || 8527 !HandleLValueArrayAdjustment(Info, Init, Subobject, 8528 CAT->getElementType(), 1)) { 8529 if (!Info.noteFailure()) 8530 return false; 8531 Success = false; 8532 } 8533 } 8534 8535 if (!Result.hasArrayFiller()) 8536 return Success; 8537 8538 // If we get here, we have a trivial filler, which we can just evaluate 8539 // once and splat over the rest of the array elements. 8540 assert(FillerExpr && "no array filler for incomplete init list"); 8541 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 8542 FillerExpr) && Success; 8543 } 8544 8545 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 8546 if (E->getCommonExpr() && 8547 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false), 8548 Info, E->getCommonExpr()->getSourceExpr())) 8549 return false; 8550 8551 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 8552 8553 uint64_t Elements = CAT->getSize().getZExtValue(); 8554 Result = APValue(APValue::UninitArray(), Elements, Elements); 8555 8556 LValue Subobject = This; 8557 Subobject.addArray(Info, E, CAT); 8558 8559 bool Success = true; 8560 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 8561 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 8562 Info, Subobject, E->getSubExpr()) || 8563 !HandleLValueArrayAdjustment(Info, E, Subobject, 8564 CAT->getElementType(), 1)) { 8565 if (!Info.noteFailure()) 8566 return false; 8567 Success = false; 8568 } 8569 } 8570 8571 return Success; 8572 } 8573 8574 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 8575 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 8576 } 8577 8578 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 8579 const LValue &Subobject, 8580 APValue *Value, 8581 QualType Type) { 8582 bool HadZeroInit = Value->hasValue(); 8583 8584 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 8585 unsigned N = CAT->getSize().getZExtValue(); 8586 8587 // Preserve the array filler if we had prior zero-initialization. 8588 APValue Filler = 8589 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 8590 : APValue(); 8591 8592 *Value = APValue(APValue::UninitArray(), N, N); 8593 8594 if (HadZeroInit) 8595 for (unsigned I = 0; I != N; ++I) 8596 Value->getArrayInitializedElt(I) = Filler; 8597 8598 // Initialize the elements. 8599 LValue ArrayElt = Subobject; 8600 ArrayElt.addArray(Info, E, CAT); 8601 for (unsigned I = 0; I != N; ++I) 8602 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 8603 CAT->getElementType()) || 8604 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 8605 CAT->getElementType(), 1)) 8606 return false; 8607 8608 return true; 8609 } 8610 8611 if (!Type->isRecordType()) 8612 return Error(E); 8613 8614 return RecordExprEvaluator(Info, Subobject, *Value) 8615 .VisitCXXConstructExpr(E, Type); 8616 } 8617 8618 //===----------------------------------------------------------------------===// 8619 // Integer Evaluation 8620 // 8621 // As a GNU extension, we support casting pointers to sufficiently-wide integer 8622 // types and back in constant folding. Integer values are thus represented 8623 // either as an integer-valued APValue, or as an lvalue-valued APValue. 8624 //===----------------------------------------------------------------------===// 8625 8626 namespace { 8627 class IntExprEvaluator 8628 : public ExprEvaluatorBase<IntExprEvaluator> { 8629 APValue &Result; 8630 public: 8631 IntExprEvaluator(EvalInfo &info, APValue &result) 8632 : ExprEvaluatorBaseTy(info), Result(result) {} 8633 8634 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 8635 assert(E->getType()->isIntegralOrEnumerationType() && 8636 "Invalid evaluation result."); 8637 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 8638 "Invalid evaluation result."); 8639 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 8640 "Invalid evaluation result."); 8641 Result = APValue(SI); 8642 return true; 8643 } 8644 bool Success(const llvm::APSInt &SI, const Expr *E) { 8645 return Success(SI, E, Result); 8646 } 8647 8648 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 8649 assert(E->getType()->isIntegralOrEnumerationType() && 8650 "Invalid evaluation result."); 8651 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 8652 "Invalid evaluation result."); 8653 Result = APValue(APSInt(I)); 8654 Result.getInt().setIsUnsigned( 8655 E->getType()->isUnsignedIntegerOrEnumerationType()); 8656 return true; 8657 } 8658 bool Success(const llvm::APInt &I, const Expr *E) { 8659 return Success(I, E, Result); 8660 } 8661 8662 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 8663 assert(E->getType()->isIntegralOrEnumerationType() && 8664 "Invalid evaluation result."); 8665 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 8666 return true; 8667 } 8668 bool Success(uint64_t Value, const Expr *E) { 8669 return Success(Value, E, Result); 8670 } 8671 8672 bool Success(CharUnits Size, const Expr *E) { 8673 return Success(Size.getQuantity(), E); 8674 } 8675 8676 bool Success(const APValue &V, const Expr *E) { 8677 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 8678 Result = V; 8679 return true; 8680 } 8681 return Success(V.getInt(), E); 8682 } 8683 8684 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 8685 8686 //===--------------------------------------------------------------------===// 8687 // Visitor Methods 8688 //===--------------------------------------------------------------------===// 8689 8690 bool VisitConstantExpr(const ConstantExpr *E); 8691 8692 bool VisitIntegerLiteral(const IntegerLiteral *E) { 8693 return Success(E->getValue(), E); 8694 } 8695 bool VisitCharacterLiteral(const CharacterLiteral *E) { 8696 return Success(E->getValue(), E); 8697 } 8698 8699 bool CheckReferencedDecl(const Expr *E, const Decl *D); 8700 bool VisitDeclRefExpr(const DeclRefExpr *E) { 8701 if (CheckReferencedDecl(E, E->getDecl())) 8702 return true; 8703 8704 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 8705 } 8706 bool VisitMemberExpr(const MemberExpr *E) { 8707 if (CheckReferencedDecl(E, E->getMemberDecl())) { 8708 VisitIgnoredBaseExpression(E->getBase()); 8709 return true; 8710 } 8711 8712 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 8713 } 8714 8715 bool VisitCallExpr(const CallExpr *E); 8716 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8717 bool VisitBinaryOperator(const BinaryOperator *E); 8718 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 8719 bool VisitUnaryOperator(const UnaryOperator *E); 8720 8721 bool VisitCastExpr(const CastExpr* E); 8722 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 8723 8724 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 8725 return Success(E->getValue(), E); 8726 } 8727 8728 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 8729 return Success(E->getValue(), E); 8730 } 8731 8732 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 8733 if (Info.ArrayInitIndex == uint64_t(-1)) { 8734 // We were asked to evaluate this subexpression independent of the 8735 // enclosing ArrayInitLoopExpr. We can't do that. 8736 Info.FFDiag(E); 8737 return false; 8738 } 8739 return Success(Info.ArrayInitIndex, E); 8740 } 8741 8742 // Note, GNU defines __null as an integer, not a pointer. 8743 bool VisitGNUNullExpr(const GNUNullExpr *E) { 8744 return ZeroInitialization(E); 8745 } 8746 8747 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 8748 return Success(E->getValue(), E); 8749 } 8750 8751 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 8752 return Success(E->getValue(), E); 8753 } 8754 8755 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 8756 return Success(E->getValue(), E); 8757 } 8758 8759 bool VisitUnaryReal(const UnaryOperator *E); 8760 bool VisitUnaryImag(const UnaryOperator *E); 8761 8762 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 8763 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 8764 bool VisitSourceLocExpr(const SourceLocExpr *E); 8765 // FIXME: Missing: array subscript of vector, member of vector 8766 }; 8767 8768 class FixedPointExprEvaluator 8769 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 8770 APValue &Result; 8771 8772 public: 8773 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 8774 : ExprEvaluatorBaseTy(info), Result(result) {} 8775 8776 bool Success(const llvm::APInt &I, const Expr *E) { 8777 return Success( 8778 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 8779 } 8780 8781 bool Success(uint64_t Value, const Expr *E) { 8782 return Success( 8783 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 8784 } 8785 8786 bool Success(const APValue &V, const Expr *E) { 8787 return Success(V.getFixedPoint(), E); 8788 } 8789 8790 bool Success(const APFixedPoint &V, const Expr *E) { 8791 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 8792 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 8793 "Invalid evaluation result."); 8794 Result = APValue(V); 8795 return true; 8796 } 8797 8798 //===--------------------------------------------------------------------===// 8799 // Visitor Methods 8800 //===--------------------------------------------------------------------===// 8801 8802 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 8803 return Success(E->getValue(), E); 8804 } 8805 8806 bool VisitCastExpr(const CastExpr *E); 8807 bool VisitUnaryOperator(const UnaryOperator *E); 8808 bool VisitBinaryOperator(const BinaryOperator *E); 8809 }; 8810 } // end anonymous namespace 8811 8812 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 8813 /// produce either the integer value or a pointer. 8814 /// 8815 /// GCC has a heinous extension which folds casts between pointer types and 8816 /// pointer-sized integral types. We support this by allowing the evaluation of 8817 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 8818 /// Some simple arithmetic on such values is supported (they are treated much 8819 /// like char*). 8820 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 8821 EvalInfo &Info) { 8822 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 8823 return IntExprEvaluator(Info, Result).Visit(E); 8824 } 8825 8826 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 8827 APValue Val; 8828 if (!EvaluateIntegerOrLValue(E, Val, Info)) 8829 return false; 8830 if (!Val.isInt()) { 8831 // FIXME: It would be better to produce the diagnostic for casting 8832 // a pointer to an integer. 8833 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 8834 return false; 8835 } 8836 Result = Val.getInt(); 8837 return true; 8838 } 8839 8840 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 8841 APValue Evaluated = E->EvaluateInContext( 8842 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8843 return Success(Evaluated, E); 8844 } 8845 8846 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 8847 EvalInfo &Info) { 8848 if (E->getType()->isFixedPointType()) { 8849 APValue Val; 8850 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 8851 return false; 8852 if (!Val.isFixedPoint()) 8853 return false; 8854 8855 Result = Val.getFixedPoint(); 8856 return true; 8857 } 8858 return false; 8859 } 8860 8861 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 8862 EvalInfo &Info) { 8863 if (E->getType()->isIntegerType()) { 8864 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 8865 APSInt Val; 8866 if (!EvaluateInteger(E, Val, Info)) 8867 return false; 8868 Result = APFixedPoint(Val, FXSema); 8869 return true; 8870 } else if (E->getType()->isFixedPointType()) { 8871 return EvaluateFixedPoint(E, Result, Info); 8872 } 8873 return false; 8874 } 8875 8876 /// Check whether the given declaration can be directly converted to an integral 8877 /// rvalue. If not, no diagnostic is produced; there are other things we can 8878 /// try. 8879 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 8880 // Enums are integer constant exprs. 8881 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 8882 // Check for signedness/width mismatches between E type and ECD value. 8883 bool SameSign = (ECD->getInitVal().isSigned() 8884 == E->getType()->isSignedIntegerOrEnumerationType()); 8885 bool SameWidth = (ECD->getInitVal().getBitWidth() 8886 == Info.Ctx.getIntWidth(E->getType())); 8887 if (SameSign && SameWidth) 8888 return Success(ECD->getInitVal(), E); 8889 else { 8890 // Get rid of mismatch (otherwise Success assertions will fail) 8891 // by computing a new value matching the type of E. 8892 llvm::APSInt Val = ECD->getInitVal(); 8893 if (!SameSign) 8894 Val.setIsSigned(!ECD->getInitVal().isSigned()); 8895 if (!SameWidth) 8896 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 8897 return Success(Val, E); 8898 } 8899 } 8900 return false; 8901 } 8902 8903 /// Values returned by __builtin_classify_type, chosen to match the values 8904 /// produced by GCC's builtin. 8905 enum class GCCTypeClass { 8906 None = -1, 8907 Void = 0, 8908 Integer = 1, 8909 // GCC reserves 2 for character types, but instead classifies them as 8910 // integers. 8911 Enum = 3, 8912 Bool = 4, 8913 Pointer = 5, 8914 // GCC reserves 6 for references, but appears to never use it (because 8915 // expressions never have reference type, presumably). 8916 PointerToDataMember = 7, 8917 RealFloat = 8, 8918 Complex = 9, 8919 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 8920 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 8921 // GCC claims to reserve 11 for pointers to member functions, but *actually* 8922 // uses 12 for that purpose, same as for a class or struct. Maybe it 8923 // internally implements a pointer to member as a struct? Who knows. 8924 PointerToMemberFunction = 12, // Not a bug, see above. 8925 ClassOrStruct = 12, 8926 Union = 13, 8927 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 8928 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 8929 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 8930 // literals. 8931 }; 8932 8933 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 8934 /// as GCC. 8935 static GCCTypeClass 8936 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 8937 assert(!T->isDependentType() && "unexpected dependent type"); 8938 8939 QualType CanTy = T.getCanonicalType(); 8940 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 8941 8942 switch (CanTy->getTypeClass()) { 8943 #define TYPE(ID, BASE) 8944 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 8945 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 8946 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 8947 #include "clang/AST/TypeNodes.def" 8948 case Type::Auto: 8949 case Type::DeducedTemplateSpecialization: 8950 llvm_unreachable("unexpected non-canonical or dependent type"); 8951 8952 case Type::Builtin: 8953 switch (BT->getKind()) { 8954 #define BUILTIN_TYPE(ID, SINGLETON_ID) 8955 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 8956 case BuiltinType::ID: return GCCTypeClass::Integer; 8957 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 8958 case BuiltinType::ID: return GCCTypeClass::RealFloat; 8959 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 8960 case BuiltinType::ID: break; 8961 #include "clang/AST/BuiltinTypes.def" 8962 case BuiltinType::Void: 8963 return GCCTypeClass::Void; 8964 8965 case BuiltinType::Bool: 8966 return GCCTypeClass::Bool; 8967 8968 case BuiltinType::Char_U: 8969 case BuiltinType::UChar: 8970 case BuiltinType::WChar_U: 8971 case BuiltinType::Char8: 8972 case BuiltinType::Char16: 8973 case BuiltinType::Char32: 8974 case BuiltinType::UShort: 8975 case BuiltinType::UInt: 8976 case BuiltinType::ULong: 8977 case BuiltinType::ULongLong: 8978 case BuiltinType::UInt128: 8979 return GCCTypeClass::Integer; 8980 8981 case BuiltinType::UShortAccum: 8982 case BuiltinType::UAccum: 8983 case BuiltinType::ULongAccum: 8984 case BuiltinType::UShortFract: 8985 case BuiltinType::UFract: 8986 case BuiltinType::ULongFract: 8987 case BuiltinType::SatUShortAccum: 8988 case BuiltinType::SatUAccum: 8989 case BuiltinType::SatULongAccum: 8990 case BuiltinType::SatUShortFract: 8991 case BuiltinType::SatUFract: 8992 case BuiltinType::SatULongFract: 8993 return GCCTypeClass::None; 8994 8995 case BuiltinType::NullPtr: 8996 8997 case BuiltinType::ObjCId: 8998 case BuiltinType::ObjCClass: 8999 case BuiltinType::ObjCSel: 9000 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 9001 case BuiltinType::Id: 9002 #include "clang/Basic/OpenCLImageTypes.def" 9003 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 9004 case BuiltinType::Id: 9005 #include "clang/Basic/OpenCLExtensionTypes.def" 9006 case BuiltinType::OCLSampler: 9007 case BuiltinType::OCLEvent: 9008 case BuiltinType::OCLClkEvent: 9009 case BuiltinType::OCLQueue: 9010 case BuiltinType::OCLReserveID: 9011 #define SVE_TYPE(Name, Id, SingletonId) \ 9012 case BuiltinType::Id: 9013 #include "clang/Basic/AArch64SVEACLETypes.def" 9014 return GCCTypeClass::None; 9015 9016 case BuiltinType::Dependent: 9017 llvm_unreachable("unexpected dependent type"); 9018 }; 9019 llvm_unreachable("unexpected placeholder type"); 9020 9021 case Type::Enum: 9022 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 9023 9024 case Type::Pointer: 9025 case Type::ConstantArray: 9026 case Type::VariableArray: 9027 case Type::IncompleteArray: 9028 case Type::FunctionNoProto: 9029 case Type::FunctionProto: 9030 return GCCTypeClass::Pointer; 9031 9032 case Type::MemberPointer: 9033 return CanTy->isMemberDataPointerType() 9034 ? GCCTypeClass::PointerToDataMember 9035 : GCCTypeClass::PointerToMemberFunction; 9036 9037 case Type::Complex: 9038 return GCCTypeClass::Complex; 9039 9040 case Type::Record: 9041 return CanTy->isUnionType() ? GCCTypeClass::Union 9042 : GCCTypeClass::ClassOrStruct; 9043 9044 case Type::Atomic: 9045 // GCC classifies _Atomic T the same as T. 9046 return EvaluateBuiltinClassifyType( 9047 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 9048 9049 case Type::BlockPointer: 9050 case Type::Vector: 9051 case Type::ExtVector: 9052 case Type::ObjCObject: 9053 case Type::ObjCInterface: 9054 case Type::ObjCObjectPointer: 9055 case Type::Pipe: 9056 // GCC classifies vectors as None. We follow its lead and classify all 9057 // other types that don't fit into the regular classification the same way. 9058 return GCCTypeClass::None; 9059 9060 case Type::LValueReference: 9061 case Type::RValueReference: 9062 llvm_unreachable("invalid type for expression"); 9063 } 9064 9065 llvm_unreachable("unexpected type class"); 9066 } 9067 9068 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 9069 /// as GCC. 9070 static GCCTypeClass 9071 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 9072 // If no argument was supplied, default to None. This isn't 9073 // ideal, however it is what gcc does. 9074 if (E->getNumArgs() == 0) 9075 return GCCTypeClass::None; 9076 9077 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 9078 // being an ICE, but still folds it to a constant using the type of the first 9079 // argument. 9080 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 9081 } 9082 9083 /// EvaluateBuiltinConstantPForLValue - Determine the result of 9084 /// __builtin_constant_p when applied to the given pointer. 9085 /// 9086 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 9087 /// or it points to the first character of a string literal. 9088 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 9089 APValue::LValueBase Base = LV.getLValueBase(); 9090 if (Base.isNull()) { 9091 // A null base is acceptable. 9092 return true; 9093 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 9094 if (!isa<StringLiteral>(E)) 9095 return false; 9096 return LV.getLValueOffset().isZero(); 9097 } else if (Base.is<TypeInfoLValue>()) { 9098 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 9099 // evaluate to true. 9100 return true; 9101 } else { 9102 // Any other base is not constant enough for GCC. 9103 return false; 9104 } 9105 } 9106 9107 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 9108 /// GCC as we can manage. 9109 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 9110 // This evaluation is not permitted to have side-effects, so evaluate it in 9111 // a speculative evaluation context. 9112 SpeculativeEvaluationRAII SpeculativeEval(Info); 9113 9114 // Constant-folding is always enabled for the operand of __builtin_constant_p 9115 // (even when the enclosing evaluation context otherwise requires a strict 9116 // language-specific constant expression). 9117 FoldConstant Fold(Info, true); 9118 9119 QualType ArgType = Arg->getType(); 9120 9121 // __builtin_constant_p always has one operand. The rules which gcc follows 9122 // are not precisely documented, but are as follows: 9123 // 9124 // - If the operand is of integral, floating, complex or enumeration type, 9125 // and can be folded to a known value of that type, it returns 1. 9126 // - If the operand can be folded to a pointer to the first character 9127 // of a string literal (or such a pointer cast to an integral type) 9128 // or to a null pointer or an integer cast to a pointer, it returns 1. 9129 // 9130 // Otherwise, it returns 0. 9131 // 9132 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 9133 // its support for this did not work prior to GCC 9 and is not yet well 9134 // understood. 9135 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 9136 ArgType->isAnyComplexType() || ArgType->isPointerType() || 9137 ArgType->isNullPtrType()) { 9138 APValue V; 9139 if (!::EvaluateAsRValue(Info, Arg, V)) { 9140 Fold.keepDiagnostics(); 9141 return false; 9142 } 9143 9144 // For a pointer (possibly cast to integer), there are special rules. 9145 if (V.getKind() == APValue::LValue) 9146 return EvaluateBuiltinConstantPForLValue(V); 9147 9148 // Otherwise, any constant value is good enough. 9149 return V.hasValue(); 9150 } 9151 9152 // Anything else isn't considered to be sufficiently constant. 9153 return false; 9154 } 9155 9156 /// Retrieves the "underlying object type" of the given expression, 9157 /// as used by __builtin_object_size. 9158 static QualType getObjectType(APValue::LValueBase B) { 9159 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 9160 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 9161 return VD->getType(); 9162 } else if (const Expr *E = B.get<const Expr*>()) { 9163 if (isa<CompoundLiteralExpr>(E)) 9164 return E->getType(); 9165 } else if (B.is<TypeInfoLValue>()) { 9166 return B.getTypeInfoType(); 9167 } 9168 9169 return QualType(); 9170 } 9171 9172 /// A more selective version of E->IgnoreParenCasts for 9173 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 9174 /// to change the type of E. 9175 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 9176 /// 9177 /// Always returns an RValue with a pointer representation. 9178 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 9179 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 9180 9181 auto *NoParens = E->IgnoreParens(); 9182 auto *Cast = dyn_cast<CastExpr>(NoParens); 9183 if (Cast == nullptr) 9184 return NoParens; 9185 9186 // We only conservatively allow a few kinds of casts, because this code is 9187 // inherently a simple solution that seeks to support the common case. 9188 auto CastKind = Cast->getCastKind(); 9189 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 9190 CastKind != CK_AddressSpaceConversion) 9191 return NoParens; 9192 9193 auto *SubExpr = Cast->getSubExpr(); 9194 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 9195 return NoParens; 9196 return ignorePointerCastsAndParens(SubExpr); 9197 } 9198 9199 /// Checks to see if the given LValue's Designator is at the end of the LValue's 9200 /// record layout. e.g. 9201 /// struct { struct { int a, b; } fst, snd; } obj; 9202 /// obj.fst // no 9203 /// obj.snd // yes 9204 /// obj.fst.a // no 9205 /// obj.fst.b // no 9206 /// obj.snd.a // no 9207 /// obj.snd.b // yes 9208 /// 9209 /// Please note: this function is specialized for how __builtin_object_size 9210 /// views "objects". 9211 /// 9212 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 9213 /// correct result, it will always return true. 9214 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 9215 assert(!LVal.Designator.Invalid); 9216 9217 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 9218 const RecordDecl *Parent = FD->getParent(); 9219 Invalid = Parent->isInvalidDecl(); 9220 if (Invalid || Parent->isUnion()) 9221 return true; 9222 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 9223 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 9224 }; 9225 9226 auto &Base = LVal.getLValueBase(); 9227 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 9228 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 9229 bool Invalid; 9230 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 9231 return Invalid; 9232 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 9233 for (auto *FD : IFD->chain()) { 9234 bool Invalid; 9235 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 9236 return Invalid; 9237 } 9238 } 9239 } 9240 9241 unsigned I = 0; 9242 QualType BaseType = getType(Base); 9243 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 9244 // If we don't know the array bound, conservatively assume we're looking at 9245 // the final array element. 9246 ++I; 9247 if (BaseType->isIncompleteArrayType()) 9248 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 9249 else 9250 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 9251 } 9252 9253 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 9254 const auto &Entry = LVal.Designator.Entries[I]; 9255 if (BaseType->isArrayType()) { 9256 // Because __builtin_object_size treats arrays as objects, we can ignore 9257 // the index iff this is the last array in the Designator. 9258 if (I + 1 == E) 9259 return true; 9260 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 9261 uint64_t Index = Entry.getAsArrayIndex(); 9262 if (Index + 1 != CAT->getSize()) 9263 return false; 9264 BaseType = CAT->getElementType(); 9265 } else if (BaseType->isAnyComplexType()) { 9266 const auto *CT = BaseType->castAs<ComplexType>(); 9267 uint64_t Index = Entry.getAsArrayIndex(); 9268 if (Index != 1) 9269 return false; 9270 BaseType = CT->getElementType(); 9271 } else if (auto *FD = getAsField(Entry)) { 9272 bool Invalid; 9273 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 9274 return Invalid; 9275 BaseType = FD->getType(); 9276 } else { 9277 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 9278 return false; 9279 } 9280 } 9281 return true; 9282 } 9283 9284 /// Tests to see if the LValue has a user-specified designator (that isn't 9285 /// necessarily valid). Note that this always returns 'true' if the LValue has 9286 /// an unsized array as its first designator entry, because there's currently no 9287 /// way to tell if the user typed *foo or foo[0]. 9288 static bool refersToCompleteObject(const LValue &LVal) { 9289 if (LVal.Designator.Invalid) 9290 return false; 9291 9292 if (!LVal.Designator.Entries.empty()) 9293 return LVal.Designator.isMostDerivedAnUnsizedArray(); 9294 9295 if (!LVal.InvalidBase) 9296 return true; 9297 9298 // If `E` is a MemberExpr, then the first part of the designator is hiding in 9299 // the LValueBase. 9300 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 9301 return !E || !isa<MemberExpr>(E); 9302 } 9303 9304 /// Attempts to detect a user writing into a piece of memory that's impossible 9305 /// to figure out the size of by just using types. 9306 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 9307 const SubobjectDesignator &Designator = LVal.Designator; 9308 // Notes: 9309 // - Users can only write off of the end when we have an invalid base. Invalid 9310 // bases imply we don't know where the memory came from. 9311 // - We used to be a bit more aggressive here; we'd only be conservative if 9312 // the array at the end was flexible, or if it had 0 or 1 elements. This 9313 // broke some common standard library extensions (PR30346), but was 9314 // otherwise seemingly fine. It may be useful to reintroduce this behavior 9315 // with some sort of whitelist. OTOH, it seems that GCC is always 9316 // conservative with the last element in structs (if it's an array), so our 9317 // current behavior is more compatible than a whitelisting approach would 9318 // be. 9319 return LVal.InvalidBase && 9320 Designator.Entries.size() == Designator.MostDerivedPathLength && 9321 Designator.MostDerivedIsArrayElement && 9322 isDesignatorAtObjectEnd(Ctx, LVal); 9323 } 9324 9325 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 9326 /// Fails if the conversion would cause loss of precision. 9327 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 9328 CharUnits &Result) { 9329 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 9330 if (Int.ugt(CharUnitsMax)) 9331 return false; 9332 Result = CharUnits::fromQuantity(Int.getZExtValue()); 9333 return true; 9334 } 9335 9336 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 9337 /// determine how many bytes exist from the beginning of the object to either 9338 /// the end of the current subobject, or the end of the object itself, depending 9339 /// on what the LValue looks like + the value of Type. 9340 /// 9341 /// If this returns false, the value of Result is undefined. 9342 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 9343 unsigned Type, const LValue &LVal, 9344 CharUnits &EndOffset) { 9345 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 9346 9347 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 9348 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 9349 return false; 9350 return HandleSizeof(Info, ExprLoc, Ty, Result); 9351 }; 9352 9353 // We want to evaluate the size of the entire object. This is a valid fallback 9354 // for when Type=1 and the designator is invalid, because we're asked for an 9355 // upper-bound. 9356 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 9357 // Type=3 wants a lower bound, so we can't fall back to this. 9358 if (Type == 3 && !DetermineForCompleteObject) 9359 return false; 9360 9361 llvm::APInt APEndOffset; 9362 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 9363 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 9364 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 9365 9366 if (LVal.InvalidBase) 9367 return false; 9368 9369 QualType BaseTy = getObjectType(LVal.getLValueBase()); 9370 return CheckedHandleSizeof(BaseTy, EndOffset); 9371 } 9372 9373 // We want to evaluate the size of a subobject. 9374 const SubobjectDesignator &Designator = LVal.Designator; 9375 9376 // The following is a moderately common idiom in C: 9377 // 9378 // struct Foo { int a; char c[1]; }; 9379 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 9380 // strcpy(&F->c[0], Bar); 9381 // 9382 // In order to not break too much legacy code, we need to support it. 9383 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 9384 // If we can resolve this to an alloc_size call, we can hand that back, 9385 // because we know for certain how many bytes there are to write to. 9386 llvm::APInt APEndOffset; 9387 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 9388 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 9389 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 9390 9391 // If we cannot determine the size of the initial allocation, then we can't 9392 // given an accurate upper-bound. However, we are still able to give 9393 // conservative lower-bounds for Type=3. 9394 if (Type == 1) 9395 return false; 9396 } 9397 9398 CharUnits BytesPerElem; 9399 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 9400 return false; 9401 9402 // According to the GCC documentation, we want the size of the subobject 9403 // denoted by the pointer. But that's not quite right -- what we actually 9404 // want is the size of the immediately-enclosing array, if there is one. 9405 int64_t ElemsRemaining; 9406 if (Designator.MostDerivedIsArrayElement && 9407 Designator.Entries.size() == Designator.MostDerivedPathLength) { 9408 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 9409 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 9410 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 9411 } else { 9412 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 9413 } 9414 9415 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 9416 return true; 9417 } 9418 9419 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 9420 /// returns true and stores the result in @p Size. 9421 /// 9422 /// If @p WasError is non-null, this will report whether the failure to evaluate 9423 /// is to be treated as an Error in IntExprEvaluator. 9424 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 9425 EvalInfo &Info, uint64_t &Size) { 9426 // Determine the denoted object. 9427 LValue LVal; 9428 { 9429 // The operand of __builtin_object_size is never evaluated for side-effects. 9430 // If there are any, but we can determine the pointed-to object anyway, then 9431 // ignore the side-effects. 9432 SpeculativeEvaluationRAII SpeculativeEval(Info); 9433 IgnoreSideEffectsRAII Fold(Info); 9434 9435 if (E->isGLValue()) { 9436 // It's possible for us to be given GLValues if we're called via 9437 // Expr::tryEvaluateObjectSize. 9438 APValue RVal; 9439 if (!EvaluateAsRValue(Info, E, RVal)) 9440 return false; 9441 LVal.setFrom(Info.Ctx, RVal); 9442 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 9443 /*InvalidBaseOK=*/true)) 9444 return false; 9445 } 9446 9447 // If we point to before the start of the object, there are no accessible 9448 // bytes. 9449 if (LVal.getLValueOffset().isNegative()) { 9450 Size = 0; 9451 return true; 9452 } 9453 9454 CharUnits EndOffset; 9455 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 9456 return false; 9457 9458 // If we've fallen outside of the end offset, just pretend there's nothing to 9459 // write to/read from. 9460 if (EndOffset <= LVal.getLValueOffset()) 9461 Size = 0; 9462 else 9463 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 9464 return true; 9465 } 9466 9467 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) { 9468 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true); 9469 if (E->getResultAPValueKind() != APValue::None) 9470 return Success(E->getAPValueResult(), E); 9471 return ExprEvaluatorBaseTy::VisitConstantExpr(E); 9472 } 9473 9474 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 9475 if (unsigned BuiltinOp = E->getBuiltinCallee()) 9476 return VisitBuiltinCallExpr(E, BuiltinOp); 9477 9478 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9479 } 9480 9481 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 9482 unsigned BuiltinOp) { 9483 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 9484 default: 9485 return ExprEvaluatorBaseTy::VisitCallExpr(E); 9486 9487 case Builtin::BI__builtin_dynamic_object_size: 9488 case Builtin::BI__builtin_object_size: { 9489 // The type was checked when we built the expression. 9490 unsigned Type = 9491 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 9492 assert(Type <= 3 && "unexpected type"); 9493 9494 uint64_t Size; 9495 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 9496 return Success(Size, E); 9497 9498 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 9499 return Success((Type & 2) ? 0 : -1, E); 9500 9501 // Expression had no side effects, but we couldn't statically determine the 9502 // size of the referenced object. 9503 switch (Info.EvalMode) { 9504 case EvalInfo::EM_ConstantExpression: 9505 case EvalInfo::EM_PotentialConstantExpression: 9506 case EvalInfo::EM_ConstantFold: 9507 case EvalInfo::EM_EvaluateForOverflow: 9508 case EvalInfo::EM_IgnoreSideEffects: 9509 // Leave it to IR generation. 9510 return Error(E); 9511 case EvalInfo::EM_ConstantExpressionUnevaluated: 9512 case EvalInfo::EM_PotentialConstantExpressionUnevaluated: 9513 // Reduce it to a constant now. 9514 return Success((Type & 2) ? 0 : -1, E); 9515 } 9516 9517 llvm_unreachable("unexpected EvalMode"); 9518 } 9519 9520 case Builtin::BI__builtin_os_log_format_buffer_size: { 9521 analyze_os_log::OSLogBufferLayout Layout; 9522 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 9523 return Success(Layout.size().getQuantity(), E); 9524 } 9525 9526 case Builtin::BI__builtin_bswap16: 9527 case Builtin::BI__builtin_bswap32: 9528 case Builtin::BI__builtin_bswap64: { 9529 APSInt Val; 9530 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9531 return false; 9532 9533 return Success(Val.byteSwap(), E); 9534 } 9535 9536 case Builtin::BI__builtin_classify_type: 9537 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 9538 9539 case Builtin::BI__builtin_clrsb: 9540 case Builtin::BI__builtin_clrsbl: 9541 case Builtin::BI__builtin_clrsbll: { 9542 APSInt Val; 9543 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9544 return false; 9545 9546 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 9547 } 9548 9549 case Builtin::BI__builtin_clz: 9550 case Builtin::BI__builtin_clzl: 9551 case Builtin::BI__builtin_clzll: 9552 case Builtin::BI__builtin_clzs: { 9553 APSInt Val; 9554 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9555 return false; 9556 if (!Val) 9557 return Error(E); 9558 9559 return Success(Val.countLeadingZeros(), E); 9560 } 9561 9562 case Builtin::BI__builtin_constant_p: { 9563 const Expr *Arg = E->getArg(0); 9564 if (EvaluateBuiltinConstantP(Info, Arg)) 9565 return Success(true, E); 9566 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 9567 // Outside a constant context, eagerly evaluate to false in the presence 9568 // of side-effects in order to avoid -Wunsequenced false-positives in 9569 // a branch on __builtin_constant_p(expr). 9570 return Success(false, E); 9571 } 9572 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 9573 return false; 9574 } 9575 9576 case Builtin::BI__builtin_is_constant_evaluated: 9577 return Success(Info.InConstantContext, E); 9578 9579 case Builtin::BI__builtin_ctz: 9580 case Builtin::BI__builtin_ctzl: 9581 case Builtin::BI__builtin_ctzll: 9582 case Builtin::BI__builtin_ctzs: { 9583 APSInt Val; 9584 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9585 return false; 9586 if (!Val) 9587 return Error(E); 9588 9589 return Success(Val.countTrailingZeros(), E); 9590 } 9591 9592 case Builtin::BI__builtin_eh_return_data_regno: { 9593 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 9594 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 9595 return Success(Operand, E); 9596 } 9597 9598 case Builtin::BI__builtin_expect: 9599 return Visit(E->getArg(0)); 9600 9601 case Builtin::BI__builtin_ffs: 9602 case Builtin::BI__builtin_ffsl: 9603 case Builtin::BI__builtin_ffsll: { 9604 APSInt Val; 9605 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9606 return false; 9607 9608 unsigned N = Val.countTrailingZeros(); 9609 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 9610 } 9611 9612 case Builtin::BI__builtin_fpclassify: { 9613 APFloat Val(0.0); 9614 if (!EvaluateFloat(E->getArg(5), Val, Info)) 9615 return false; 9616 unsigned Arg; 9617 switch (Val.getCategory()) { 9618 case APFloat::fcNaN: Arg = 0; break; 9619 case APFloat::fcInfinity: Arg = 1; break; 9620 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 9621 case APFloat::fcZero: Arg = 4; break; 9622 } 9623 return Visit(E->getArg(Arg)); 9624 } 9625 9626 case Builtin::BI__builtin_isinf_sign: { 9627 APFloat Val(0.0); 9628 return EvaluateFloat(E->getArg(0), Val, Info) && 9629 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 9630 } 9631 9632 case Builtin::BI__builtin_isinf: { 9633 APFloat Val(0.0); 9634 return EvaluateFloat(E->getArg(0), Val, Info) && 9635 Success(Val.isInfinity() ? 1 : 0, E); 9636 } 9637 9638 case Builtin::BI__builtin_isfinite: { 9639 APFloat Val(0.0); 9640 return EvaluateFloat(E->getArg(0), Val, Info) && 9641 Success(Val.isFinite() ? 1 : 0, E); 9642 } 9643 9644 case Builtin::BI__builtin_isnan: { 9645 APFloat Val(0.0); 9646 return EvaluateFloat(E->getArg(0), Val, Info) && 9647 Success(Val.isNaN() ? 1 : 0, E); 9648 } 9649 9650 case Builtin::BI__builtin_isnormal: { 9651 APFloat Val(0.0); 9652 return EvaluateFloat(E->getArg(0), Val, Info) && 9653 Success(Val.isNormal() ? 1 : 0, E); 9654 } 9655 9656 case Builtin::BI__builtin_parity: 9657 case Builtin::BI__builtin_parityl: 9658 case Builtin::BI__builtin_parityll: { 9659 APSInt Val; 9660 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9661 return false; 9662 9663 return Success(Val.countPopulation() % 2, E); 9664 } 9665 9666 case Builtin::BI__builtin_popcount: 9667 case Builtin::BI__builtin_popcountl: 9668 case Builtin::BI__builtin_popcountll: { 9669 APSInt Val; 9670 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9671 return false; 9672 9673 return Success(Val.countPopulation(), E); 9674 } 9675 9676 case Builtin::BIstrlen: 9677 case Builtin::BIwcslen: 9678 // A call to strlen is not a constant expression. 9679 if (Info.getLangOpts().CPlusPlus11) 9680 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9681 << /*isConstexpr*/0 << /*isConstructor*/0 9682 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9683 else 9684 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9685 LLVM_FALLTHROUGH; 9686 case Builtin::BI__builtin_strlen: 9687 case Builtin::BI__builtin_wcslen: { 9688 // As an extension, we support __builtin_strlen() as a constant expression, 9689 // and support folding strlen() to a constant. 9690 LValue String; 9691 if (!EvaluatePointer(E->getArg(0), String, Info)) 9692 return false; 9693 9694 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 9695 9696 // Fast path: if it's a string literal, search the string value. 9697 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 9698 String.getLValueBase().dyn_cast<const Expr *>())) { 9699 // The string literal may have embedded null characters. Find the first 9700 // one and truncate there. 9701 StringRef Str = S->getBytes(); 9702 int64_t Off = String.Offset.getQuantity(); 9703 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 9704 S->getCharByteWidth() == 1 && 9705 // FIXME: Add fast-path for wchar_t too. 9706 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 9707 Str = Str.substr(Off); 9708 9709 StringRef::size_type Pos = Str.find(0); 9710 if (Pos != StringRef::npos) 9711 Str = Str.substr(0, Pos); 9712 9713 return Success(Str.size(), E); 9714 } 9715 9716 // Fall through to slow path to issue appropriate diagnostic. 9717 } 9718 9719 // Slow path: scan the bytes of the string looking for the terminating 0. 9720 for (uint64_t Strlen = 0; /**/; ++Strlen) { 9721 APValue Char; 9722 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 9723 !Char.isInt()) 9724 return false; 9725 if (!Char.getInt()) 9726 return Success(Strlen, E); 9727 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 9728 return false; 9729 } 9730 } 9731 9732 case Builtin::BIstrcmp: 9733 case Builtin::BIwcscmp: 9734 case Builtin::BIstrncmp: 9735 case Builtin::BIwcsncmp: 9736 case Builtin::BImemcmp: 9737 case Builtin::BIbcmp: 9738 case Builtin::BIwmemcmp: 9739 // A call to strlen is not a constant expression. 9740 if (Info.getLangOpts().CPlusPlus11) 9741 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9742 << /*isConstexpr*/0 << /*isConstructor*/0 9743 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9744 else 9745 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9746 LLVM_FALLTHROUGH; 9747 case Builtin::BI__builtin_strcmp: 9748 case Builtin::BI__builtin_wcscmp: 9749 case Builtin::BI__builtin_strncmp: 9750 case Builtin::BI__builtin_wcsncmp: 9751 case Builtin::BI__builtin_memcmp: 9752 case Builtin::BI__builtin_bcmp: 9753 case Builtin::BI__builtin_wmemcmp: { 9754 LValue String1, String2; 9755 if (!EvaluatePointer(E->getArg(0), String1, Info) || 9756 !EvaluatePointer(E->getArg(1), String2, Info)) 9757 return false; 9758 9759 uint64_t MaxLength = uint64_t(-1); 9760 if (BuiltinOp != Builtin::BIstrcmp && 9761 BuiltinOp != Builtin::BIwcscmp && 9762 BuiltinOp != Builtin::BI__builtin_strcmp && 9763 BuiltinOp != Builtin::BI__builtin_wcscmp) { 9764 APSInt N; 9765 if (!EvaluateInteger(E->getArg(2), N, Info)) 9766 return false; 9767 MaxLength = N.getExtValue(); 9768 } 9769 9770 // Empty substrings compare equal by definition. 9771 if (MaxLength == 0u) 9772 return Success(0, E); 9773 9774 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9775 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9776 String1.Designator.Invalid || String2.Designator.Invalid) 9777 return false; 9778 9779 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 9780 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 9781 9782 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 9783 BuiltinOp == Builtin::BIbcmp || 9784 BuiltinOp == Builtin::BI__builtin_memcmp || 9785 BuiltinOp == Builtin::BI__builtin_bcmp; 9786 9787 assert(IsRawByte || 9788 (Info.Ctx.hasSameUnqualifiedType( 9789 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 9790 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 9791 9792 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 9793 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 9794 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 9795 Char1.isInt() && Char2.isInt(); 9796 }; 9797 const auto &AdvanceElems = [&] { 9798 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 9799 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 9800 }; 9801 9802 if (IsRawByte) { 9803 uint64_t BytesRemaining = MaxLength; 9804 // Pointers to const void may point to objects of incomplete type. 9805 if (CharTy1->isIncompleteType()) { 9806 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1; 9807 return false; 9808 } 9809 if (CharTy2->isIncompleteType()) { 9810 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2; 9811 return false; 9812 } 9813 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)}; 9814 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width); 9815 // Give up on comparing between elements with disparate widths. 9816 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2)) 9817 return false; 9818 uint64_t BytesPerElement = CharTy1Size.getQuantity(); 9819 assert(BytesRemaining && "BytesRemaining should not be zero: the " 9820 "following loop considers at least one element"); 9821 while (true) { 9822 APValue Char1, Char2; 9823 if (!ReadCurElems(Char1, Char2)) 9824 return false; 9825 // We have compatible in-memory widths, but a possible type and 9826 // (for `bool`) internal representation mismatch. 9827 // Assuming two's complement representation, including 0 for `false` and 9828 // 1 for `true`, we can check an appropriate number of elements for 9829 // equality even if they are not byte-sized. 9830 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width); 9831 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width); 9832 if (Char1InMem.ne(Char2InMem)) { 9833 // If the elements are byte-sized, then we can produce a three-way 9834 // comparison result in a straightforward manner. 9835 if (BytesPerElement == 1u) { 9836 // memcmp always compares unsigned chars. 9837 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E); 9838 } 9839 // The result is byte-order sensitive, and we have multibyte elements. 9840 // FIXME: We can compare the remaining bytes in the correct order. 9841 return false; 9842 } 9843 if (!AdvanceElems()) 9844 return false; 9845 if (BytesRemaining <= BytesPerElement) 9846 break; 9847 BytesRemaining -= BytesPerElement; 9848 } 9849 // Enough elements are equal to account for the memcmp limit. 9850 return Success(0, E); 9851 } 9852 9853 bool StopAtNull = 9854 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 9855 BuiltinOp != Builtin::BIwmemcmp && 9856 BuiltinOp != Builtin::BI__builtin_memcmp && 9857 BuiltinOp != Builtin::BI__builtin_bcmp && 9858 BuiltinOp != Builtin::BI__builtin_wmemcmp); 9859 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 9860 BuiltinOp == Builtin::BIwcsncmp || 9861 BuiltinOp == Builtin::BIwmemcmp || 9862 BuiltinOp == Builtin::BI__builtin_wcscmp || 9863 BuiltinOp == Builtin::BI__builtin_wcsncmp || 9864 BuiltinOp == Builtin::BI__builtin_wmemcmp; 9865 9866 for (; MaxLength; --MaxLength) { 9867 APValue Char1, Char2; 9868 if (!ReadCurElems(Char1, Char2)) 9869 return false; 9870 if (Char1.getInt() != Char2.getInt()) { 9871 if (IsWide) // wmemcmp compares with wchar_t signedness. 9872 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 9873 // memcmp always compares unsigned chars. 9874 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 9875 } 9876 if (StopAtNull && !Char1.getInt()) 9877 return Success(0, E); 9878 assert(!(StopAtNull && !Char2.getInt())); 9879 if (!AdvanceElems()) 9880 return false; 9881 } 9882 // We hit the strncmp / memcmp limit. 9883 return Success(0, E); 9884 } 9885 9886 case Builtin::BI__atomic_always_lock_free: 9887 case Builtin::BI__atomic_is_lock_free: 9888 case Builtin::BI__c11_atomic_is_lock_free: { 9889 APSInt SizeVal; 9890 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 9891 return false; 9892 9893 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 9894 // of two less than the maximum inline atomic width, we know it is 9895 // lock-free. If the size isn't a power of two, or greater than the 9896 // maximum alignment where we promote atomics, we know it is not lock-free 9897 // (at least not in the sense of atomic_is_lock_free). Otherwise, 9898 // the answer can only be determined at runtime; for example, 16-byte 9899 // atomics have lock-free implementations on some, but not all, 9900 // x86-64 processors. 9901 9902 // Check power-of-two. 9903 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 9904 if (Size.isPowerOfTwo()) { 9905 // Check against inlining width. 9906 unsigned InlineWidthBits = 9907 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 9908 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 9909 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 9910 Size == CharUnits::One() || 9911 E->getArg(1)->isNullPointerConstant(Info.Ctx, 9912 Expr::NPC_NeverValueDependent)) 9913 // OK, we will inline appropriately-aligned operations of this size, 9914 // and _Atomic(T) is appropriately-aligned. 9915 return Success(1, E); 9916 9917 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 9918 castAs<PointerType>()->getPointeeType(); 9919 if (!PointeeType->isIncompleteType() && 9920 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 9921 // OK, we will inline operations on this object. 9922 return Success(1, E); 9923 } 9924 } 9925 } 9926 9927 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 9928 Success(0, E) : Error(E); 9929 } 9930 case Builtin::BIomp_is_initial_device: 9931 // We can decide statically which value the runtime would return if called. 9932 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 9933 case Builtin::BI__builtin_add_overflow: 9934 case Builtin::BI__builtin_sub_overflow: 9935 case Builtin::BI__builtin_mul_overflow: 9936 case Builtin::BI__builtin_sadd_overflow: 9937 case Builtin::BI__builtin_uadd_overflow: 9938 case Builtin::BI__builtin_uaddl_overflow: 9939 case Builtin::BI__builtin_uaddll_overflow: 9940 case Builtin::BI__builtin_usub_overflow: 9941 case Builtin::BI__builtin_usubl_overflow: 9942 case Builtin::BI__builtin_usubll_overflow: 9943 case Builtin::BI__builtin_umul_overflow: 9944 case Builtin::BI__builtin_umull_overflow: 9945 case Builtin::BI__builtin_umulll_overflow: 9946 case Builtin::BI__builtin_saddl_overflow: 9947 case Builtin::BI__builtin_saddll_overflow: 9948 case Builtin::BI__builtin_ssub_overflow: 9949 case Builtin::BI__builtin_ssubl_overflow: 9950 case Builtin::BI__builtin_ssubll_overflow: 9951 case Builtin::BI__builtin_smul_overflow: 9952 case Builtin::BI__builtin_smull_overflow: 9953 case Builtin::BI__builtin_smulll_overflow: { 9954 LValue ResultLValue; 9955 APSInt LHS, RHS; 9956 9957 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 9958 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 9959 !EvaluateInteger(E->getArg(1), RHS, Info) || 9960 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 9961 return false; 9962 9963 APSInt Result; 9964 bool DidOverflow = false; 9965 9966 // If the types don't have to match, enlarge all 3 to the largest of them. 9967 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 9968 BuiltinOp == Builtin::BI__builtin_sub_overflow || 9969 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 9970 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 9971 ResultType->isSignedIntegerOrEnumerationType(); 9972 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 9973 ResultType->isSignedIntegerOrEnumerationType(); 9974 uint64_t LHSSize = LHS.getBitWidth(); 9975 uint64_t RHSSize = RHS.getBitWidth(); 9976 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 9977 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 9978 9979 // Add an additional bit if the signedness isn't uniformly agreed to. We 9980 // could do this ONLY if there is a signed and an unsigned that both have 9981 // MaxBits, but the code to check that is pretty nasty. The issue will be 9982 // caught in the shrink-to-result later anyway. 9983 if (IsSigned && !AllSigned) 9984 ++MaxBits; 9985 9986 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 9987 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 9988 Result = APSInt(MaxBits, !IsSigned); 9989 } 9990 9991 // Find largest int. 9992 switch (BuiltinOp) { 9993 default: 9994 llvm_unreachable("Invalid value for BuiltinOp"); 9995 case Builtin::BI__builtin_add_overflow: 9996 case Builtin::BI__builtin_sadd_overflow: 9997 case Builtin::BI__builtin_saddl_overflow: 9998 case Builtin::BI__builtin_saddll_overflow: 9999 case Builtin::BI__builtin_uadd_overflow: 10000 case Builtin::BI__builtin_uaddl_overflow: 10001 case Builtin::BI__builtin_uaddll_overflow: 10002 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 10003 : LHS.uadd_ov(RHS, DidOverflow); 10004 break; 10005 case Builtin::BI__builtin_sub_overflow: 10006 case Builtin::BI__builtin_ssub_overflow: 10007 case Builtin::BI__builtin_ssubl_overflow: 10008 case Builtin::BI__builtin_ssubll_overflow: 10009 case Builtin::BI__builtin_usub_overflow: 10010 case Builtin::BI__builtin_usubl_overflow: 10011 case Builtin::BI__builtin_usubll_overflow: 10012 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 10013 : LHS.usub_ov(RHS, DidOverflow); 10014 break; 10015 case Builtin::BI__builtin_mul_overflow: 10016 case Builtin::BI__builtin_smul_overflow: 10017 case Builtin::BI__builtin_smull_overflow: 10018 case Builtin::BI__builtin_smulll_overflow: 10019 case Builtin::BI__builtin_umul_overflow: 10020 case Builtin::BI__builtin_umull_overflow: 10021 case Builtin::BI__builtin_umulll_overflow: 10022 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 10023 : LHS.umul_ov(RHS, DidOverflow); 10024 break; 10025 } 10026 10027 // In the case where multiple sizes are allowed, truncate and see if 10028 // the values are the same. 10029 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 10030 BuiltinOp == Builtin::BI__builtin_sub_overflow || 10031 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 10032 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 10033 // since it will give us the behavior of a TruncOrSelf in the case where 10034 // its parameter <= its size. We previously set Result to be at least the 10035 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 10036 // will work exactly like TruncOrSelf. 10037 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 10038 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 10039 10040 if (!APSInt::isSameValue(Temp, Result)) 10041 DidOverflow = true; 10042 Result = Temp; 10043 } 10044 10045 APValue APV{Result}; 10046 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 10047 return false; 10048 return Success(DidOverflow, E); 10049 } 10050 } 10051 } 10052 10053 /// Determine whether this is a pointer past the end of the complete 10054 /// object referred to by the lvalue. 10055 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 10056 const LValue &LV) { 10057 // A null pointer can be viewed as being "past the end" but we don't 10058 // choose to look at it that way here. 10059 if (!LV.getLValueBase()) 10060 return false; 10061 10062 // If the designator is valid and refers to a subobject, we're not pointing 10063 // past the end. 10064 if (!LV.getLValueDesignator().Invalid && 10065 !LV.getLValueDesignator().isOnePastTheEnd()) 10066 return false; 10067 10068 // A pointer to an incomplete type might be past-the-end if the type's size is 10069 // zero. We cannot tell because the type is incomplete. 10070 QualType Ty = getType(LV.getLValueBase()); 10071 if (Ty->isIncompleteType()) 10072 return true; 10073 10074 // We're a past-the-end pointer if we point to the byte after the object, 10075 // no matter what our type or path is. 10076 auto Size = Ctx.getTypeSizeInChars(Ty); 10077 return LV.getLValueOffset() == Size; 10078 } 10079 10080 namespace { 10081 10082 /// Data recursive integer evaluator of certain binary operators. 10083 /// 10084 /// We use a data recursive algorithm for binary operators so that we are able 10085 /// to handle extreme cases of chained binary operators without causing stack 10086 /// overflow. 10087 class DataRecursiveIntBinOpEvaluator { 10088 struct EvalResult { 10089 APValue Val; 10090 bool Failed; 10091 10092 EvalResult() : Failed(false) { } 10093 10094 void swap(EvalResult &RHS) { 10095 Val.swap(RHS.Val); 10096 Failed = RHS.Failed; 10097 RHS.Failed = false; 10098 } 10099 }; 10100 10101 struct Job { 10102 const Expr *E; 10103 EvalResult LHSResult; // meaningful only for binary operator expression. 10104 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 10105 10106 Job() = default; 10107 Job(Job &&) = default; 10108 10109 void startSpeculativeEval(EvalInfo &Info) { 10110 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 10111 } 10112 10113 private: 10114 SpeculativeEvaluationRAII SpecEvalRAII; 10115 }; 10116 10117 SmallVector<Job, 16> Queue; 10118 10119 IntExprEvaluator &IntEval; 10120 EvalInfo &Info; 10121 APValue &FinalResult; 10122 10123 public: 10124 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 10125 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 10126 10127 /// True if \param E is a binary operator that we are going to handle 10128 /// data recursively. 10129 /// We handle binary operators that are comma, logical, or that have operands 10130 /// with integral or enumeration type. 10131 static bool shouldEnqueue(const BinaryOperator *E) { 10132 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 10133 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 10134 E->getLHS()->getType()->isIntegralOrEnumerationType() && 10135 E->getRHS()->getType()->isIntegralOrEnumerationType()); 10136 } 10137 10138 bool Traverse(const BinaryOperator *E) { 10139 enqueue(E); 10140 EvalResult PrevResult; 10141 while (!Queue.empty()) 10142 process(PrevResult); 10143 10144 if (PrevResult.Failed) return false; 10145 10146 FinalResult.swap(PrevResult.Val); 10147 return true; 10148 } 10149 10150 private: 10151 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10152 return IntEval.Success(Value, E, Result); 10153 } 10154 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 10155 return IntEval.Success(Value, E, Result); 10156 } 10157 bool Error(const Expr *E) { 10158 return IntEval.Error(E); 10159 } 10160 bool Error(const Expr *E, diag::kind D) { 10161 return IntEval.Error(E, D); 10162 } 10163 10164 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 10165 return Info.CCEDiag(E, D); 10166 } 10167 10168 // Returns true if visiting the RHS is necessary, false otherwise. 10169 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 10170 bool &SuppressRHSDiags); 10171 10172 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 10173 const BinaryOperator *E, APValue &Result); 10174 10175 void EvaluateExpr(const Expr *E, EvalResult &Result) { 10176 Result.Failed = !Evaluate(Result.Val, Info, E); 10177 if (Result.Failed) 10178 Result.Val = APValue(); 10179 } 10180 10181 void process(EvalResult &Result); 10182 10183 void enqueue(const Expr *E) { 10184 E = E->IgnoreParens(); 10185 Queue.resize(Queue.size()+1); 10186 Queue.back().E = E; 10187 Queue.back().Kind = Job::AnyExprKind; 10188 } 10189 }; 10190 10191 } 10192 10193 bool DataRecursiveIntBinOpEvaluator:: 10194 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 10195 bool &SuppressRHSDiags) { 10196 if (E->getOpcode() == BO_Comma) { 10197 // Ignore LHS but note if we could not evaluate it. 10198 if (LHSResult.Failed) 10199 return Info.noteSideEffect(); 10200 return true; 10201 } 10202 10203 if (E->isLogicalOp()) { 10204 bool LHSAsBool; 10205 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 10206 // We were able to evaluate the LHS, see if we can get away with not 10207 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 10208 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 10209 Success(LHSAsBool, E, LHSResult.Val); 10210 return false; // Ignore RHS 10211 } 10212 } else { 10213 LHSResult.Failed = true; 10214 10215 // Since we weren't able to evaluate the left hand side, it 10216 // might have had side effects. 10217 if (!Info.noteSideEffect()) 10218 return false; 10219 10220 // We can't evaluate the LHS; however, sometimes the result 10221 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 10222 // Don't ignore RHS and suppress diagnostics from this arm. 10223 SuppressRHSDiags = true; 10224 } 10225 10226 return true; 10227 } 10228 10229 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 10230 E->getRHS()->getType()->isIntegralOrEnumerationType()); 10231 10232 if (LHSResult.Failed && !Info.noteFailure()) 10233 return false; // Ignore RHS; 10234 10235 return true; 10236 } 10237 10238 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 10239 bool IsSub) { 10240 // Compute the new offset in the appropriate width, wrapping at 64 bits. 10241 // FIXME: When compiling for a 32-bit target, we should use 32-bit 10242 // offsets. 10243 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 10244 CharUnits &Offset = LVal.getLValueOffset(); 10245 uint64_t Offset64 = Offset.getQuantity(); 10246 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 10247 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 10248 : Offset64 + Index64); 10249 } 10250 10251 bool DataRecursiveIntBinOpEvaluator:: 10252 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 10253 const BinaryOperator *E, APValue &Result) { 10254 if (E->getOpcode() == BO_Comma) { 10255 if (RHSResult.Failed) 10256 return false; 10257 Result = RHSResult.Val; 10258 return true; 10259 } 10260 10261 if (E->isLogicalOp()) { 10262 bool lhsResult, rhsResult; 10263 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 10264 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 10265 10266 if (LHSIsOK) { 10267 if (RHSIsOK) { 10268 if (E->getOpcode() == BO_LOr) 10269 return Success(lhsResult || rhsResult, E, Result); 10270 else 10271 return Success(lhsResult && rhsResult, E, Result); 10272 } 10273 } else { 10274 if (RHSIsOK) { 10275 // We can't evaluate the LHS; however, sometimes the result 10276 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 10277 if (rhsResult == (E->getOpcode() == BO_LOr)) 10278 return Success(rhsResult, E, Result); 10279 } 10280 } 10281 10282 return false; 10283 } 10284 10285 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 10286 E->getRHS()->getType()->isIntegralOrEnumerationType()); 10287 10288 if (LHSResult.Failed || RHSResult.Failed) 10289 return false; 10290 10291 const APValue &LHSVal = LHSResult.Val; 10292 const APValue &RHSVal = RHSResult.Val; 10293 10294 // Handle cases like (unsigned long)&a + 4. 10295 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 10296 Result = LHSVal; 10297 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 10298 return true; 10299 } 10300 10301 // Handle cases like 4 + (unsigned long)&a 10302 if (E->getOpcode() == BO_Add && 10303 RHSVal.isLValue() && LHSVal.isInt()) { 10304 Result = RHSVal; 10305 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 10306 return true; 10307 } 10308 10309 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 10310 // Handle (intptr_t)&&A - (intptr_t)&&B. 10311 if (!LHSVal.getLValueOffset().isZero() || 10312 !RHSVal.getLValueOffset().isZero()) 10313 return false; 10314 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 10315 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 10316 if (!LHSExpr || !RHSExpr) 10317 return false; 10318 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 10319 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 10320 if (!LHSAddrExpr || !RHSAddrExpr) 10321 return false; 10322 // Make sure both labels come from the same function. 10323 if (LHSAddrExpr->getLabel()->getDeclContext() != 10324 RHSAddrExpr->getLabel()->getDeclContext()) 10325 return false; 10326 Result = APValue(LHSAddrExpr, RHSAddrExpr); 10327 return true; 10328 } 10329 10330 // All the remaining cases expect both operands to be an integer 10331 if (!LHSVal.isInt() || !RHSVal.isInt()) 10332 return Error(E); 10333 10334 // Set up the width and signedness manually, in case it can't be deduced 10335 // from the operation we're performing. 10336 // FIXME: Don't do this in the cases where we can deduce it. 10337 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 10338 E->getType()->isUnsignedIntegerOrEnumerationType()); 10339 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 10340 RHSVal.getInt(), Value)) 10341 return false; 10342 return Success(Value, E, Result); 10343 } 10344 10345 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 10346 Job &job = Queue.back(); 10347 10348 switch (job.Kind) { 10349 case Job::AnyExprKind: { 10350 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 10351 if (shouldEnqueue(Bop)) { 10352 job.Kind = Job::BinOpKind; 10353 enqueue(Bop->getLHS()); 10354 return; 10355 } 10356 } 10357 10358 EvaluateExpr(job.E, Result); 10359 Queue.pop_back(); 10360 return; 10361 } 10362 10363 case Job::BinOpKind: { 10364 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 10365 bool SuppressRHSDiags = false; 10366 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 10367 Queue.pop_back(); 10368 return; 10369 } 10370 if (SuppressRHSDiags) 10371 job.startSpeculativeEval(Info); 10372 job.LHSResult.swap(Result); 10373 job.Kind = Job::BinOpVisitedLHSKind; 10374 enqueue(Bop->getRHS()); 10375 return; 10376 } 10377 10378 case Job::BinOpVisitedLHSKind: { 10379 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 10380 EvalResult RHS; 10381 RHS.swap(Result); 10382 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 10383 Queue.pop_back(); 10384 return; 10385 } 10386 } 10387 10388 llvm_unreachable("Invalid Job::Kind!"); 10389 } 10390 10391 namespace { 10392 /// Used when we determine that we should fail, but can keep evaluating prior to 10393 /// noting that we had a failure. 10394 class DelayedNoteFailureRAII { 10395 EvalInfo &Info; 10396 bool NoteFailure; 10397 10398 public: 10399 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 10400 : Info(Info), NoteFailure(NoteFailure) {} 10401 ~DelayedNoteFailureRAII() { 10402 if (NoteFailure) { 10403 bool ContinueAfterFailure = Info.noteFailure(); 10404 (void)ContinueAfterFailure; 10405 assert(ContinueAfterFailure && 10406 "Shouldn't have kept evaluating on failure."); 10407 } 10408 } 10409 }; 10410 } 10411 10412 template <class SuccessCB, class AfterCB> 10413 static bool 10414 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 10415 SuccessCB &&Success, AfterCB &&DoAfter) { 10416 assert(E->isComparisonOp() && "expected comparison operator"); 10417 assert((E->getOpcode() == BO_Cmp || 10418 E->getType()->isIntegralOrEnumerationType()) && 10419 "unsupported binary expression evaluation"); 10420 auto Error = [&](const Expr *E) { 10421 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10422 return false; 10423 }; 10424 10425 using CCR = ComparisonCategoryResult; 10426 bool IsRelational = E->isRelationalOp(); 10427 bool IsEquality = E->isEqualityOp(); 10428 if (E->getOpcode() == BO_Cmp) { 10429 const ComparisonCategoryInfo &CmpInfo = 10430 Info.Ctx.CompCategories.getInfoForType(E->getType()); 10431 IsRelational = CmpInfo.isOrdered(); 10432 IsEquality = CmpInfo.isEquality(); 10433 } 10434 10435 QualType LHSTy = E->getLHS()->getType(); 10436 QualType RHSTy = E->getRHS()->getType(); 10437 10438 if (LHSTy->isIntegralOrEnumerationType() && 10439 RHSTy->isIntegralOrEnumerationType()) { 10440 APSInt LHS, RHS; 10441 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 10442 if (!LHSOK && !Info.noteFailure()) 10443 return false; 10444 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 10445 return false; 10446 if (LHS < RHS) 10447 return Success(CCR::Less, E); 10448 if (LHS > RHS) 10449 return Success(CCR::Greater, E); 10450 return Success(CCR::Equal, E); 10451 } 10452 10453 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 10454 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 10455 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 10456 10457 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 10458 if (!LHSOK && !Info.noteFailure()) 10459 return false; 10460 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 10461 return false; 10462 if (LHSFX < RHSFX) 10463 return Success(CCR::Less, E); 10464 if (LHSFX > RHSFX) 10465 return Success(CCR::Greater, E); 10466 return Success(CCR::Equal, E); 10467 } 10468 10469 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 10470 ComplexValue LHS, RHS; 10471 bool LHSOK; 10472 if (E->isAssignmentOp()) { 10473 LValue LV; 10474 EvaluateLValue(E->getLHS(), LV, Info); 10475 LHSOK = false; 10476 } else if (LHSTy->isRealFloatingType()) { 10477 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 10478 if (LHSOK) { 10479 LHS.makeComplexFloat(); 10480 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 10481 } 10482 } else { 10483 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 10484 } 10485 if (!LHSOK && !Info.noteFailure()) 10486 return false; 10487 10488 if (E->getRHS()->getType()->isRealFloatingType()) { 10489 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 10490 return false; 10491 RHS.makeComplexFloat(); 10492 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 10493 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 10494 return false; 10495 10496 if (LHS.isComplexFloat()) { 10497 APFloat::cmpResult CR_r = 10498 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 10499 APFloat::cmpResult CR_i = 10500 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 10501 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 10502 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 10503 } else { 10504 assert(IsEquality && "invalid complex comparison"); 10505 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 10506 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 10507 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 10508 } 10509 } 10510 10511 if (LHSTy->isRealFloatingType() && 10512 RHSTy->isRealFloatingType()) { 10513 APFloat RHS(0.0), LHS(0.0); 10514 10515 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 10516 if (!LHSOK && !Info.noteFailure()) 10517 return false; 10518 10519 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 10520 return false; 10521 10522 assert(E->isComparisonOp() && "Invalid binary operator!"); 10523 auto GetCmpRes = [&]() { 10524 switch (LHS.compare(RHS)) { 10525 case APFloat::cmpEqual: 10526 return CCR::Equal; 10527 case APFloat::cmpLessThan: 10528 return CCR::Less; 10529 case APFloat::cmpGreaterThan: 10530 return CCR::Greater; 10531 case APFloat::cmpUnordered: 10532 return CCR::Unordered; 10533 } 10534 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 10535 }; 10536 return Success(GetCmpRes(), E); 10537 } 10538 10539 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 10540 LValue LHSValue, RHSValue; 10541 10542 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 10543 if (!LHSOK && !Info.noteFailure()) 10544 return false; 10545 10546 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10547 return false; 10548 10549 // Reject differing bases from the normal codepath; we special-case 10550 // comparisons to null. 10551 if (!HasSameBase(LHSValue, RHSValue)) { 10552 // Inequalities and subtractions between unrelated pointers have 10553 // unspecified or undefined behavior. 10554 if (!IsEquality) 10555 return Error(E); 10556 // A constant address may compare equal to the address of a symbol. 10557 // The one exception is that address of an object cannot compare equal 10558 // to a null pointer constant. 10559 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 10560 (!RHSValue.Base && !RHSValue.Offset.isZero())) 10561 return Error(E); 10562 // It's implementation-defined whether distinct literals will have 10563 // distinct addresses. In clang, the result of such a comparison is 10564 // unspecified, so it is not a constant expression. However, we do know 10565 // that the address of a literal will be non-null. 10566 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 10567 LHSValue.Base && RHSValue.Base) 10568 return Error(E); 10569 // We can't tell whether weak symbols will end up pointing to the same 10570 // object. 10571 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 10572 return Error(E); 10573 // We can't compare the address of the start of one object with the 10574 // past-the-end address of another object, per C++ DR1652. 10575 if ((LHSValue.Base && LHSValue.Offset.isZero() && 10576 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 10577 (RHSValue.Base && RHSValue.Offset.isZero() && 10578 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 10579 return Error(E); 10580 // We can't tell whether an object is at the same address as another 10581 // zero sized object. 10582 if ((RHSValue.Base && isZeroSized(LHSValue)) || 10583 (LHSValue.Base && isZeroSized(RHSValue))) 10584 return Error(E); 10585 return Success(CCR::Nonequal, E); 10586 } 10587 10588 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 10589 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 10590 10591 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 10592 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 10593 10594 // C++11 [expr.rel]p3: 10595 // Pointers to void (after pointer conversions) can be compared, with a 10596 // result defined as follows: If both pointers represent the same 10597 // address or are both the null pointer value, the result is true if the 10598 // operator is <= or >= and false otherwise; otherwise the result is 10599 // unspecified. 10600 // We interpret this as applying to pointers to *cv* void. 10601 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 10602 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 10603 10604 // C++11 [expr.rel]p2: 10605 // - If two pointers point to non-static data members of the same object, 10606 // or to subobjects or array elements fo such members, recursively, the 10607 // pointer to the later declared member compares greater provided the 10608 // two members have the same access control and provided their class is 10609 // not a union. 10610 // [...] 10611 // - Otherwise pointer comparisons are unspecified. 10612 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 10613 bool WasArrayIndex; 10614 unsigned Mismatch = FindDesignatorMismatch( 10615 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 10616 // At the point where the designators diverge, the comparison has a 10617 // specified value if: 10618 // - we are comparing array indices 10619 // - we are comparing fields of a union, or fields with the same access 10620 // Otherwise, the result is unspecified and thus the comparison is not a 10621 // constant expression. 10622 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 10623 Mismatch < RHSDesignator.Entries.size()) { 10624 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 10625 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 10626 if (!LF && !RF) 10627 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 10628 else if (!LF) 10629 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 10630 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 10631 << RF->getParent() << RF; 10632 else if (!RF) 10633 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 10634 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 10635 << LF->getParent() << LF; 10636 else if (!LF->getParent()->isUnion() && 10637 LF->getAccess() != RF->getAccess()) 10638 Info.CCEDiag(E, 10639 diag::note_constexpr_pointer_comparison_differing_access) 10640 << LF << LF->getAccess() << RF << RF->getAccess() 10641 << LF->getParent(); 10642 } 10643 } 10644 10645 // The comparison here must be unsigned, and performed with the same 10646 // width as the pointer. 10647 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 10648 uint64_t CompareLHS = LHSOffset.getQuantity(); 10649 uint64_t CompareRHS = RHSOffset.getQuantity(); 10650 assert(PtrSize <= 64 && "Unexpected pointer width"); 10651 uint64_t Mask = ~0ULL >> (64 - PtrSize); 10652 CompareLHS &= Mask; 10653 CompareRHS &= Mask; 10654 10655 // If there is a base and this is a relational operator, we can only 10656 // compare pointers within the object in question; otherwise, the result 10657 // depends on where the object is located in memory. 10658 if (!LHSValue.Base.isNull() && IsRelational) { 10659 QualType BaseTy = getType(LHSValue.Base); 10660 if (BaseTy->isIncompleteType()) 10661 return Error(E); 10662 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 10663 uint64_t OffsetLimit = Size.getQuantity(); 10664 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 10665 return Error(E); 10666 } 10667 10668 if (CompareLHS < CompareRHS) 10669 return Success(CCR::Less, E); 10670 if (CompareLHS > CompareRHS) 10671 return Success(CCR::Greater, E); 10672 return Success(CCR::Equal, E); 10673 } 10674 10675 if (LHSTy->isMemberPointerType()) { 10676 assert(IsEquality && "unexpected member pointer operation"); 10677 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 10678 10679 MemberPtr LHSValue, RHSValue; 10680 10681 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 10682 if (!LHSOK && !Info.noteFailure()) 10683 return false; 10684 10685 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10686 return false; 10687 10688 // C++11 [expr.eq]p2: 10689 // If both operands are null, they compare equal. Otherwise if only one is 10690 // null, they compare unequal. 10691 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 10692 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 10693 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 10694 } 10695 10696 // Otherwise if either is a pointer to a virtual member function, the 10697 // result is unspecified. 10698 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 10699 if (MD->isVirtual()) 10700 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 10701 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 10702 if (MD->isVirtual()) 10703 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 10704 10705 // Otherwise they compare equal if and only if they would refer to the 10706 // same member of the same most derived object or the same subobject if 10707 // they were dereferenced with a hypothetical object of the associated 10708 // class type. 10709 bool Equal = LHSValue == RHSValue; 10710 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 10711 } 10712 10713 if (LHSTy->isNullPtrType()) { 10714 assert(E->isComparisonOp() && "unexpected nullptr operation"); 10715 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 10716 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 10717 // are compared, the result is true of the operator is <=, >= or ==, and 10718 // false otherwise. 10719 return Success(CCR::Equal, E); 10720 } 10721 10722 return DoAfter(); 10723 } 10724 10725 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 10726 if (!CheckLiteralType(Info, E)) 10727 return false; 10728 10729 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 10730 const BinaryOperator *E) { 10731 // Evaluation succeeded. Lookup the information for the comparison category 10732 // type and fetch the VarDecl for the result. 10733 const ComparisonCategoryInfo &CmpInfo = 10734 Info.Ctx.CompCategories.getInfoForType(E->getType()); 10735 const VarDecl *VD = 10736 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; 10737 // Check and evaluate the result as a constant expression. 10738 LValue LV; 10739 LV.set(VD); 10740 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 10741 return false; 10742 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 10743 }; 10744 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 10745 return ExprEvaluatorBaseTy::VisitBinCmp(E); 10746 }); 10747 } 10748 10749 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10750 // We don't call noteFailure immediately because the assignment happens after 10751 // we evaluate LHS and RHS. 10752 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 10753 return Error(E); 10754 10755 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 10756 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 10757 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 10758 10759 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 10760 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 10761 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 10762 10763 if (E->isComparisonOp()) { 10764 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way 10765 // comparisons and then translating the result. 10766 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 10767 const BinaryOperator *E) { 10768 using CCR = ComparisonCategoryResult; 10769 bool IsEqual = ResKind == CCR::Equal, 10770 IsLess = ResKind == CCR::Less, 10771 IsGreater = ResKind == CCR::Greater; 10772 auto Op = E->getOpcode(); 10773 switch (Op) { 10774 default: 10775 llvm_unreachable("unsupported binary operator"); 10776 case BO_EQ: 10777 case BO_NE: 10778 return Success(IsEqual == (Op == BO_EQ), E); 10779 case BO_LT: return Success(IsLess, E); 10780 case BO_GT: return Success(IsGreater, E); 10781 case BO_LE: return Success(IsEqual || IsLess, E); 10782 case BO_GE: return Success(IsEqual || IsGreater, E); 10783 } 10784 }; 10785 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 10786 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10787 }); 10788 } 10789 10790 QualType LHSTy = E->getLHS()->getType(); 10791 QualType RHSTy = E->getRHS()->getType(); 10792 10793 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 10794 E->getOpcode() == BO_Sub) { 10795 LValue LHSValue, RHSValue; 10796 10797 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 10798 if (!LHSOK && !Info.noteFailure()) 10799 return false; 10800 10801 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10802 return false; 10803 10804 // Reject differing bases from the normal codepath; we special-case 10805 // comparisons to null. 10806 if (!HasSameBase(LHSValue, RHSValue)) { 10807 // Handle &&A - &&B. 10808 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 10809 return Error(E); 10810 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 10811 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 10812 if (!LHSExpr || !RHSExpr) 10813 return Error(E); 10814 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 10815 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 10816 if (!LHSAddrExpr || !RHSAddrExpr) 10817 return Error(E); 10818 // Make sure both labels come from the same function. 10819 if (LHSAddrExpr->getLabel()->getDeclContext() != 10820 RHSAddrExpr->getLabel()->getDeclContext()) 10821 return Error(E); 10822 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 10823 } 10824 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 10825 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 10826 10827 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 10828 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 10829 10830 // C++11 [expr.add]p6: 10831 // Unless both pointers point to elements of the same array object, or 10832 // one past the last element of the array object, the behavior is 10833 // undefined. 10834 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 10835 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 10836 RHSDesignator)) 10837 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 10838 10839 QualType Type = E->getLHS()->getType(); 10840 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 10841 10842 CharUnits ElementSize; 10843 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 10844 return false; 10845 10846 // As an extension, a type may have zero size (empty struct or union in 10847 // C, array of zero length). Pointer subtraction in such cases has 10848 // undefined behavior, so is not constant. 10849 if (ElementSize.isZero()) { 10850 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 10851 << ElementType; 10852 return false; 10853 } 10854 10855 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 10856 // and produce incorrect results when it overflows. Such behavior 10857 // appears to be non-conforming, but is common, so perhaps we should 10858 // assume the standard intended for such cases to be undefined behavior 10859 // and check for them. 10860 10861 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 10862 // overflow in the final conversion to ptrdiff_t. 10863 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 10864 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 10865 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 10866 false); 10867 APSInt TrueResult = (LHS - RHS) / ElemSize; 10868 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 10869 10870 if (Result.extend(65) != TrueResult && 10871 !HandleOverflow(Info, E, TrueResult, E->getType())) 10872 return false; 10873 return Success(Result, E); 10874 } 10875 10876 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10877 } 10878 10879 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 10880 /// a result as the expression's type. 10881 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 10882 const UnaryExprOrTypeTraitExpr *E) { 10883 switch(E->getKind()) { 10884 case UETT_PreferredAlignOf: 10885 case UETT_AlignOf: { 10886 if (E->isArgumentType()) 10887 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 10888 E); 10889 else 10890 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 10891 E); 10892 } 10893 10894 case UETT_VecStep: { 10895 QualType Ty = E->getTypeOfArgument(); 10896 10897 if (Ty->isVectorType()) { 10898 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 10899 10900 // The vec_step built-in functions that take a 3-component 10901 // vector return 4. (OpenCL 1.1 spec 6.11.12) 10902 if (n == 3) 10903 n = 4; 10904 10905 return Success(n, E); 10906 } else 10907 return Success(1, E); 10908 } 10909 10910 case UETT_SizeOf: { 10911 QualType SrcTy = E->getTypeOfArgument(); 10912 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 10913 // the result is the size of the referenced type." 10914 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 10915 SrcTy = Ref->getPointeeType(); 10916 10917 CharUnits Sizeof; 10918 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 10919 return false; 10920 return Success(Sizeof, E); 10921 } 10922 case UETT_OpenMPRequiredSimdAlign: 10923 assert(E->isArgumentType()); 10924 return Success( 10925 Info.Ctx.toCharUnitsFromBits( 10926 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 10927 .getQuantity(), 10928 E); 10929 } 10930 10931 llvm_unreachable("unknown expr/type trait"); 10932 } 10933 10934 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 10935 CharUnits Result; 10936 unsigned n = OOE->getNumComponents(); 10937 if (n == 0) 10938 return Error(OOE); 10939 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 10940 for (unsigned i = 0; i != n; ++i) { 10941 OffsetOfNode ON = OOE->getComponent(i); 10942 switch (ON.getKind()) { 10943 case OffsetOfNode::Array: { 10944 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 10945 APSInt IdxResult; 10946 if (!EvaluateInteger(Idx, IdxResult, Info)) 10947 return false; 10948 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 10949 if (!AT) 10950 return Error(OOE); 10951 CurrentType = AT->getElementType(); 10952 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 10953 Result += IdxResult.getSExtValue() * ElementSize; 10954 break; 10955 } 10956 10957 case OffsetOfNode::Field: { 10958 FieldDecl *MemberDecl = ON.getField(); 10959 const RecordType *RT = CurrentType->getAs<RecordType>(); 10960 if (!RT) 10961 return Error(OOE); 10962 RecordDecl *RD = RT->getDecl(); 10963 if (RD->isInvalidDecl()) return false; 10964 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 10965 unsigned i = MemberDecl->getFieldIndex(); 10966 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 10967 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 10968 CurrentType = MemberDecl->getType().getNonReferenceType(); 10969 break; 10970 } 10971 10972 case OffsetOfNode::Identifier: 10973 llvm_unreachable("dependent __builtin_offsetof"); 10974 10975 case OffsetOfNode::Base: { 10976 CXXBaseSpecifier *BaseSpec = ON.getBase(); 10977 if (BaseSpec->isVirtual()) 10978 return Error(OOE); 10979 10980 // Find the layout of the class whose base we are looking into. 10981 const RecordType *RT = CurrentType->getAs<RecordType>(); 10982 if (!RT) 10983 return Error(OOE); 10984 RecordDecl *RD = RT->getDecl(); 10985 if (RD->isInvalidDecl()) return false; 10986 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 10987 10988 // Find the base class itself. 10989 CurrentType = BaseSpec->getType(); 10990 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 10991 if (!BaseRT) 10992 return Error(OOE); 10993 10994 // Add the offset to the base. 10995 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 10996 break; 10997 } 10998 } 10999 } 11000 return Success(Result, OOE); 11001 } 11002 11003 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 11004 switch (E->getOpcode()) { 11005 default: 11006 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 11007 // See C99 6.6p3. 11008 return Error(E); 11009 case UO_Extension: 11010 // FIXME: Should extension allow i-c-e extension expressions in its scope? 11011 // If so, we could clear the diagnostic ID. 11012 return Visit(E->getSubExpr()); 11013 case UO_Plus: 11014 // The result is just the value. 11015 return Visit(E->getSubExpr()); 11016 case UO_Minus: { 11017 if (!Visit(E->getSubExpr())) 11018 return false; 11019 if (!Result.isInt()) return Error(E); 11020 const APSInt &Value = Result.getInt(); 11021 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 11022 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 11023 E->getType())) 11024 return false; 11025 return Success(-Value, E); 11026 } 11027 case UO_Not: { 11028 if (!Visit(E->getSubExpr())) 11029 return false; 11030 if (!Result.isInt()) return Error(E); 11031 return Success(~Result.getInt(), E); 11032 } 11033 case UO_LNot: { 11034 bool bres; 11035 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 11036 return false; 11037 return Success(!bres, E); 11038 } 11039 } 11040 } 11041 11042 /// HandleCast - This is used to evaluate implicit or explicit casts where the 11043 /// result type is integer. 11044 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 11045 const Expr *SubExpr = E->getSubExpr(); 11046 QualType DestType = E->getType(); 11047 QualType SrcType = SubExpr->getType(); 11048 11049 switch (E->getCastKind()) { 11050 case CK_BaseToDerived: 11051 case CK_DerivedToBase: 11052 case CK_UncheckedDerivedToBase: 11053 case CK_Dynamic: 11054 case CK_ToUnion: 11055 case CK_ArrayToPointerDecay: 11056 case CK_FunctionToPointerDecay: 11057 case CK_NullToPointer: 11058 case CK_NullToMemberPointer: 11059 case CK_BaseToDerivedMemberPointer: 11060 case CK_DerivedToBaseMemberPointer: 11061 case CK_ReinterpretMemberPointer: 11062 case CK_ConstructorConversion: 11063 case CK_IntegralToPointer: 11064 case CK_ToVoid: 11065 case CK_VectorSplat: 11066 case CK_IntegralToFloating: 11067 case CK_FloatingCast: 11068 case CK_CPointerToObjCPointerCast: 11069 case CK_BlockPointerToObjCPointerCast: 11070 case CK_AnyPointerToBlockPointerCast: 11071 case CK_ObjCObjectLValueCast: 11072 case CK_FloatingRealToComplex: 11073 case CK_FloatingComplexToReal: 11074 case CK_FloatingComplexCast: 11075 case CK_FloatingComplexToIntegralComplex: 11076 case CK_IntegralRealToComplex: 11077 case CK_IntegralComplexCast: 11078 case CK_IntegralComplexToFloatingComplex: 11079 case CK_BuiltinFnToFnPtr: 11080 case CK_ZeroToOCLOpaqueType: 11081 case CK_NonAtomicToAtomic: 11082 case CK_AddressSpaceConversion: 11083 case CK_IntToOCLSampler: 11084 case CK_FixedPointCast: 11085 case CK_IntegralToFixedPoint: 11086 llvm_unreachable("invalid cast kind for integral value"); 11087 11088 case CK_BitCast: 11089 case CK_Dependent: 11090 case CK_LValueBitCast: 11091 case CK_ARCProduceObject: 11092 case CK_ARCConsumeObject: 11093 case CK_ARCReclaimReturnedObject: 11094 case CK_ARCExtendBlockObject: 11095 case CK_CopyAndAutoreleaseBlockObject: 11096 return Error(E); 11097 11098 case CK_UserDefinedConversion: 11099 case CK_LValueToRValue: 11100 case CK_AtomicToNonAtomic: 11101 case CK_NoOp: 11102 case CK_LValueToRValueBitCast: 11103 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11104 11105 case CK_MemberPointerToBoolean: 11106 case CK_PointerToBoolean: 11107 case CK_IntegralToBoolean: 11108 case CK_FloatingToBoolean: 11109 case CK_BooleanToSignedIntegral: 11110 case CK_FloatingComplexToBoolean: 11111 case CK_IntegralComplexToBoolean: { 11112 bool BoolResult; 11113 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 11114 return false; 11115 uint64_t IntResult = BoolResult; 11116 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 11117 IntResult = (uint64_t)-1; 11118 return Success(IntResult, E); 11119 } 11120 11121 case CK_FixedPointToIntegral: { 11122 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 11123 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 11124 return false; 11125 bool Overflowed; 11126 llvm::APSInt Result = Src.convertToInt( 11127 Info.Ctx.getIntWidth(DestType), 11128 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 11129 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 11130 return false; 11131 return Success(Result, E); 11132 } 11133 11134 case CK_FixedPointToBoolean: { 11135 // Unsigned padding does not affect this. 11136 APValue Val; 11137 if (!Evaluate(Val, Info, SubExpr)) 11138 return false; 11139 return Success(Val.getFixedPoint().getBoolValue(), E); 11140 } 11141 11142 case CK_IntegralCast: { 11143 if (!Visit(SubExpr)) 11144 return false; 11145 11146 if (!Result.isInt()) { 11147 // Allow casts of address-of-label differences if they are no-ops 11148 // or narrowing. (The narrowing case isn't actually guaranteed to 11149 // be constant-evaluatable except in some narrow cases which are hard 11150 // to detect here. We let it through on the assumption the user knows 11151 // what they are doing.) 11152 if (Result.isAddrLabelDiff()) 11153 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 11154 // Only allow casts of lvalues if they are lossless. 11155 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 11156 } 11157 11158 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 11159 Result.getInt()), E); 11160 } 11161 11162 case CK_PointerToIntegral: { 11163 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 11164 11165 LValue LV; 11166 if (!EvaluatePointer(SubExpr, LV, Info)) 11167 return false; 11168 11169 if (LV.getLValueBase()) { 11170 // Only allow based lvalue casts if they are lossless. 11171 // FIXME: Allow a larger integer size than the pointer size, and allow 11172 // narrowing back down to pointer width in subsequent integral casts. 11173 // FIXME: Check integer type's active bits, not its type size. 11174 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 11175 return Error(E); 11176 11177 LV.Designator.setInvalid(); 11178 LV.moveInto(Result); 11179 return true; 11180 } 11181 11182 APSInt AsInt; 11183 APValue V; 11184 LV.moveInto(V); 11185 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 11186 llvm_unreachable("Can't cast this!"); 11187 11188 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 11189 } 11190 11191 case CK_IntegralComplexToReal: { 11192 ComplexValue C; 11193 if (!EvaluateComplex(SubExpr, C, Info)) 11194 return false; 11195 return Success(C.getComplexIntReal(), E); 11196 } 11197 11198 case CK_FloatingToIntegral: { 11199 APFloat F(0.0); 11200 if (!EvaluateFloat(SubExpr, F, Info)) 11201 return false; 11202 11203 APSInt Value; 11204 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 11205 return false; 11206 return Success(Value, E); 11207 } 11208 } 11209 11210 llvm_unreachable("unknown cast resulting in integral value"); 11211 } 11212 11213 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 11214 if (E->getSubExpr()->getType()->isAnyComplexType()) { 11215 ComplexValue LV; 11216 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 11217 return false; 11218 if (!LV.isComplexInt()) 11219 return Error(E); 11220 return Success(LV.getComplexIntReal(), E); 11221 } 11222 11223 return Visit(E->getSubExpr()); 11224 } 11225 11226 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 11227 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 11228 ComplexValue LV; 11229 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 11230 return false; 11231 if (!LV.isComplexInt()) 11232 return Error(E); 11233 return Success(LV.getComplexIntImag(), E); 11234 } 11235 11236 VisitIgnoredValue(E->getSubExpr()); 11237 return Success(0, E); 11238 } 11239 11240 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 11241 return Success(E->getPackLength(), E); 11242 } 11243 11244 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 11245 return Success(E->getValue(), E); 11246 } 11247 11248 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 11249 switch (E->getOpcode()) { 11250 default: 11251 // Invalid unary operators 11252 return Error(E); 11253 case UO_Plus: 11254 // The result is just the value. 11255 return Visit(E->getSubExpr()); 11256 case UO_Minus: { 11257 if (!Visit(E->getSubExpr())) return false; 11258 if (!Result.isFixedPoint()) 11259 return Error(E); 11260 bool Overflowed; 11261 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 11262 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 11263 return false; 11264 return Success(Negated, E); 11265 } 11266 case UO_LNot: { 11267 bool bres; 11268 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 11269 return false; 11270 return Success(!bres, E); 11271 } 11272 } 11273 } 11274 11275 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 11276 const Expr *SubExpr = E->getSubExpr(); 11277 QualType DestType = E->getType(); 11278 assert(DestType->isFixedPointType() && 11279 "Expected destination type to be a fixed point type"); 11280 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 11281 11282 switch (E->getCastKind()) { 11283 case CK_FixedPointCast: { 11284 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 11285 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 11286 return false; 11287 bool Overflowed; 11288 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 11289 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 11290 return false; 11291 return Success(Result, E); 11292 } 11293 case CK_IntegralToFixedPoint: { 11294 APSInt Src; 11295 if (!EvaluateInteger(SubExpr, Src, Info)) 11296 return false; 11297 11298 bool Overflowed; 11299 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11300 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 11301 11302 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType)) 11303 return false; 11304 11305 return Success(IntResult, E); 11306 } 11307 case CK_NoOp: 11308 case CK_LValueToRValue: 11309 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11310 default: 11311 return Error(E); 11312 } 11313 } 11314 11315 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11316 const Expr *LHS = E->getLHS(); 11317 const Expr *RHS = E->getRHS(); 11318 FixedPointSemantics ResultFXSema = 11319 Info.Ctx.getFixedPointSemantics(E->getType()); 11320 11321 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 11322 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 11323 return false; 11324 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 11325 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 11326 return false; 11327 11328 switch (E->getOpcode()) { 11329 case BO_Add: { 11330 bool AddOverflow, ConversionOverflow; 11331 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow) 11332 .convert(ResultFXSema, &ConversionOverflow); 11333 if ((AddOverflow || ConversionOverflow) && 11334 !HandleOverflow(Info, E, Result, E->getType())) 11335 return false; 11336 return Success(Result, E); 11337 } 11338 default: 11339 return false; 11340 } 11341 llvm_unreachable("Should've exited before this"); 11342 } 11343 11344 //===----------------------------------------------------------------------===// 11345 // Float Evaluation 11346 //===----------------------------------------------------------------------===// 11347 11348 namespace { 11349 class FloatExprEvaluator 11350 : public ExprEvaluatorBase<FloatExprEvaluator> { 11351 APFloat &Result; 11352 public: 11353 FloatExprEvaluator(EvalInfo &info, APFloat &result) 11354 : ExprEvaluatorBaseTy(info), Result(result) {} 11355 11356 bool Success(const APValue &V, const Expr *e) { 11357 Result = V.getFloat(); 11358 return true; 11359 } 11360 11361 bool ZeroInitialization(const Expr *E) { 11362 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 11363 return true; 11364 } 11365 11366 bool VisitCallExpr(const CallExpr *E); 11367 11368 bool VisitUnaryOperator(const UnaryOperator *E); 11369 bool VisitBinaryOperator(const BinaryOperator *E); 11370 bool VisitFloatingLiteral(const FloatingLiteral *E); 11371 bool VisitCastExpr(const CastExpr *E); 11372 11373 bool VisitUnaryReal(const UnaryOperator *E); 11374 bool VisitUnaryImag(const UnaryOperator *E); 11375 11376 // FIXME: Missing: array subscript of vector, member of vector 11377 }; 11378 } // end anonymous namespace 11379 11380 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 11381 assert(E->isRValue() && E->getType()->isRealFloatingType()); 11382 return FloatExprEvaluator(Info, Result).Visit(E); 11383 } 11384 11385 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 11386 QualType ResultTy, 11387 const Expr *Arg, 11388 bool SNaN, 11389 llvm::APFloat &Result) { 11390 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 11391 if (!S) return false; 11392 11393 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 11394 11395 llvm::APInt fill; 11396 11397 // Treat empty strings as if they were zero. 11398 if (S->getString().empty()) 11399 fill = llvm::APInt(32, 0); 11400 else if (S->getString().getAsInteger(0, fill)) 11401 return false; 11402 11403 if (Context.getTargetInfo().isNan2008()) { 11404 if (SNaN) 11405 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 11406 else 11407 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 11408 } else { 11409 // Prior to IEEE 754-2008, architectures were allowed to choose whether 11410 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 11411 // a different encoding to what became a standard in 2008, and for pre- 11412 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 11413 // sNaN. This is now known as "legacy NaN" encoding. 11414 if (SNaN) 11415 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 11416 else 11417 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 11418 } 11419 11420 return true; 11421 } 11422 11423 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 11424 switch (E->getBuiltinCallee()) { 11425 default: 11426 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11427 11428 case Builtin::BI__builtin_huge_val: 11429 case Builtin::BI__builtin_huge_valf: 11430 case Builtin::BI__builtin_huge_vall: 11431 case Builtin::BI__builtin_huge_valf128: 11432 case Builtin::BI__builtin_inf: 11433 case Builtin::BI__builtin_inff: 11434 case Builtin::BI__builtin_infl: 11435 case Builtin::BI__builtin_inff128: { 11436 const llvm::fltSemantics &Sem = 11437 Info.Ctx.getFloatTypeSemantics(E->getType()); 11438 Result = llvm::APFloat::getInf(Sem); 11439 return true; 11440 } 11441 11442 case Builtin::BI__builtin_nans: 11443 case Builtin::BI__builtin_nansf: 11444 case Builtin::BI__builtin_nansl: 11445 case Builtin::BI__builtin_nansf128: 11446 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 11447 true, Result)) 11448 return Error(E); 11449 return true; 11450 11451 case Builtin::BI__builtin_nan: 11452 case Builtin::BI__builtin_nanf: 11453 case Builtin::BI__builtin_nanl: 11454 case Builtin::BI__builtin_nanf128: 11455 // If this is __builtin_nan() turn this into a nan, otherwise we 11456 // can't constant fold it. 11457 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 11458 false, Result)) 11459 return Error(E); 11460 return true; 11461 11462 case Builtin::BI__builtin_fabs: 11463 case Builtin::BI__builtin_fabsf: 11464 case Builtin::BI__builtin_fabsl: 11465 case Builtin::BI__builtin_fabsf128: 11466 if (!EvaluateFloat(E->getArg(0), Result, Info)) 11467 return false; 11468 11469 if (Result.isNegative()) 11470 Result.changeSign(); 11471 return true; 11472 11473 // FIXME: Builtin::BI__builtin_powi 11474 // FIXME: Builtin::BI__builtin_powif 11475 // FIXME: Builtin::BI__builtin_powil 11476 11477 case Builtin::BI__builtin_copysign: 11478 case Builtin::BI__builtin_copysignf: 11479 case Builtin::BI__builtin_copysignl: 11480 case Builtin::BI__builtin_copysignf128: { 11481 APFloat RHS(0.); 11482 if (!EvaluateFloat(E->getArg(0), Result, Info) || 11483 !EvaluateFloat(E->getArg(1), RHS, Info)) 11484 return false; 11485 Result.copySign(RHS); 11486 return true; 11487 } 11488 } 11489 } 11490 11491 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 11492 if (E->getSubExpr()->getType()->isAnyComplexType()) { 11493 ComplexValue CV; 11494 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 11495 return false; 11496 Result = CV.FloatReal; 11497 return true; 11498 } 11499 11500 return Visit(E->getSubExpr()); 11501 } 11502 11503 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 11504 if (E->getSubExpr()->getType()->isAnyComplexType()) { 11505 ComplexValue CV; 11506 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 11507 return false; 11508 Result = CV.FloatImag; 11509 return true; 11510 } 11511 11512 VisitIgnoredValue(E->getSubExpr()); 11513 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 11514 Result = llvm::APFloat::getZero(Sem); 11515 return true; 11516 } 11517 11518 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 11519 switch (E->getOpcode()) { 11520 default: return Error(E); 11521 case UO_Plus: 11522 return EvaluateFloat(E->getSubExpr(), Result, Info); 11523 case UO_Minus: 11524 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 11525 return false; 11526 Result.changeSign(); 11527 return true; 11528 } 11529 } 11530 11531 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11532 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 11533 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11534 11535 APFloat RHS(0.0); 11536 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 11537 if (!LHSOK && !Info.noteFailure()) 11538 return false; 11539 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 11540 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 11541 } 11542 11543 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 11544 Result = E->getValue(); 11545 return true; 11546 } 11547 11548 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 11549 const Expr* SubExpr = E->getSubExpr(); 11550 11551 switch (E->getCastKind()) { 11552 default: 11553 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11554 11555 case CK_IntegralToFloating: { 11556 APSInt IntResult; 11557 return EvaluateInteger(SubExpr, IntResult, Info) && 11558 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 11559 E->getType(), Result); 11560 } 11561 11562 case CK_FloatingCast: { 11563 if (!Visit(SubExpr)) 11564 return false; 11565 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 11566 Result); 11567 } 11568 11569 case CK_FloatingComplexToReal: { 11570 ComplexValue V; 11571 if (!EvaluateComplex(SubExpr, V, Info)) 11572 return false; 11573 Result = V.getComplexFloatReal(); 11574 return true; 11575 } 11576 } 11577 } 11578 11579 //===----------------------------------------------------------------------===// 11580 // Complex Evaluation (for float and integer) 11581 //===----------------------------------------------------------------------===// 11582 11583 namespace { 11584 class ComplexExprEvaluator 11585 : public ExprEvaluatorBase<ComplexExprEvaluator> { 11586 ComplexValue &Result; 11587 11588 public: 11589 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 11590 : ExprEvaluatorBaseTy(info), Result(Result) {} 11591 11592 bool Success(const APValue &V, const Expr *e) { 11593 Result.setFrom(V); 11594 return true; 11595 } 11596 11597 bool ZeroInitialization(const Expr *E); 11598 11599 //===--------------------------------------------------------------------===// 11600 // Visitor Methods 11601 //===--------------------------------------------------------------------===// 11602 11603 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 11604 bool VisitCastExpr(const CastExpr *E); 11605 bool VisitBinaryOperator(const BinaryOperator *E); 11606 bool VisitUnaryOperator(const UnaryOperator *E); 11607 bool VisitInitListExpr(const InitListExpr *E); 11608 }; 11609 } // end anonymous namespace 11610 11611 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 11612 EvalInfo &Info) { 11613 assert(E->isRValue() && E->getType()->isAnyComplexType()); 11614 return ComplexExprEvaluator(Info, Result).Visit(E); 11615 } 11616 11617 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 11618 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 11619 if (ElemTy->isRealFloatingType()) { 11620 Result.makeComplexFloat(); 11621 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 11622 Result.FloatReal = Zero; 11623 Result.FloatImag = Zero; 11624 } else { 11625 Result.makeComplexInt(); 11626 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 11627 Result.IntReal = Zero; 11628 Result.IntImag = Zero; 11629 } 11630 return true; 11631 } 11632 11633 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 11634 const Expr* SubExpr = E->getSubExpr(); 11635 11636 if (SubExpr->getType()->isRealFloatingType()) { 11637 Result.makeComplexFloat(); 11638 APFloat &Imag = Result.FloatImag; 11639 if (!EvaluateFloat(SubExpr, Imag, Info)) 11640 return false; 11641 11642 Result.FloatReal = APFloat(Imag.getSemantics()); 11643 return true; 11644 } else { 11645 assert(SubExpr->getType()->isIntegerType() && 11646 "Unexpected imaginary literal."); 11647 11648 Result.makeComplexInt(); 11649 APSInt &Imag = Result.IntImag; 11650 if (!EvaluateInteger(SubExpr, Imag, Info)) 11651 return false; 11652 11653 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 11654 return true; 11655 } 11656 } 11657 11658 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 11659 11660 switch (E->getCastKind()) { 11661 case CK_BitCast: 11662 case CK_BaseToDerived: 11663 case CK_DerivedToBase: 11664 case CK_UncheckedDerivedToBase: 11665 case CK_Dynamic: 11666 case CK_ToUnion: 11667 case CK_ArrayToPointerDecay: 11668 case CK_FunctionToPointerDecay: 11669 case CK_NullToPointer: 11670 case CK_NullToMemberPointer: 11671 case CK_BaseToDerivedMemberPointer: 11672 case CK_DerivedToBaseMemberPointer: 11673 case CK_MemberPointerToBoolean: 11674 case CK_ReinterpretMemberPointer: 11675 case CK_ConstructorConversion: 11676 case CK_IntegralToPointer: 11677 case CK_PointerToIntegral: 11678 case CK_PointerToBoolean: 11679 case CK_ToVoid: 11680 case CK_VectorSplat: 11681 case CK_IntegralCast: 11682 case CK_BooleanToSignedIntegral: 11683 case CK_IntegralToBoolean: 11684 case CK_IntegralToFloating: 11685 case CK_FloatingToIntegral: 11686 case CK_FloatingToBoolean: 11687 case CK_FloatingCast: 11688 case CK_CPointerToObjCPointerCast: 11689 case CK_BlockPointerToObjCPointerCast: 11690 case CK_AnyPointerToBlockPointerCast: 11691 case CK_ObjCObjectLValueCast: 11692 case CK_FloatingComplexToReal: 11693 case CK_FloatingComplexToBoolean: 11694 case CK_IntegralComplexToReal: 11695 case CK_IntegralComplexToBoolean: 11696 case CK_ARCProduceObject: 11697 case CK_ARCConsumeObject: 11698 case CK_ARCReclaimReturnedObject: 11699 case CK_ARCExtendBlockObject: 11700 case CK_CopyAndAutoreleaseBlockObject: 11701 case CK_BuiltinFnToFnPtr: 11702 case CK_ZeroToOCLOpaqueType: 11703 case CK_NonAtomicToAtomic: 11704 case CK_AddressSpaceConversion: 11705 case CK_IntToOCLSampler: 11706 case CK_FixedPointCast: 11707 case CK_FixedPointToBoolean: 11708 case CK_FixedPointToIntegral: 11709 case CK_IntegralToFixedPoint: 11710 llvm_unreachable("invalid cast kind for complex value"); 11711 11712 case CK_LValueToRValue: 11713 case CK_AtomicToNonAtomic: 11714 case CK_NoOp: 11715 case CK_LValueToRValueBitCast: 11716 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11717 11718 case CK_Dependent: 11719 case CK_LValueBitCast: 11720 case CK_UserDefinedConversion: 11721 return Error(E); 11722 11723 case CK_FloatingRealToComplex: { 11724 APFloat &Real = Result.FloatReal; 11725 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 11726 return false; 11727 11728 Result.makeComplexFloat(); 11729 Result.FloatImag = APFloat(Real.getSemantics()); 11730 return true; 11731 } 11732 11733 case CK_FloatingComplexCast: { 11734 if (!Visit(E->getSubExpr())) 11735 return false; 11736 11737 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11738 QualType From 11739 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11740 11741 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 11742 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 11743 } 11744 11745 case CK_FloatingComplexToIntegralComplex: { 11746 if (!Visit(E->getSubExpr())) 11747 return false; 11748 11749 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11750 QualType From 11751 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11752 Result.makeComplexInt(); 11753 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 11754 To, Result.IntReal) && 11755 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 11756 To, Result.IntImag); 11757 } 11758 11759 case CK_IntegralRealToComplex: { 11760 APSInt &Real = Result.IntReal; 11761 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 11762 return false; 11763 11764 Result.makeComplexInt(); 11765 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 11766 return true; 11767 } 11768 11769 case CK_IntegralComplexCast: { 11770 if (!Visit(E->getSubExpr())) 11771 return false; 11772 11773 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11774 QualType From 11775 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11776 11777 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 11778 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 11779 return true; 11780 } 11781 11782 case CK_IntegralComplexToFloatingComplex: { 11783 if (!Visit(E->getSubExpr())) 11784 return false; 11785 11786 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 11787 QualType From 11788 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 11789 Result.makeComplexFloat(); 11790 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 11791 To, Result.FloatReal) && 11792 HandleIntToFloatCast(Info, E, From, Result.IntImag, 11793 To, Result.FloatImag); 11794 } 11795 } 11796 11797 llvm_unreachable("unknown cast resulting in complex value"); 11798 } 11799 11800 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11801 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 11802 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11803 11804 // Track whether the LHS or RHS is real at the type system level. When this is 11805 // the case we can simplify our evaluation strategy. 11806 bool LHSReal = false, RHSReal = false; 11807 11808 bool LHSOK; 11809 if (E->getLHS()->getType()->isRealFloatingType()) { 11810 LHSReal = true; 11811 APFloat &Real = Result.FloatReal; 11812 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 11813 if (LHSOK) { 11814 Result.makeComplexFloat(); 11815 Result.FloatImag = APFloat(Real.getSemantics()); 11816 } 11817 } else { 11818 LHSOK = Visit(E->getLHS()); 11819 } 11820 if (!LHSOK && !Info.noteFailure()) 11821 return false; 11822 11823 ComplexValue RHS; 11824 if (E->getRHS()->getType()->isRealFloatingType()) { 11825 RHSReal = true; 11826 APFloat &Real = RHS.FloatReal; 11827 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 11828 return false; 11829 RHS.makeComplexFloat(); 11830 RHS.FloatImag = APFloat(Real.getSemantics()); 11831 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 11832 return false; 11833 11834 assert(!(LHSReal && RHSReal) && 11835 "Cannot have both operands of a complex operation be real."); 11836 switch (E->getOpcode()) { 11837 default: return Error(E); 11838 case BO_Add: 11839 if (Result.isComplexFloat()) { 11840 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 11841 APFloat::rmNearestTiesToEven); 11842 if (LHSReal) 11843 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 11844 else if (!RHSReal) 11845 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 11846 APFloat::rmNearestTiesToEven); 11847 } else { 11848 Result.getComplexIntReal() += RHS.getComplexIntReal(); 11849 Result.getComplexIntImag() += RHS.getComplexIntImag(); 11850 } 11851 break; 11852 case BO_Sub: 11853 if (Result.isComplexFloat()) { 11854 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 11855 APFloat::rmNearestTiesToEven); 11856 if (LHSReal) { 11857 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 11858 Result.getComplexFloatImag().changeSign(); 11859 } else if (!RHSReal) { 11860 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 11861 APFloat::rmNearestTiesToEven); 11862 } 11863 } else { 11864 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 11865 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 11866 } 11867 break; 11868 case BO_Mul: 11869 if (Result.isComplexFloat()) { 11870 // This is an implementation of complex multiplication according to the 11871 // constraints laid out in C11 Annex G. The implementation uses the 11872 // following naming scheme: 11873 // (a + ib) * (c + id) 11874 ComplexValue LHS = Result; 11875 APFloat &A = LHS.getComplexFloatReal(); 11876 APFloat &B = LHS.getComplexFloatImag(); 11877 APFloat &C = RHS.getComplexFloatReal(); 11878 APFloat &D = RHS.getComplexFloatImag(); 11879 APFloat &ResR = Result.getComplexFloatReal(); 11880 APFloat &ResI = Result.getComplexFloatImag(); 11881 if (LHSReal) { 11882 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 11883 ResR = A * C; 11884 ResI = A * D; 11885 } else if (RHSReal) { 11886 ResR = C * A; 11887 ResI = C * B; 11888 } else { 11889 // In the fully general case, we need to handle NaNs and infinities 11890 // robustly. 11891 APFloat AC = A * C; 11892 APFloat BD = B * D; 11893 APFloat AD = A * D; 11894 APFloat BC = B * C; 11895 ResR = AC - BD; 11896 ResI = AD + BC; 11897 if (ResR.isNaN() && ResI.isNaN()) { 11898 bool Recalc = false; 11899 if (A.isInfinity() || B.isInfinity()) { 11900 A = APFloat::copySign( 11901 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 11902 B = APFloat::copySign( 11903 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 11904 if (C.isNaN()) 11905 C = APFloat::copySign(APFloat(C.getSemantics()), C); 11906 if (D.isNaN()) 11907 D = APFloat::copySign(APFloat(D.getSemantics()), D); 11908 Recalc = true; 11909 } 11910 if (C.isInfinity() || D.isInfinity()) { 11911 C = APFloat::copySign( 11912 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 11913 D = APFloat::copySign( 11914 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 11915 if (A.isNaN()) 11916 A = APFloat::copySign(APFloat(A.getSemantics()), A); 11917 if (B.isNaN()) 11918 B = APFloat::copySign(APFloat(B.getSemantics()), B); 11919 Recalc = true; 11920 } 11921 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 11922 AD.isInfinity() || BC.isInfinity())) { 11923 if (A.isNaN()) 11924 A = APFloat::copySign(APFloat(A.getSemantics()), A); 11925 if (B.isNaN()) 11926 B = APFloat::copySign(APFloat(B.getSemantics()), B); 11927 if (C.isNaN()) 11928 C = APFloat::copySign(APFloat(C.getSemantics()), C); 11929 if (D.isNaN()) 11930 D = APFloat::copySign(APFloat(D.getSemantics()), D); 11931 Recalc = true; 11932 } 11933 if (Recalc) { 11934 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 11935 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 11936 } 11937 } 11938 } 11939 } else { 11940 ComplexValue LHS = Result; 11941 Result.getComplexIntReal() = 11942 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 11943 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 11944 Result.getComplexIntImag() = 11945 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 11946 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 11947 } 11948 break; 11949 case BO_Div: 11950 if (Result.isComplexFloat()) { 11951 // This is an implementation of complex division according to the 11952 // constraints laid out in C11 Annex G. The implementation uses the 11953 // following naming scheme: 11954 // (a + ib) / (c + id) 11955 ComplexValue LHS = Result; 11956 APFloat &A = LHS.getComplexFloatReal(); 11957 APFloat &B = LHS.getComplexFloatImag(); 11958 APFloat &C = RHS.getComplexFloatReal(); 11959 APFloat &D = RHS.getComplexFloatImag(); 11960 APFloat &ResR = Result.getComplexFloatReal(); 11961 APFloat &ResI = Result.getComplexFloatImag(); 11962 if (RHSReal) { 11963 ResR = A / C; 11964 ResI = B / C; 11965 } else { 11966 if (LHSReal) { 11967 // No real optimizations we can do here, stub out with zero. 11968 B = APFloat::getZero(A.getSemantics()); 11969 } 11970 int DenomLogB = 0; 11971 APFloat MaxCD = maxnum(abs(C), abs(D)); 11972 if (MaxCD.isFinite()) { 11973 DenomLogB = ilogb(MaxCD); 11974 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 11975 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 11976 } 11977 APFloat Denom = C * C + D * D; 11978 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 11979 APFloat::rmNearestTiesToEven); 11980 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 11981 APFloat::rmNearestTiesToEven); 11982 if (ResR.isNaN() && ResI.isNaN()) { 11983 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 11984 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 11985 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 11986 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 11987 D.isFinite()) { 11988 A = APFloat::copySign( 11989 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 11990 B = APFloat::copySign( 11991 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 11992 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 11993 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 11994 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 11995 C = APFloat::copySign( 11996 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 11997 D = APFloat::copySign( 11998 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 11999 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 12000 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 12001 } 12002 } 12003 } 12004 } else { 12005 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 12006 return Error(E, diag::note_expr_divide_by_zero); 12007 12008 ComplexValue LHS = Result; 12009 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 12010 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 12011 Result.getComplexIntReal() = 12012 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 12013 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 12014 Result.getComplexIntImag() = 12015 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 12016 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 12017 } 12018 break; 12019 } 12020 12021 return true; 12022 } 12023 12024 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12025 // Get the operand value into 'Result'. 12026 if (!Visit(E->getSubExpr())) 12027 return false; 12028 12029 switch (E->getOpcode()) { 12030 default: 12031 return Error(E); 12032 case UO_Extension: 12033 return true; 12034 case UO_Plus: 12035 // The result is always just the subexpr. 12036 return true; 12037 case UO_Minus: 12038 if (Result.isComplexFloat()) { 12039 Result.getComplexFloatReal().changeSign(); 12040 Result.getComplexFloatImag().changeSign(); 12041 } 12042 else { 12043 Result.getComplexIntReal() = -Result.getComplexIntReal(); 12044 Result.getComplexIntImag() = -Result.getComplexIntImag(); 12045 } 12046 return true; 12047 case UO_Not: 12048 if (Result.isComplexFloat()) 12049 Result.getComplexFloatImag().changeSign(); 12050 else 12051 Result.getComplexIntImag() = -Result.getComplexIntImag(); 12052 return true; 12053 } 12054 } 12055 12056 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 12057 if (E->getNumInits() == 2) { 12058 if (E->getType()->isComplexType()) { 12059 Result.makeComplexFloat(); 12060 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 12061 return false; 12062 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 12063 return false; 12064 } else { 12065 Result.makeComplexInt(); 12066 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 12067 return false; 12068 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 12069 return false; 12070 } 12071 return true; 12072 } 12073 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 12074 } 12075 12076 //===----------------------------------------------------------------------===// 12077 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 12078 // implicit conversion. 12079 //===----------------------------------------------------------------------===// 12080 12081 namespace { 12082 class AtomicExprEvaluator : 12083 public ExprEvaluatorBase<AtomicExprEvaluator> { 12084 const LValue *This; 12085 APValue &Result; 12086 public: 12087 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 12088 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 12089 12090 bool Success(const APValue &V, const Expr *E) { 12091 Result = V; 12092 return true; 12093 } 12094 12095 bool ZeroInitialization(const Expr *E) { 12096 ImplicitValueInitExpr VIE( 12097 E->getType()->castAs<AtomicType>()->getValueType()); 12098 // For atomic-qualified class (and array) types in C++, initialize the 12099 // _Atomic-wrapped subobject directly, in-place. 12100 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 12101 : Evaluate(Result, Info, &VIE); 12102 } 12103 12104 bool VisitCastExpr(const CastExpr *E) { 12105 switch (E->getCastKind()) { 12106 default: 12107 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12108 case CK_NonAtomicToAtomic: 12109 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 12110 : Evaluate(Result, Info, E->getSubExpr()); 12111 } 12112 } 12113 }; 12114 } // end anonymous namespace 12115 12116 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 12117 EvalInfo &Info) { 12118 assert(E->isRValue() && E->getType()->isAtomicType()); 12119 return AtomicExprEvaluator(Info, This, Result).Visit(E); 12120 } 12121 12122 //===----------------------------------------------------------------------===// 12123 // Void expression evaluation, primarily for a cast to void on the LHS of a 12124 // comma operator 12125 //===----------------------------------------------------------------------===// 12126 12127 namespace { 12128 class VoidExprEvaluator 12129 : public ExprEvaluatorBase<VoidExprEvaluator> { 12130 public: 12131 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 12132 12133 bool Success(const APValue &V, const Expr *e) { return true; } 12134 12135 bool ZeroInitialization(const Expr *E) { return true; } 12136 12137 bool VisitCastExpr(const CastExpr *E) { 12138 switch (E->getCastKind()) { 12139 default: 12140 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12141 case CK_ToVoid: 12142 VisitIgnoredValue(E->getSubExpr()); 12143 return true; 12144 } 12145 } 12146 12147 bool VisitCallExpr(const CallExpr *E) { 12148 switch (E->getBuiltinCallee()) { 12149 default: 12150 return ExprEvaluatorBaseTy::VisitCallExpr(E); 12151 case Builtin::BI__assume: 12152 case Builtin::BI__builtin_assume: 12153 // The argument is not evaluated! 12154 return true; 12155 } 12156 } 12157 }; 12158 } // end anonymous namespace 12159 12160 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 12161 assert(E->isRValue() && E->getType()->isVoidType()); 12162 return VoidExprEvaluator(Info).Visit(E); 12163 } 12164 12165 //===----------------------------------------------------------------------===// 12166 // Top level Expr::EvaluateAsRValue method. 12167 //===----------------------------------------------------------------------===// 12168 12169 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 12170 // In C, function designators are not lvalues, but we evaluate them as if they 12171 // are. 12172 QualType T = E->getType(); 12173 if (E->isGLValue() || T->isFunctionType()) { 12174 LValue LV; 12175 if (!EvaluateLValue(E, LV, Info)) 12176 return false; 12177 LV.moveInto(Result); 12178 } else if (T->isVectorType()) { 12179 if (!EvaluateVector(E, Result, Info)) 12180 return false; 12181 } else if (T->isIntegralOrEnumerationType()) { 12182 if (!IntExprEvaluator(Info, Result).Visit(E)) 12183 return false; 12184 } else if (T->hasPointerRepresentation()) { 12185 LValue LV; 12186 if (!EvaluatePointer(E, LV, Info)) 12187 return false; 12188 LV.moveInto(Result); 12189 } else if (T->isRealFloatingType()) { 12190 llvm::APFloat F(0.0); 12191 if (!EvaluateFloat(E, F, Info)) 12192 return false; 12193 Result = APValue(F); 12194 } else if (T->isAnyComplexType()) { 12195 ComplexValue C; 12196 if (!EvaluateComplex(E, C, Info)) 12197 return false; 12198 C.moveInto(Result); 12199 } else if (T->isFixedPointType()) { 12200 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 12201 } else if (T->isMemberPointerType()) { 12202 MemberPtr P; 12203 if (!EvaluateMemberPointer(E, P, Info)) 12204 return false; 12205 P.moveInto(Result); 12206 return true; 12207 } else if (T->isArrayType()) { 12208 LValue LV; 12209 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 12210 if (!EvaluateArray(E, LV, Value, Info)) 12211 return false; 12212 Result = Value; 12213 } else if (T->isRecordType()) { 12214 LValue LV; 12215 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 12216 if (!EvaluateRecord(E, LV, Value, Info)) 12217 return false; 12218 Result = Value; 12219 } else if (T->isVoidType()) { 12220 if (!Info.getLangOpts().CPlusPlus11) 12221 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 12222 << E->getType(); 12223 if (!EvaluateVoid(E, Info)) 12224 return false; 12225 } else if (T->isAtomicType()) { 12226 QualType Unqual = T.getAtomicUnqualifiedType(); 12227 if (Unqual->isArrayType() || Unqual->isRecordType()) { 12228 LValue LV; 12229 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 12230 if (!EvaluateAtomic(E, &LV, Value, Info)) 12231 return false; 12232 } else { 12233 if (!EvaluateAtomic(E, nullptr, Result, Info)) 12234 return false; 12235 } 12236 } else if (Info.getLangOpts().CPlusPlus11) { 12237 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 12238 return false; 12239 } else { 12240 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 12241 return false; 12242 } 12243 12244 return true; 12245 } 12246 12247 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 12248 /// cases, the in-place evaluation is essential, since later initializers for 12249 /// an object can indirectly refer to subobjects which were initialized earlier. 12250 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 12251 const Expr *E, bool AllowNonLiteralTypes) { 12252 assert(!E->isValueDependent()); 12253 12254 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 12255 return false; 12256 12257 if (E->isRValue()) { 12258 // Evaluate arrays and record types in-place, so that later initializers can 12259 // refer to earlier-initialized members of the object. 12260 QualType T = E->getType(); 12261 if (T->isArrayType()) 12262 return EvaluateArray(E, This, Result, Info); 12263 else if (T->isRecordType()) 12264 return EvaluateRecord(E, This, Result, Info); 12265 else if (T->isAtomicType()) { 12266 QualType Unqual = T.getAtomicUnqualifiedType(); 12267 if (Unqual->isArrayType() || Unqual->isRecordType()) 12268 return EvaluateAtomic(E, &This, Result, Info); 12269 } 12270 } 12271 12272 // For any other type, in-place evaluation is unimportant. 12273 return Evaluate(Result, Info, E); 12274 } 12275 12276 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 12277 /// lvalue-to-rvalue cast if it is an lvalue. 12278 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 12279 if (E->getType().isNull()) 12280 return false; 12281 12282 if (!CheckLiteralType(Info, E)) 12283 return false; 12284 12285 if (!::Evaluate(Result, Info, E)) 12286 return false; 12287 12288 if (E->isGLValue()) { 12289 LValue LV; 12290 LV.setFrom(Info.Ctx, Result); 12291 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 12292 return false; 12293 } 12294 12295 // Check this core constant expression is a constant expression. 12296 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 12297 } 12298 12299 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 12300 const ASTContext &Ctx, bool &IsConst) { 12301 // Fast-path evaluations of integer literals, since we sometimes see files 12302 // containing vast quantities of these. 12303 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 12304 Result.Val = APValue(APSInt(L->getValue(), 12305 L->getType()->isUnsignedIntegerType())); 12306 IsConst = true; 12307 return true; 12308 } 12309 12310 // This case should be rare, but we need to check it before we check on 12311 // the type below. 12312 if (Exp->getType().isNull()) { 12313 IsConst = false; 12314 return true; 12315 } 12316 12317 // FIXME: Evaluating values of large array and record types can cause 12318 // performance problems. Only do so in C++11 for now. 12319 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 12320 Exp->getType()->isRecordType()) && 12321 !Ctx.getLangOpts().CPlusPlus11) { 12322 IsConst = false; 12323 return true; 12324 } 12325 return false; 12326 } 12327 12328 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 12329 Expr::SideEffectsKind SEK) { 12330 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 12331 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 12332 } 12333 12334 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 12335 const ASTContext &Ctx, EvalInfo &Info) { 12336 bool IsConst; 12337 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 12338 return IsConst; 12339 12340 return EvaluateAsRValue(Info, E, Result.Val); 12341 } 12342 12343 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 12344 const ASTContext &Ctx, 12345 Expr::SideEffectsKind AllowSideEffects, 12346 EvalInfo &Info) { 12347 if (!E->getType()->isIntegralOrEnumerationType()) 12348 return false; 12349 12350 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 12351 !ExprResult.Val.isInt() || 12352 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 12353 return false; 12354 12355 return true; 12356 } 12357 12358 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 12359 const ASTContext &Ctx, 12360 Expr::SideEffectsKind AllowSideEffects, 12361 EvalInfo &Info) { 12362 if (!E->getType()->isFixedPointType()) 12363 return false; 12364 12365 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 12366 return false; 12367 12368 if (!ExprResult.Val.isFixedPoint() || 12369 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 12370 return false; 12371 12372 return true; 12373 } 12374 12375 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 12376 /// any crazy technique (that has nothing to do with language standards) that 12377 /// we want to. If this function returns true, it returns the folded constant 12378 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 12379 /// will be applied to the result. 12380 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 12381 bool InConstantContext) const { 12382 assert(!isValueDependent() && 12383 "Expression evaluator can't be called on a dependent expression."); 12384 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 12385 Info.InConstantContext = InConstantContext; 12386 return ::EvaluateAsRValue(this, Result, Ctx, Info); 12387 } 12388 12389 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 12390 bool InConstantContext) const { 12391 assert(!isValueDependent() && 12392 "Expression evaluator can't be called on a dependent expression."); 12393 EvalResult Scratch; 12394 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 12395 HandleConversionToBool(Scratch.Val, Result); 12396 } 12397 12398 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 12399 SideEffectsKind AllowSideEffects, 12400 bool InConstantContext) const { 12401 assert(!isValueDependent() && 12402 "Expression evaluator can't be called on a dependent expression."); 12403 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 12404 Info.InConstantContext = InConstantContext; 12405 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 12406 } 12407 12408 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 12409 SideEffectsKind AllowSideEffects, 12410 bool InConstantContext) const { 12411 assert(!isValueDependent() && 12412 "Expression evaluator can't be called on a dependent expression."); 12413 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 12414 Info.InConstantContext = InConstantContext; 12415 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 12416 } 12417 12418 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 12419 SideEffectsKind AllowSideEffects, 12420 bool InConstantContext) const { 12421 assert(!isValueDependent() && 12422 "Expression evaluator can't be called on a dependent expression."); 12423 12424 if (!getType()->isRealFloatingType()) 12425 return false; 12426 12427 EvalResult ExprResult; 12428 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 12429 !ExprResult.Val.isFloat() || 12430 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 12431 return false; 12432 12433 Result = ExprResult.Val.getFloat(); 12434 return true; 12435 } 12436 12437 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 12438 bool InConstantContext) const { 12439 assert(!isValueDependent() && 12440 "Expression evaluator can't be called on a dependent expression."); 12441 12442 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 12443 Info.InConstantContext = InConstantContext; 12444 LValue LV; 12445 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 12446 !CheckLValueConstantExpression(Info, getExprLoc(), 12447 Ctx.getLValueReferenceType(getType()), LV, 12448 Expr::EvaluateForCodeGen)) 12449 return false; 12450 12451 LV.moveInto(Result.Val); 12452 return true; 12453 } 12454 12455 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 12456 const ASTContext &Ctx) const { 12457 assert(!isValueDependent() && 12458 "Expression evaluator can't be called on a dependent expression."); 12459 12460 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 12461 EvalInfo Info(Ctx, Result, EM); 12462 Info.InConstantContext = true; 12463 12464 if (!::Evaluate(Result.Val, Info, this)) 12465 return false; 12466 12467 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val, 12468 Usage); 12469 } 12470 12471 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 12472 const VarDecl *VD, 12473 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 12474 assert(!isValueDependent() && 12475 "Expression evaluator can't be called on a dependent expression."); 12476 12477 // FIXME: Evaluating initializers for large array and record types can cause 12478 // performance problems. Only do so in C++11 for now. 12479 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 12480 !Ctx.getLangOpts().CPlusPlus11) 12481 return false; 12482 12483 Expr::EvalStatus EStatus; 12484 EStatus.Diag = &Notes; 12485 12486 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr() 12487 ? EvalInfo::EM_ConstantExpression 12488 : EvalInfo::EM_ConstantFold); 12489 InitInfo.setEvaluatingDecl(VD, Value); 12490 InitInfo.InConstantContext = true; 12491 12492 LValue LVal; 12493 LVal.set(VD); 12494 12495 // C++11 [basic.start.init]p2: 12496 // Variables with static storage duration or thread storage duration shall be 12497 // zero-initialized before any other initialization takes place. 12498 // This behavior is not present in C. 12499 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 12500 !VD->getType()->isReferenceType()) { 12501 ImplicitValueInitExpr VIE(VD->getType()); 12502 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, 12503 /*AllowNonLiteralTypes=*/true)) 12504 return false; 12505 } 12506 12507 if (!EvaluateInPlace(Value, InitInfo, LVal, this, 12508 /*AllowNonLiteralTypes=*/true) || 12509 EStatus.HasSideEffects) 12510 return false; 12511 12512 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 12513 Value); 12514 } 12515 12516 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 12517 /// constant folded, but discard the result. 12518 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 12519 assert(!isValueDependent() && 12520 "Expression evaluator can't be called on a dependent expression."); 12521 12522 EvalResult Result; 12523 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 12524 !hasUnacceptableSideEffect(Result, SEK); 12525 } 12526 12527 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 12528 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 12529 assert(!isValueDependent() && 12530 "Expression evaluator can't be called on a dependent expression."); 12531 12532 EvalResult EVResult; 12533 EVResult.Diag = Diag; 12534 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 12535 Info.InConstantContext = true; 12536 12537 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 12538 (void)Result; 12539 assert(Result && "Could not evaluate expression"); 12540 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 12541 12542 return EVResult.Val.getInt(); 12543 } 12544 12545 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 12546 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 12547 assert(!isValueDependent() && 12548 "Expression evaluator can't be called on a dependent expression."); 12549 12550 EvalResult EVResult; 12551 EVResult.Diag = Diag; 12552 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow); 12553 Info.InConstantContext = true; 12554 12555 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 12556 (void)Result; 12557 assert(Result && "Could not evaluate expression"); 12558 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 12559 12560 return EVResult.Val.getInt(); 12561 } 12562 12563 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 12564 assert(!isValueDependent() && 12565 "Expression evaluator can't be called on a dependent expression."); 12566 12567 bool IsConst; 12568 EvalResult EVResult; 12569 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 12570 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow); 12571 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 12572 } 12573 } 12574 12575 bool Expr::EvalResult::isGlobalLValue() const { 12576 assert(Val.isLValue()); 12577 return IsGlobalLValue(Val.getLValueBase()); 12578 } 12579 12580 12581 /// isIntegerConstantExpr - this recursive routine will test if an expression is 12582 /// an integer constant expression. 12583 12584 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 12585 /// comma, etc 12586 12587 // CheckICE - This function does the fundamental ICE checking: the returned 12588 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 12589 // and a (possibly null) SourceLocation indicating the location of the problem. 12590 // 12591 // Note that to reduce code duplication, this helper does no evaluation 12592 // itself; the caller checks whether the expression is evaluatable, and 12593 // in the rare cases where CheckICE actually cares about the evaluated 12594 // value, it calls into Evaluate. 12595 12596 namespace { 12597 12598 enum ICEKind { 12599 /// This expression is an ICE. 12600 IK_ICE, 12601 /// This expression is not an ICE, but if it isn't evaluated, it's 12602 /// a legal subexpression for an ICE. This return value is used to handle 12603 /// the comma operator in C99 mode, and non-constant subexpressions. 12604 IK_ICEIfUnevaluated, 12605 /// This expression is not an ICE, and is not a legal subexpression for one. 12606 IK_NotICE 12607 }; 12608 12609 struct ICEDiag { 12610 ICEKind Kind; 12611 SourceLocation Loc; 12612 12613 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 12614 }; 12615 12616 } 12617 12618 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 12619 12620 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 12621 12622 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 12623 Expr::EvalResult EVResult; 12624 Expr::EvalStatus Status; 12625 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 12626 12627 Info.InConstantContext = true; 12628 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 12629 !EVResult.Val.isInt()) 12630 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12631 12632 return NoDiag(); 12633 } 12634 12635 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 12636 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 12637 if (!E->getType()->isIntegralOrEnumerationType()) 12638 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12639 12640 switch (E->getStmtClass()) { 12641 #define ABSTRACT_STMT(Node) 12642 #define STMT(Node, Base) case Expr::Node##Class: 12643 #define EXPR(Node, Base) 12644 #include "clang/AST/StmtNodes.inc" 12645 case Expr::PredefinedExprClass: 12646 case Expr::FloatingLiteralClass: 12647 case Expr::ImaginaryLiteralClass: 12648 case Expr::StringLiteralClass: 12649 case Expr::ArraySubscriptExprClass: 12650 case Expr::OMPArraySectionExprClass: 12651 case Expr::MemberExprClass: 12652 case Expr::CompoundAssignOperatorClass: 12653 case Expr::CompoundLiteralExprClass: 12654 case Expr::ExtVectorElementExprClass: 12655 case Expr::DesignatedInitExprClass: 12656 case Expr::ArrayInitLoopExprClass: 12657 case Expr::ArrayInitIndexExprClass: 12658 case Expr::NoInitExprClass: 12659 case Expr::DesignatedInitUpdateExprClass: 12660 case Expr::ImplicitValueInitExprClass: 12661 case Expr::ParenListExprClass: 12662 case Expr::VAArgExprClass: 12663 case Expr::AddrLabelExprClass: 12664 case Expr::StmtExprClass: 12665 case Expr::CXXMemberCallExprClass: 12666 case Expr::CUDAKernelCallExprClass: 12667 case Expr::CXXDynamicCastExprClass: 12668 case Expr::CXXTypeidExprClass: 12669 case Expr::CXXUuidofExprClass: 12670 case Expr::MSPropertyRefExprClass: 12671 case Expr::MSPropertySubscriptExprClass: 12672 case Expr::CXXNullPtrLiteralExprClass: 12673 case Expr::UserDefinedLiteralClass: 12674 case Expr::CXXThisExprClass: 12675 case Expr::CXXThrowExprClass: 12676 case Expr::CXXNewExprClass: 12677 case Expr::CXXDeleteExprClass: 12678 case Expr::CXXPseudoDestructorExprClass: 12679 case Expr::UnresolvedLookupExprClass: 12680 case Expr::TypoExprClass: 12681 case Expr::DependentScopeDeclRefExprClass: 12682 case Expr::CXXConstructExprClass: 12683 case Expr::CXXInheritedCtorInitExprClass: 12684 case Expr::CXXStdInitializerListExprClass: 12685 case Expr::CXXBindTemporaryExprClass: 12686 case Expr::ExprWithCleanupsClass: 12687 case Expr::CXXTemporaryObjectExprClass: 12688 case Expr::CXXUnresolvedConstructExprClass: 12689 case Expr::CXXDependentScopeMemberExprClass: 12690 case Expr::UnresolvedMemberExprClass: 12691 case Expr::ObjCStringLiteralClass: 12692 case Expr::ObjCBoxedExprClass: 12693 case Expr::ObjCArrayLiteralClass: 12694 case Expr::ObjCDictionaryLiteralClass: 12695 case Expr::ObjCEncodeExprClass: 12696 case Expr::ObjCMessageExprClass: 12697 case Expr::ObjCSelectorExprClass: 12698 case Expr::ObjCProtocolExprClass: 12699 case Expr::ObjCIvarRefExprClass: 12700 case Expr::ObjCPropertyRefExprClass: 12701 case Expr::ObjCSubscriptRefExprClass: 12702 case Expr::ObjCIsaExprClass: 12703 case Expr::ObjCAvailabilityCheckExprClass: 12704 case Expr::ShuffleVectorExprClass: 12705 case Expr::ConvertVectorExprClass: 12706 case Expr::BlockExprClass: 12707 case Expr::NoStmtClass: 12708 case Expr::OpaqueValueExprClass: 12709 case Expr::PackExpansionExprClass: 12710 case Expr::SubstNonTypeTemplateParmPackExprClass: 12711 case Expr::FunctionParmPackExprClass: 12712 case Expr::AsTypeExprClass: 12713 case Expr::ObjCIndirectCopyRestoreExprClass: 12714 case Expr::MaterializeTemporaryExprClass: 12715 case Expr::PseudoObjectExprClass: 12716 case Expr::AtomicExprClass: 12717 case Expr::LambdaExprClass: 12718 case Expr::CXXFoldExprClass: 12719 case Expr::CoawaitExprClass: 12720 case Expr::DependentCoawaitExprClass: 12721 case Expr::CoyieldExprClass: 12722 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12723 12724 case Expr::InitListExprClass: { 12725 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 12726 // form "T x = { a };" is equivalent to "T x = a;". 12727 // Unless we're initializing a reference, T is a scalar as it is known to be 12728 // of integral or enumeration type. 12729 if (E->isRValue()) 12730 if (cast<InitListExpr>(E)->getNumInits() == 1) 12731 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 12732 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12733 } 12734 12735 case Expr::SizeOfPackExprClass: 12736 case Expr::GNUNullExprClass: 12737 case Expr::SourceLocExprClass: 12738 return NoDiag(); 12739 12740 case Expr::SubstNonTypeTemplateParmExprClass: 12741 return 12742 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 12743 12744 case Expr::ConstantExprClass: 12745 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 12746 12747 case Expr::ParenExprClass: 12748 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 12749 case Expr::GenericSelectionExprClass: 12750 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 12751 case Expr::IntegerLiteralClass: 12752 case Expr::FixedPointLiteralClass: 12753 case Expr::CharacterLiteralClass: 12754 case Expr::ObjCBoolLiteralExprClass: 12755 case Expr::CXXBoolLiteralExprClass: 12756 case Expr::CXXScalarValueInitExprClass: 12757 case Expr::TypeTraitExprClass: 12758 case Expr::ArrayTypeTraitExprClass: 12759 case Expr::ExpressionTraitExprClass: 12760 case Expr::CXXNoexceptExprClass: 12761 return NoDiag(); 12762 case Expr::CallExprClass: 12763 case Expr::CXXOperatorCallExprClass: { 12764 // C99 6.6/3 allows function calls within unevaluated subexpressions of 12765 // constant expressions, but they can never be ICEs because an ICE cannot 12766 // contain an operand of (pointer to) function type. 12767 const CallExpr *CE = cast<CallExpr>(E); 12768 if (CE->getBuiltinCallee()) 12769 return CheckEvalInICE(E, Ctx); 12770 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12771 } 12772 case Expr::DeclRefExprClass: { 12773 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 12774 return NoDiag(); 12775 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 12776 if (Ctx.getLangOpts().CPlusPlus && 12777 D && IsConstNonVolatile(D->getType())) { 12778 // Parameter variables are never constants. Without this check, 12779 // getAnyInitializer() can find a default argument, which leads 12780 // to chaos. 12781 if (isa<ParmVarDecl>(D)) 12782 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12783 12784 // C++ 7.1.5.1p2 12785 // A variable of non-volatile const-qualified integral or enumeration 12786 // type initialized by an ICE can be used in ICEs. 12787 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 12788 if (!Dcl->getType()->isIntegralOrEnumerationType()) 12789 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12790 12791 const VarDecl *VD; 12792 // Look for a declaration of this variable that has an initializer, and 12793 // check whether it is an ICE. 12794 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 12795 return NoDiag(); 12796 else 12797 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12798 } 12799 } 12800 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12801 } 12802 case Expr::UnaryOperatorClass: { 12803 const UnaryOperator *Exp = cast<UnaryOperator>(E); 12804 switch (Exp->getOpcode()) { 12805 case UO_PostInc: 12806 case UO_PostDec: 12807 case UO_PreInc: 12808 case UO_PreDec: 12809 case UO_AddrOf: 12810 case UO_Deref: 12811 case UO_Coawait: 12812 // C99 6.6/3 allows increment and decrement within unevaluated 12813 // subexpressions of constant expressions, but they can never be ICEs 12814 // because an ICE cannot contain an lvalue operand. 12815 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12816 case UO_Extension: 12817 case UO_LNot: 12818 case UO_Plus: 12819 case UO_Minus: 12820 case UO_Not: 12821 case UO_Real: 12822 case UO_Imag: 12823 return CheckICE(Exp->getSubExpr(), Ctx); 12824 } 12825 llvm_unreachable("invalid unary operator class"); 12826 } 12827 case Expr::OffsetOfExprClass: { 12828 // Note that per C99, offsetof must be an ICE. And AFAIK, using 12829 // EvaluateAsRValue matches the proposed gcc behavior for cases like 12830 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 12831 // compliance: we should warn earlier for offsetof expressions with 12832 // array subscripts that aren't ICEs, and if the array subscripts 12833 // are ICEs, the value of the offsetof must be an integer constant. 12834 return CheckEvalInICE(E, Ctx); 12835 } 12836 case Expr::UnaryExprOrTypeTraitExprClass: { 12837 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 12838 if ((Exp->getKind() == UETT_SizeOf) && 12839 Exp->getTypeOfArgument()->isVariableArrayType()) 12840 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12841 return NoDiag(); 12842 } 12843 case Expr::BinaryOperatorClass: { 12844 const BinaryOperator *Exp = cast<BinaryOperator>(E); 12845 switch (Exp->getOpcode()) { 12846 case BO_PtrMemD: 12847 case BO_PtrMemI: 12848 case BO_Assign: 12849 case BO_MulAssign: 12850 case BO_DivAssign: 12851 case BO_RemAssign: 12852 case BO_AddAssign: 12853 case BO_SubAssign: 12854 case BO_ShlAssign: 12855 case BO_ShrAssign: 12856 case BO_AndAssign: 12857 case BO_XorAssign: 12858 case BO_OrAssign: 12859 // C99 6.6/3 allows assignments within unevaluated subexpressions of 12860 // constant expressions, but they can never be ICEs because an ICE cannot 12861 // contain an lvalue operand. 12862 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12863 12864 case BO_Mul: 12865 case BO_Div: 12866 case BO_Rem: 12867 case BO_Add: 12868 case BO_Sub: 12869 case BO_Shl: 12870 case BO_Shr: 12871 case BO_LT: 12872 case BO_GT: 12873 case BO_LE: 12874 case BO_GE: 12875 case BO_EQ: 12876 case BO_NE: 12877 case BO_And: 12878 case BO_Xor: 12879 case BO_Or: 12880 case BO_Comma: 12881 case BO_Cmp: { 12882 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 12883 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 12884 if (Exp->getOpcode() == BO_Div || 12885 Exp->getOpcode() == BO_Rem) { 12886 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 12887 // we don't evaluate one. 12888 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 12889 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 12890 if (REval == 0) 12891 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12892 if (REval.isSigned() && REval.isAllOnesValue()) { 12893 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 12894 if (LEval.isMinSignedValue()) 12895 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12896 } 12897 } 12898 } 12899 if (Exp->getOpcode() == BO_Comma) { 12900 if (Ctx.getLangOpts().C99) { 12901 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 12902 // if it isn't evaluated. 12903 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 12904 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12905 } else { 12906 // In both C89 and C++, commas in ICEs are illegal. 12907 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12908 } 12909 } 12910 return Worst(LHSResult, RHSResult); 12911 } 12912 case BO_LAnd: 12913 case BO_LOr: { 12914 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 12915 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 12916 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 12917 // Rare case where the RHS has a comma "side-effect"; we need 12918 // to actually check the condition to see whether the side 12919 // with the comma is evaluated. 12920 if ((Exp->getOpcode() == BO_LAnd) != 12921 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 12922 return RHSResult; 12923 return NoDiag(); 12924 } 12925 12926 return Worst(LHSResult, RHSResult); 12927 } 12928 } 12929 llvm_unreachable("invalid binary operator kind"); 12930 } 12931 case Expr::ImplicitCastExprClass: 12932 case Expr::CStyleCastExprClass: 12933 case Expr::CXXFunctionalCastExprClass: 12934 case Expr::CXXStaticCastExprClass: 12935 case Expr::CXXReinterpretCastExprClass: 12936 case Expr::CXXConstCastExprClass: 12937 case Expr::ObjCBridgedCastExprClass: { 12938 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 12939 if (isa<ExplicitCastExpr>(E)) { 12940 if (const FloatingLiteral *FL 12941 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 12942 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 12943 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 12944 APSInt IgnoredVal(DestWidth, !DestSigned); 12945 bool Ignored; 12946 // If the value does not fit in the destination type, the behavior is 12947 // undefined, so we are not required to treat it as a constant 12948 // expression. 12949 if (FL->getValue().convertToInteger(IgnoredVal, 12950 llvm::APFloat::rmTowardZero, 12951 &Ignored) & APFloat::opInvalidOp) 12952 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12953 return NoDiag(); 12954 } 12955 } 12956 switch (cast<CastExpr>(E)->getCastKind()) { 12957 case CK_LValueToRValue: 12958 case CK_AtomicToNonAtomic: 12959 case CK_NonAtomicToAtomic: 12960 case CK_NoOp: 12961 case CK_IntegralToBoolean: 12962 case CK_IntegralCast: 12963 return CheckICE(SubExpr, Ctx); 12964 default: 12965 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12966 } 12967 } 12968 case Expr::BinaryConditionalOperatorClass: { 12969 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 12970 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 12971 if (CommonResult.Kind == IK_NotICE) return CommonResult; 12972 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 12973 if (FalseResult.Kind == IK_NotICE) return FalseResult; 12974 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 12975 if (FalseResult.Kind == IK_ICEIfUnevaluated && 12976 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 12977 return FalseResult; 12978 } 12979 case Expr::ConditionalOperatorClass: { 12980 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 12981 // If the condition (ignoring parens) is a __builtin_constant_p call, 12982 // then only the true side is actually considered in an integer constant 12983 // expression, and it is fully evaluated. This is an important GNU 12984 // extension. See GCC PR38377 for discussion. 12985 if (const CallExpr *CallCE 12986 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 12987 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 12988 return CheckEvalInICE(E, Ctx); 12989 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 12990 if (CondResult.Kind == IK_NotICE) 12991 return CondResult; 12992 12993 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 12994 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 12995 12996 if (TrueResult.Kind == IK_NotICE) 12997 return TrueResult; 12998 if (FalseResult.Kind == IK_NotICE) 12999 return FalseResult; 13000 if (CondResult.Kind == IK_ICEIfUnevaluated) 13001 return CondResult; 13002 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 13003 return NoDiag(); 13004 // Rare case where the diagnostics depend on which side is evaluated 13005 // Note that if we get here, CondResult is 0, and at least one of 13006 // TrueResult and FalseResult is non-zero. 13007 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 13008 return FalseResult; 13009 return TrueResult; 13010 } 13011 case Expr::CXXDefaultArgExprClass: 13012 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 13013 case Expr::CXXDefaultInitExprClass: 13014 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 13015 case Expr::ChooseExprClass: { 13016 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 13017 } 13018 case Expr::BuiltinBitCastExprClass: { 13019 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 13020 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13021 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 13022 } 13023 } 13024 13025 llvm_unreachable("Invalid StmtClass!"); 13026 } 13027 13028 /// Evaluate an expression as a C++11 integral constant expression. 13029 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 13030 const Expr *E, 13031 llvm::APSInt *Value, 13032 SourceLocation *Loc) { 13033 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13034 if (Loc) *Loc = E->getExprLoc(); 13035 return false; 13036 } 13037 13038 APValue Result; 13039 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 13040 return false; 13041 13042 if (!Result.isInt()) { 13043 if (Loc) *Loc = E->getExprLoc(); 13044 return false; 13045 } 13046 13047 if (Value) *Value = Result.getInt(); 13048 return true; 13049 } 13050 13051 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 13052 SourceLocation *Loc) const { 13053 assert(!isValueDependent() && 13054 "Expression evaluator can't be called on a dependent expression."); 13055 13056 if (Ctx.getLangOpts().CPlusPlus11) 13057 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 13058 13059 ICEDiag D = CheckICE(this, Ctx); 13060 if (D.Kind != IK_ICE) { 13061 if (Loc) *Loc = D.Loc; 13062 return false; 13063 } 13064 return true; 13065 } 13066 13067 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 13068 SourceLocation *Loc, bool isEvaluated) const { 13069 assert(!isValueDependent() && 13070 "Expression evaluator can't be called on a dependent expression."); 13071 13072 if (Ctx.getLangOpts().CPlusPlus11) 13073 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 13074 13075 if (!isIntegerConstantExpr(Ctx, Loc)) 13076 return false; 13077 13078 // The only possible side-effects here are due to UB discovered in the 13079 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 13080 // required to treat the expression as an ICE, so we produce the folded 13081 // value. 13082 EvalResult ExprResult; 13083 Expr::EvalStatus Status; 13084 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 13085 Info.InConstantContext = true; 13086 13087 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 13088 llvm_unreachable("ICE cannot be evaluated!"); 13089 13090 Value = ExprResult.Val.getInt(); 13091 return true; 13092 } 13093 13094 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 13095 assert(!isValueDependent() && 13096 "Expression evaluator can't be called on a dependent expression."); 13097 13098 return CheckICE(this, Ctx).Kind == IK_ICE; 13099 } 13100 13101 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 13102 SourceLocation *Loc) const { 13103 assert(!isValueDependent() && 13104 "Expression evaluator can't be called on a dependent expression."); 13105 13106 // We support this checking in C++98 mode in order to diagnose compatibility 13107 // issues. 13108 assert(Ctx.getLangOpts().CPlusPlus); 13109 13110 // Build evaluation settings. 13111 Expr::EvalStatus Status; 13112 SmallVector<PartialDiagnosticAt, 8> Diags; 13113 Status.Diag = &Diags; 13114 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 13115 13116 APValue Scratch; 13117 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 13118 13119 if (!Diags.empty()) { 13120 IsConstExpr = false; 13121 if (Loc) *Loc = Diags[0].first; 13122 } else if (!IsConstExpr) { 13123 // FIXME: This shouldn't happen. 13124 if (Loc) *Loc = getExprLoc(); 13125 } 13126 13127 return IsConstExpr; 13128 } 13129 13130 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 13131 const FunctionDecl *Callee, 13132 ArrayRef<const Expr*> Args, 13133 const Expr *This) const { 13134 assert(!isValueDependent() && 13135 "Expression evaluator can't be called on a dependent expression."); 13136 13137 Expr::EvalStatus Status; 13138 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 13139 Info.InConstantContext = true; 13140 13141 LValue ThisVal; 13142 const LValue *ThisPtr = nullptr; 13143 if (This) { 13144 #ifndef NDEBUG 13145 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 13146 assert(MD && "Don't provide `this` for non-methods."); 13147 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 13148 #endif 13149 if (EvaluateObjectArgument(Info, This, ThisVal)) 13150 ThisPtr = &ThisVal; 13151 if (Info.EvalStatus.HasSideEffects) 13152 return false; 13153 } 13154 13155 ArgVector ArgValues(Args.size()); 13156 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 13157 I != E; ++I) { 13158 if ((*I)->isValueDependent() || 13159 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 13160 // If evaluation fails, throw away the argument entirely. 13161 ArgValues[I - Args.begin()] = APValue(); 13162 if (Info.EvalStatus.HasSideEffects) 13163 return false; 13164 } 13165 13166 // Build fake call to Callee. 13167 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 13168 ArgValues.data()); 13169 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 13170 } 13171 13172 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 13173 SmallVectorImpl< 13174 PartialDiagnosticAt> &Diags) { 13175 // FIXME: It would be useful to check constexpr function templates, but at the 13176 // moment the constant expression evaluator cannot cope with the non-rigorous 13177 // ASTs which we build for dependent expressions. 13178 if (FD->isDependentContext()) 13179 return true; 13180 13181 Expr::EvalStatus Status; 13182 Status.Diag = &Diags; 13183 13184 EvalInfo Info(FD->getASTContext(), Status, 13185 EvalInfo::EM_PotentialConstantExpression); 13186 Info.InConstantContext = true; 13187 13188 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 13189 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 13190 13191 // Fabricate an arbitrary expression on the stack and pretend that it 13192 // is a temporary being used as the 'this' pointer. 13193 LValue This; 13194 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 13195 This.set({&VIE, Info.CurrentCall->Index}); 13196 13197 ArrayRef<const Expr*> Args; 13198 13199 APValue Scratch; 13200 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 13201 // Evaluate the call as a constant initializer, to allow the construction 13202 // of objects of non-literal types. 13203 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 13204 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 13205 } else { 13206 SourceLocation Loc = FD->getLocation(); 13207 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 13208 Args, FD->getBody(), Info, Scratch, nullptr); 13209 } 13210 13211 return Diags.empty(); 13212 } 13213 13214 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 13215 const FunctionDecl *FD, 13216 SmallVectorImpl< 13217 PartialDiagnosticAt> &Diags) { 13218 assert(!E->isValueDependent() && 13219 "Expression evaluator can't be called on a dependent expression."); 13220 13221 Expr::EvalStatus Status; 13222 Status.Diag = &Diags; 13223 13224 EvalInfo Info(FD->getASTContext(), Status, 13225 EvalInfo::EM_PotentialConstantExpressionUnevaluated); 13226 Info.InConstantContext = true; 13227 13228 // Fabricate a call stack frame to give the arguments a plausible cover story. 13229 ArrayRef<const Expr*> Args; 13230 ArgVector ArgValues(0); 13231 bool Success = EvaluateArgs(Args, ArgValues, Info, FD); 13232 (void)Success; 13233 assert(Success && 13234 "Failed to set up arguments for potential constant evaluation"); 13235 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 13236 13237 APValue ResultScratch; 13238 Evaluate(ResultScratch, Info, E); 13239 return Diags.empty(); 13240 } 13241 13242 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 13243 unsigned Type) const { 13244 if (!getType()->isPointerType()) 13245 return false; 13246 13247 Expr::EvalStatus Status; 13248 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 13249 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 13250 } 13251