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/Support/SaveAndRestore.h" 51 #include "llvm/Support/raw_ostream.h" 52 #include <cstring> 53 #include <functional> 54 55 #define DEBUG_TYPE "exprconstant" 56 57 using namespace clang; 58 using llvm::APSInt; 59 using llvm::APFloat; 60 61 static bool IsGlobalLValue(APValue::LValueBase B); 62 63 namespace { 64 struct LValue; 65 struct CallStackFrame; 66 struct EvalInfo; 67 68 using SourceLocExprScopeGuard = 69 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 70 71 static QualType getType(APValue::LValueBase B) { 72 if (!B) return QualType(); 73 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 74 // FIXME: It's unclear where we're supposed to take the type from, and 75 // this actually matters for arrays of unknown bound. Eg: 76 // 77 // extern int arr[]; void f() { extern int arr[3]; }; 78 // constexpr int *p = &arr[1]; // valid? 79 // 80 // For now, we take the array bound from the most recent declaration. 81 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 82 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 83 QualType T = Redecl->getType(); 84 if (!T->isIncompleteArrayType()) 85 return T; 86 } 87 return D->getType(); 88 } 89 90 if (B.is<TypeInfoLValue>()) 91 return B.getTypeInfoType(); 92 93 const Expr *Base = B.get<const Expr*>(); 94 95 // For a materialized temporary, the type of the temporary we materialized 96 // may not be the type of the expression. 97 if (const MaterializeTemporaryExpr *MTE = 98 dyn_cast<MaterializeTemporaryExpr>(Base)) { 99 SmallVector<const Expr *, 2> CommaLHSs; 100 SmallVector<SubobjectAdjustment, 2> Adjustments; 101 const Expr *Temp = MTE->GetTemporaryExpr(); 102 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 103 Adjustments); 104 // Keep any cv-qualifiers from the reference if we generated a temporary 105 // for it directly. Otherwise use the type after adjustment. 106 if (!Adjustments.empty()) 107 return Inner->getType(); 108 } 109 110 return Base->getType(); 111 } 112 113 /// Get an LValue path entry, which is known to not be an array index, as a 114 /// field declaration. 115 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 116 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 117 } 118 /// Get an LValue path entry, which is known to not be an array index, as a 119 /// base class declaration. 120 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 121 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 122 } 123 /// Determine whether this LValue path entry for a base class names a virtual 124 /// base class. 125 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 126 return E.getAsBaseOrMember().getInt(); 127 } 128 129 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 130 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 131 const FunctionDecl *Callee = CE->getDirectCallee(); 132 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 133 } 134 135 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 136 /// This will look through a single cast. 137 /// 138 /// Returns null if we couldn't unwrap a function with alloc_size. 139 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 140 if (!E->getType()->isPointerType()) 141 return nullptr; 142 143 E = E->IgnoreParens(); 144 // If we're doing a variable assignment from e.g. malloc(N), there will 145 // probably be a cast of some kind. In exotic cases, we might also see a 146 // top-level ExprWithCleanups. Ignore them either way. 147 if (const auto *FE = dyn_cast<FullExpr>(E)) 148 E = FE->getSubExpr()->IgnoreParens(); 149 150 if (const auto *Cast = dyn_cast<CastExpr>(E)) 151 E = Cast->getSubExpr()->IgnoreParens(); 152 153 if (const auto *CE = dyn_cast<CallExpr>(E)) 154 return getAllocSizeAttr(CE) ? CE : nullptr; 155 return nullptr; 156 } 157 158 /// Determines whether or not the given Base contains a call to a function 159 /// with the alloc_size attribute. 160 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 161 const auto *E = Base.dyn_cast<const Expr *>(); 162 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 163 } 164 165 /// The bound to claim that an array of unknown bound has. 166 /// The value in MostDerivedArraySize is undefined in this case. So, set it 167 /// to an arbitrary value that's likely to loudly break things if it's used. 168 static const uint64_t AssumedSizeForUnsizedArray = 169 std::numeric_limits<uint64_t>::max() / 2; 170 171 /// Determines if an LValue with the given LValueBase will have an unsized 172 /// array in its designator. 173 /// Find the path length and type of the most-derived subobject in the given 174 /// path, and find the size of the containing array, if any. 175 static unsigned 176 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 177 ArrayRef<APValue::LValuePathEntry> Path, 178 uint64_t &ArraySize, QualType &Type, bool &IsArray, 179 bool &FirstEntryIsUnsizedArray) { 180 // This only accepts LValueBases from APValues, and APValues don't support 181 // arrays that lack size info. 182 assert(!isBaseAnAllocSizeCall(Base) && 183 "Unsized arrays shouldn't appear here"); 184 unsigned MostDerivedLength = 0; 185 Type = getType(Base); 186 187 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 188 if (Type->isArrayType()) { 189 const ArrayType *AT = Ctx.getAsArrayType(Type); 190 Type = AT->getElementType(); 191 MostDerivedLength = I + 1; 192 IsArray = true; 193 194 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 195 ArraySize = CAT->getSize().getZExtValue(); 196 } else { 197 assert(I == 0 && "unexpected unsized array designator"); 198 FirstEntryIsUnsizedArray = true; 199 ArraySize = AssumedSizeForUnsizedArray; 200 } 201 } else if (Type->isAnyComplexType()) { 202 const ComplexType *CT = Type->castAs<ComplexType>(); 203 Type = CT->getElementType(); 204 ArraySize = 2; 205 MostDerivedLength = I + 1; 206 IsArray = true; 207 } else if (const FieldDecl *FD = getAsField(Path[I])) { 208 Type = FD->getType(); 209 ArraySize = 0; 210 MostDerivedLength = I + 1; 211 IsArray = false; 212 } else { 213 // Path[I] describes a base class. 214 ArraySize = 0; 215 IsArray = false; 216 } 217 } 218 return MostDerivedLength; 219 } 220 221 // The order of this enum is important for diagnostics. 222 enum CheckSubobjectKind { 223 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex, 224 CSK_Real, CSK_Imag 225 }; 226 227 /// A path from a glvalue to a subobject of that glvalue. 228 struct SubobjectDesignator { 229 /// True if the subobject was named in a manner not supported by C++11. Such 230 /// lvalues can still be folded, but they are not core constant expressions 231 /// and we cannot perform lvalue-to-rvalue conversions on them. 232 unsigned Invalid : 1; 233 234 /// Is this a pointer one past the end of an object? 235 unsigned IsOnePastTheEnd : 1; 236 237 /// Indicator of whether the first entry is an unsized array. 238 unsigned FirstEntryIsAnUnsizedArray : 1; 239 240 /// Indicator of whether the most-derived object is an array element. 241 unsigned MostDerivedIsArrayElement : 1; 242 243 /// The length of the path to the most-derived object of which this is a 244 /// subobject. 245 unsigned MostDerivedPathLength : 28; 246 247 /// The size of the array of which the most-derived object is an element. 248 /// This will always be 0 if the most-derived object is not an array 249 /// element. 0 is not an indicator of whether or not the most-derived object 250 /// is an array, however, because 0-length arrays are allowed. 251 /// 252 /// If the current array is an unsized array, the value of this is 253 /// undefined. 254 uint64_t MostDerivedArraySize; 255 256 /// The type of the most derived object referred to by this address. 257 QualType MostDerivedType; 258 259 typedef APValue::LValuePathEntry PathEntry; 260 261 /// The entries on the path from the glvalue to the designated subobject. 262 SmallVector<PathEntry, 8> Entries; 263 264 SubobjectDesignator() : Invalid(true) {} 265 266 explicit SubobjectDesignator(QualType T) 267 : Invalid(false), IsOnePastTheEnd(false), 268 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 269 MostDerivedPathLength(0), MostDerivedArraySize(0), 270 MostDerivedType(T) {} 271 272 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 273 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 274 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 275 MostDerivedPathLength(0), MostDerivedArraySize(0) { 276 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 277 if (!Invalid) { 278 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 279 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 280 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 281 if (V.getLValueBase()) { 282 bool IsArray = false; 283 bool FirstIsUnsizedArray = false; 284 MostDerivedPathLength = findMostDerivedSubobject( 285 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 286 MostDerivedType, IsArray, FirstIsUnsizedArray); 287 MostDerivedIsArrayElement = IsArray; 288 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 289 } 290 } 291 } 292 293 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 294 unsigned NewLength) { 295 if (Invalid) 296 return; 297 298 assert(Base && "cannot truncate path for null pointer"); 299 assert(NewLength <= Entries.size() && "not a truncation"); 300 301 if (NewLength == Entries.size()) 302 return; 303 Entries.resize(NewLength); 304 305 bool IsArray = false; 306 bool FirstIsUnsizedArray = false; 307 MostDerivedPathLength = findMostDerivedSubobject( 308 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 309 FirstIsUnsizedArray); 310 MostDerivedIsArrayElement = IsArray; 311 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 312 } 313 314 void setInvalid() { 315 Invalid = true; 316 Entries.clear(); 317 } 318 319 /// Determine whether the most derived subobject is an array without a 320 /// known bound. 321 bool isMostDerivedAnUnsizedArray() const { 322 assert(!Invalid && "Calling this makes no sense on invalid designators"); 323 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 324 } 325 326 /// Determine what the most derived array's size is. Results in an assertion 327 /// failure if the most derived array lacks a size. 328 uint64_t getMostDerivedArraySize() const { 329 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 330 return MostDerivedArraySize; 331 } 332 333 /// Determine whether this is a one-past-the-end pointer. 334 bool isOnePastTheEnd() const { 335 assert(!Invalid); 336 if (IsOnePastTheEnd) 337 return true; 338 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 339 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 340 MostDerivedArraySize) 341 return true; 342 return false; 343 } 344 345 /// Get the range of valid index adjustments in the form 346 /// {maximum value that can be subtracted from this pointer, 347 /// maximum value that can be added to this pointer} 348 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 349 if (Invalid || isMostDerivedAnUnsizedArray()) 350 return {0, 0}; 351 352 // [expr.add]p4: For the purposes of these operators, a pointer to a 353 // nonarray object behaves the same as a pointer to the first element of 354 // an array of length one with the type of the object as its element type. 355 bool IsArray = MostDerivedPathLength == Entries.size() && 356 MostDerivedIsArrayElement; 357 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 358 : (uint64_t)IsOnePastTheEnd; 359 uint64_t ArraySize = 360 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 361 return {ArrayIndex, ArraySize - ArrayIndex}; 362 } 363 364 /// Check that this refers to a valid subobject. 365 bool isValidSubobject() const { 366 if (Invalid) 367 return false; 368 return !isOnePastTheEnd(); 369 } 370 /// Check that this refers to a valid subobject, and if not, produce a 371 /// relevant diagnostic and set the designator as invalid. 372 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 373 374 /// Get the type of the designated object. 375 QualType getType(ASTContext &Ctx) const { 376 assert(!Invalid && "invalid designator has no subobject type"); 377 return MostDerivedPathLength == Entries.size() 378 ? MostDerivedType 379 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 380 } 381 382 /// Update this designator to refer to the first element within this array. 383 void addArrayUnchecked(const ConstantArrayType *CAT) { 384 Entries.push_back(PathEntry::ArrayIndex(0)); 385 386 // This is a most-derived object. 387 MostDerivedType = CAT->getElementType(); 388 MostDerivedIsArrayElement = true; 389 MostDerivedArraySize = CAT->getSize().getZExtValue(); 390 MostDerivedPathLength = Entries.size(); 391 } 392 /// Update this designator to refer to the first element within the array of 393 /// elements of type T. This is an array of unknown size. 394 void addUnsizedArrayUnchecked(QualType ElemTy) { 395 Entries.push_back(PathEntry::ArrayIndex(0)); 396 397 MostDerivedType = ElemTy; 398 MostDerivedIsArrayElement = true; 399 // The value in MostDerivedArraySize is undefined in this case. So, set it 400 // to an arbitrary value that's likely to loudly break things if it's 401 // used. 402 MostDerivedArraySize = AssumedSizeForUnsizedArray; 403 MostDerivedPathLength = Entries.size(); 404 } 405 /// Update this designator to refer to the given base or member of this 406 /// object. 407 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 408 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 409 410 // If this isn't a base class, it's a new most-derived object. 411 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 412 MostDerivedType = FD->getType(); 413 MostDerivedIsArrayElement = false; 414 MostDerivedArraySize = 0; 415 MostDerivedPathLength = Entries.size(); 416 } 417 } 418 /// Update this designator to refer to the given complex component. 419 void addComplexUnchecked(QualType EltTy, bool Imag) { 420 Entries.push_back(PathEntry::ArrayIndex(Imag)); 421 422 // This is technically a most-derived object, though in practice this 423 // is unlikely to matter. 424 MostDerivedType = EltTy; 425 MostDerivedIsArrayElement = true; 426 MostDerivedArraySize = 2; 427 MostDerivedPathLength = Entries.size(); 428 } 429 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 430 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 431 const APSInt &N); 432 /// Add N to the address of this subobject. 433 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 434 if (Invalid || !N) return; 435 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 436 if (isMostDerivedAnUnsizedArray()) { 437 diagnoseUnsizedArrayPointerArithmetic(Info, E); 438 // Can't verify -- trust that the user is doing the right thing (or if 439 // not, trust that the caller will catch the bad behavior). 440 // FIXME: Should we reject if this overflows, at least? 441 Entries.back() = PathEntry::ArrayIndex( 442 Entries.back().getAsArrayIndex() + TruncatedN); 443 return; 444 } 445 446 // [expr.add]p4: For the purposes of these operators, a pointer to a 447 // nonarray object behaves the same as a pointer to the first element of 448 // an array of length one with the type of the object as its element type. 449 bool IsArray = MostDerivedPathLength == Entries.size() && 450 MostDerivedIsArrayElement; 451 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 452 : (uint64_t)IsOnePastTheEnd; 453 uint64_t ArraySize = 454 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 455 456 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 457 // Calculate the actual index in a wide enough type, so we can include 458 // it in the note. 459 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 460 (llvm::APInt&)N += ArrayIndex; 461 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 462 diagnosePointerArithmetic(Info, E, N); 463 setInvalid(); 464 return; 465 } 466 467 ArrayIndex += TruncatedN; 468 assert(ArrayIndex <= ArraySize && 469 "bounds check succeeded for out-of-bounds index"); 470 471 if (IsArray) 472 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 473 else 474 IsOnePastTheEnd = (ArrayIndex != 0); 475 } 476 }; 477 478 /// A stack frame in the constexpr call stack. 479 struct CallStackFrame { 480 EvalInfo &Info; 481 482 /// Parent - The caller of this stack frame. 483 CallStackFrame *Caller; 484 485 /// Callee - The function which was called. 486 const FunctionDecl *Callee; 487 488 /// This - The binding for the this pointer in this call, if any. 489 const LValue *This; 490 491 /// Arguments - Parameter bindings for this function call, indexed by 492 /// parameters' function scope indices. 493 APValue *Arguments; 494 495 /// Source location information about the default argument or default 496 /// initializer expression we're evaluating, if any. 497 CurrentSourceLocExprScope CurSourceLocExprScope; 498 499 // Note that we intentionally use std::map here so that references to 500 // values are stable. 501 typedef std::pair<const void *, unsigned> MapKeyTy; 502 typedef std::map<MapKeyTy, APValue> MapTy; 503 /// Temporaries - Temporary lvalues materialized within this stack frame. 504 MapTy Temporaries; 505 506 /// CallLoc - The location of the call expression for this call. 507 SourceLocation CallLoc; 508 509 /// Index - The call index of this call. 510 unsigned Index; 511 512 /// The stack of integers for tracking version numbers for temporaries. 513 SmallVector<unsigned, 2> TempVersionStack = {1}; 514 unsigned CurTempVersion = TempVersionStack.back(); 515 516 unsigned getTempVersion() const { return TempVersionStack.back(); } 517 518 void pushTempVersion() { 519 TempVersionStack.push_back(++CurTempVersion); 520 } 521 522 void popTempVersion() { 523 TempVersionStack.pop_back(); 524 } 525 526 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 527 // on the overall stack usage of deeply-recursing constexpr evaluations. 528 // (We should cache this map rather than recomputing it repeatedly.) 529 // But let's try this and see how it goes; we can look into caching the map 530 // as a later change. 531 532 /// LambdaCaptureFields - Mapping from captured variables/this to 533 /// corresponding data members in the closure class. 534 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 535 FieldDecl *LambdaThisCaptureField; 536 537 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 538 const FunctionDecl *Callee, const LValue *This, 539 APValue *Arguments); 540 ~CallStackFrame(); 541 542 // Return the temporary for Key whose version number is Version. 543 APValue *getTemporary(const void *Key, unsigned Version) { 544 MapKeyTy KV(Key, Version); 545 auto LB = Temporaries.lower_bound(KV); 546 if (LB != Temporaries.end() && LB->first == KV) 547 return &LB->second; 548 // Pair (Key,Version) wasn't found in the map. Check that no elements 549 // in the map have 'Key' as their key. 550 assert((LB == Temporaries.end() || LB->first.first != Key) && 551 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 552 "Element with key 'Key' found in map"); 553 return nullptr; 554 } 555 556 // Return the current temporary for Key in the map. 557 APValue *getCurrentTemporary(const void *Key) { 558 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 559 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 560 return &std::prev(UB)->second; 561 return nullptr; 562 } 563 564 // Return the version number of the current temporary for Key. 565 unsigned getCurrentTemporaryVersion(const void *Key) const { 566 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 567 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 568 return std::prev(UB)->first.second; 569 return 0; 570 } 571 572 APValue &createTemporary(const void *Key, bool IsLifetimeExtended); 573 }; 574 575 /// Temporarily override 'this'. 576 class ThisOverrideRAII { 577 public: 578 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 579 : Frame(Frame), OldThis(Frame.This) { 580 if (Enable) 581 Frame.This = NewThis; 582 } 583 ~ThisOverrideRAII() { 584 Frame.This = OldThis; 585 } 586 private: 587 CallStackFrame &Frame; 588 const LValue *OldThis; 589 }; 590 591 /// A partial diagnostic which we might know in advance that we are not going 592 /// to emit. 593 class OptionalDiagnostic { 594 PartialDiagnostic *Diag; 595 596 public: 597 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr) 598 : Diag(Diag) {} 599 600 template<typename T> 601 OptionalDiagnostic &operator<<(const T &v) { 602 if (Diag) 603 *Diag << v; 604 return *this; 605 } 606 607 OptionalDiagnostic &operator<<(const APSInt &I) { 608 if (Diag) { 609 SmallVector<char, 32> Buffer; 610 I.toString(Buffer); 611 *Diag << StringRef(Buffer.data(), Buffer.size()); 612 } 613 return *this; 614 } 615 616 OptionalDiagnostic &operator<<(const APFloat &F) { 617 if (Diag) { 618 // FIXME: Force the precision of the source value down so we don't 619 // print digits which are usually useless (we don't really care here if 620 // we truncate a digit by accident in edge cases). Ideally, 621 // APFloat::toString would automatically print the shortest 622 // representation which rounds to the correct value, but it's a bit 623 // tricky to implement. 624 unsigned precision = 625 llvm::APFloat::semanticsPrecision(F.getSemantics()); 626 precision = (precision * 59 + 195) / 196; 627 SmallVector<char, 32> Buffer; 628 F.toString(Buffer, precision); 629 *Diag << StringRef(Buffer.data(), Buffer.size()); 630 } 631 return *this; 632 } 633 634 OptionalDiagnostic &operator<<(const APFixedPoint &FX) { 635 if (Diag) { 636 SmallVector<char, 32> Buffer; 637 FX.toString(Buffer); 638 *Diag << StringRef(Buffer.data(), Buffer.size()); 639 } 640 return *this; 641 } 642 }; 643 644 /// A cleanup, and a flag indicating whether it is lifetime-extended. 645 class Cleanup { 646 llvm::PointerIntPair<APValue*, 1, bool> Value; 647 648 public: 649 Cleanup(APValue *Val, bool IsLifetimeExtended) 650 : Value(Val, IsLifetimeExtended) {} 651 652 bool isLifetimeExtended() const { return Value.getInt(); } 653 void endLifetime() { 654 *Value.getPointer() = APValue(); 655 } 656 }; 657 658 /// A reference to an object whose construction we are currently evaluating. 659 struct ObjectUnderConstruction { 660 APValue::LValueBase Base; 661 ArrayRef<APValue::LValuePathEntry> Path; 662 friend bool operator==(const ObjectUnderConstruction &LHS, 663 const ObjectUnderConstruction &RHS) { 664 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 665 } 666 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 667 return llvm::hash_combine(Obj.Base, Obj.Path); 668 } 669 }; 670 enum class ConstructionPhase { None, Bases, AfterBases }; 671 } 672 673 namespace llvm { 674 template<> struct DenseMapInfo<ObjectUnderConstruction> { 675 using Base = DenseMapInfo<APValue::LValueBase>; 676 static ObjectUnderConstruction getEmptyKey() { 677 return {Base::getEmptyKey(), {}}; } 678 static ObjectUnderConstruction getTombstoneKey() { 679 return {Base::getTombstoneKey(), {}}; 680 } 681 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 682 return hash_value(Object); 683 } 684 static bool isEqual(const ObjectUnderConstruction &LHS, 685 const ObjectUnderConstruction &RHS) { 686 return LHS == RHS; 687 } 688 }; 689 } 690 691 namespace { 692 /// EvalInfo - This is a private struct used by the evaluator to capture 693 /// information about a subexpression as it is folded. It retains information 694 /// about the AST context, but also maintains information about the folded 695 /// expression. 696 /// 697 /// If an expression could be evaluated, it is still possible it is not a C 698 /// "integer constant expression" or constant expression. If not, this struct 699 /// captures information about how and why not. 700 /// 701 /// One bit of information passed *into* the request for constant folding 702 /// indicates whether the subexpression is "evaluated" or not according to C 703 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 704 /// evaluate the expression regardless of what the RHS is, but C only allows 705 /// certain things in certain situations. 706 struct EvalInfo { 707 ASTContext &Ctx; 708 709 /// EvalStatus - Contains information about the evaluation. 710 Expr::EvalStatus &EvalStatus; 711 712 /// CurrentCall - The top of the constexpr call stack. 713 CallStackFrame *CurrentCall; 714 715 /// CallStackDepth - The number of calls in the call stack right now. 716 unsigned CallStackDepth; 717 718 /// NextCallIndex - The next call index to assign. 719 unsigned NextCallIndex; 720 721 /// StepsLeft - The remaining number of evaluation steps we're permitted 722 /// to perform. This is essentially a limit for the number of statements 723 /// we will evaluate. 724 unsigned StepsLeft; 725 726 /// BottomFrame - The frame in which evaluation started. This must be 727 /// initialized after CurrentCall and CallStackDepth. 728 CallStackFrame BottomFrame; 729 730 /// A stack of values whose lifetimes end at the end of some surrounding 731 /// evaluation frame. 732 llvm::SmallVector<Cleanup, 16> CleanupStack; 733 734 /// EvaluatingDecl - This is the declaration whose initializer is being 735 /// evaluated, if any. 736 APValue::LValueBase EvaluatingDecl; 737 738 /// EvaluatingDeclValue - This is the value being constructed for the 739 /// declaration whose initializer is being evaluated, if any. 740 APValue *EvaluatingDeclValue; 741 742 /// Set of objects that are currently being constructed. 743 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 744 ObjectsUnderConstruction; 745 746 struct EvaluatingConstructorRAII { 747 EvalInfo &EI; 748 ObjectUnderConstruction Object; 749 bool DidInsert; 750 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 751 bool HasBases) 752 : EI(EI), Object(Object) { 753 DidInsert = 754 EI.ObjectsUnderConstruction 755 .insert({Object, HasBases ? ConstructionPhase::Bases 756 : ConstructionPhase::AfterBases}) 757 .second; 758 } 759 void finishedConstructingBases() { 760 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 761 } 762 ~EvaluatingConstructorRAII() { 763 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 764 } 765 }; 766 767 ConstructionPhase 768 isEvaluatingConstructor(APValue::LValueBase Base, 769 ArrayRef<APValue::LValuePathEntry> Path) { 770 return ObjectsUnderConstruction.lookup({Base, Path}); 771 } 772 773 /// If we're currently speculatively evaluating, the outermost call stack 774 /// depth at which we can mutate state, otherwise 0. 775 unsigned SpeculativeEvaluationDepth = 0; 776 777 /// The current array initialization index, if we're performing array 778 /// initialization. 779 uint64_t ArrayInitIndex = -1; 780 781 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 782 /// notes attached to it will also be stored, otherwise they will not be. 783 bool HasActiveDiagnostic; 784 785 /// Have we emitted a diagnostic explaining why we couldn't constant 786 /// fold (not just why it's not strictly a constant expression)? 787 bool HasFoldFailureDiagnostic; 788 789 /// Whether or not we're in a context where the front end requires a 790 /// constant value. 791 bool InConstantContext; 792 793 enum EvaluationMode { 794 /// Evaluate as a constant expression. Stop if we find that the expression 795 /// is not a constant expression. 796 EM_ConstantExpression, 797 798 /// Evaluate as a potential constant expression. Keep going if we hit a 799 /// construct that we can't evaluate yet (because we don't yet know the 800 /// value of something) but stop if we hit something that could never be 801 /// a constant expression. 802 EM_PotentialConstantExpression, 803 804 /// Fold the expression to a constant. Stop if we hit a side-effect that 805 /// we can't model. 806 EM_ConstantFold, 807 808 /// Evaluate the expression looking for integer overflow and similar 809 /// issues. Don't worry about side-effects, and try to visit all 810 /// subexpressions. 811 EM_EvaluateForOverflow, 812 813 /// Evaluate in any way we know how. Don't worry about side-effects that 814 /// can't be modeled. 815 EM_IgnoreSideEffects, 816 817 /// Evaluate as a constant expression. Stop if we find that the expression 818 /// is not a constant expression. Some expressions can be retried in the 819 /// optimizer if we don't constant fold them here, but in an unevaluated 820 /// context we try to fold them immediately since the optimizer never 821 /// gets a chance to look at it. 822 EM_ConstantExpressionUnevaluated, 823 824 /// Evaluate as a potential constant expression. Keep going if we hit a 825 /// construct that we can't evaluate yet (because we don't yet know the 826 /// value of something) but stop if we hit something that could never be 827 /// a constant expression. Some expressions can be retried in the 828 /// optimizer if we don't constant fold them here, but in an unevaluated 829 /// context we try to fold them immediately since the optimizer never 830 /// gets a chance to look at it. 831 EM_PotentialConstantExpressionUnevaluated, 832 } EvalMode; 833 834 /// Are we checking whether the expression is a potential constant 835 /// expression? 836 bool checkingPotentialConstantExpression() const { 837 return EvalMode == EM_PotentialConstantExpression || 838 EvalMode == EM_PotentialConstantExpressionUnevaluated; 839 } 840 841 /// Are we checking an expression for overflow? 842 // FIXME: We should check for any kind of undefined or suspicious behavior 843 // in such constructs, not just overflow. 844 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; } 845 846 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 847 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 848 CallStackDepth(0), NextCallIndex(1), 849 StepsLeft(getLangOpts().ConstexprStepLimit), 850 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 851 EvaluatingDecl((const ValueDecl *)nullptr), 852 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 853 HasFoldFailureDiagnostic(false), 854 InConstantContext(false), EvalMode(Mode) {} 855 856 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) { 857 EvaluatingDecl = Base; 858 EvaluatingDeclValue = &Value; 859 } 860 861 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); } 862 863 bool CheckCallLimit(SourceLocation Loc) { 864 // Don't perform any constexpr calls (other than the call we're checking) 865 // when checking a potential constant expression. 866 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 867 return false; 868 if (NextCallIndex == 0) { 869 // NextCallIndex has wrapped around. 870 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 871 return false; 872 } 873 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 874 return true; 875 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 876 << getLangOpts().ConstexprCallDepth; 877 return false; 878 } 879 880 std::pair<CallStackFrame *, unsigned> 881 getCallFrameAndDepth(unsigned CallIndex) { 882 assert(CallIndex && "no call index in getCallFrameAndDepth"); 883 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 884 // be null in this loop. 885 unsigned Depth = CallStackDepth; 886 CallStackFrame *Frame = CurrentCall; 887 while (Frame->Index > CallIndex) { 888 Frame = Frame->Caller; 889 --Depth; 890 } 891 if (Frame->Index == CallIndex) 892 return {Frame, Depth}; 893 return {nullptr, 0}; 894 } 895 896 bool nextStep(const Stmt *S) { 897 if (!StepsLeft) { 898 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 899 return false; 900 } 901 --StepsLeft; 902 return true; 903 } 904 905 private: 906 /// Add a diagnostic to the diagnostics list. 907 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) { 908 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator()); 909 EvalStatus.Diag->push_back(std::make_pair(Loc, PD)); 910 return EvalStatus.Diag->back().second; 911 } 912 913 /// Add notes containing a call stack to the current point of evaluation. 914 void addCallStack(unsigned Limit); 915 916 private: 917 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId, 918 unsigned ExtraNotes, bool IsCCEDiag) { 919 920 if (EvalStatus.Diag) { 921 // If we have a prior diagnostic, it will be noting that the expression 922 // isn't a constant expression. This diagnostic is more important, 923 // unless we require this evaluation to produce a constant expression. 924 // 925 // FIXME: We might want to show both diagnostics to the user in 926 // EM_ConstantFold mode. 927 if (!EvalStatus.Diag->empty()) { 928 switch (EvalMode) { 929 case EM_ConstantFold: 930 case EM_IgnoreSideEffects: 931 case EM_EvaluateForOverflow: 932 if (!HasFoldFailureDiagnostic) 933 break; 934 // We've already failed to fold something. Keep that diagnostic. 935 LLVM_FALLTHROUGH; 936 case EM_ConstantExpression: 937 case EM_PotentialConstantExpression: 938 case EM_ConstantExpressionUnevaluated: 939 case EM_PotentialConstantExpressionUnevaluated: 940 HasActiveDiagnostic = false; 941 return OptionalDiagnostic(); 942 } 943 } 944 945 unsigned CallStackNotes = CallStackDepth - 1; 946 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit(); 947 if (Limit) 948 CallStackNotes = std::min(CallStackNotes, Limit + 1); 949 if (checkingPotentialConstantExpression()) 950 CallStackNotes = 0; 951 952 HasActiveDiagnostic = true; 953 HasFoldFailureDiagnostic = !IsCCEDiag; 954 EvalStatus.Diag->clear(); 955 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes); 956 addDiag(Loc, DiagId); 957 if (!checkingPotentialConstantExpression()) 958 addCallStack(Limit); 959 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second); 960 } 961 HasActiveDiagnostic = false; 962 return OptionalDiagnostic(); 963 } 964 public: 965 // Diagnose that the evaluation could not be folded (FF => FoldFailure) 966 OptionalDiagnostic 967 FFDiag(SourceLocation Loc, 968 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr, 969 unsigned ExtraNotes = 0) { 970 return Diag(Loc, DiagId, ExtraNotes, false); 971 } 972 973 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId 974 = diag::note_invalid_subexpr_in_const_expr, 975 unsigned ExtraNotes = 0) { 976 if (EvalStatus.Diag) 977 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false); 978 HasActiveDiagnostic = false; 979 return OptionalDiagnostic(); 980 } 981 982 /// Diagnose that the evaluation does not produce a C++11 core constant 983 /// expression. 984 /// 985 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or 986 /// EM_PotentialConstantExpression mode and we produce one of these. 987 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId 988 = diag::note_invalid_subexpr_in_const_expr, 989 unsigned ExtraNotes = 0) { 990 // Don't override a previous diagnostic. Don't bother collecting 991 // diagnostics if we're evaluating for overflow. 992 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) { 993 HasActiveDiagnostic = false; 994 return OptionalDiagnostic(); 995 } 996 return Diag(Loc, DiagId, ExtraNotes, true); 997 } 998 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId 999 = diag::note_invalid_subexpr_in_const_expr, 1000 unsigned ExtraNotes = 0) { 1001 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes); 1002 } 1003 /// Add a note to a prior diagnostic. 1004 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) { 1005 if (!HasActiveDiagnostic) 1006 return OptionalDiagnostic(); 1007 return OptionalDiagnostic(&addDiag(Loc, DiagId)); 1008 } 1009 1010 /// Add a stack of notes to a prior diagnostic. 1011 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) { 1012 if (HasActiveDiagnostic) { 1013 EvalStatus.Diag->insert(EvalStatus.Diag->end(), 1014 Diags.begin(), Diags.end()); 1015 } 1016 } 1017 1018 /// Should we continue evaluation after encountering a side-effect that we 1019 /// couldn't model? 1020 bool keepEvaluatingAfterSideEffect() { 1021 switch (EvalMode) { 1022 case EM_PotentialConstantExpression: 1023 case EM_PotentialConstantExpressionUnevaluated: 1024 case EM_EvaluateForOverflow: 1025 case EM_IgnoreSideEffects: 1026 return true; 1027 1028 case EM_ConstantExpression: 1029 case EM_ConstantExpressionUnevaluated: 1030 case EM_ConstantFold: 1031 return false; 1032 } 1033 llvm_unreachable("Missed EvalMode case"); 1034 } 1035 1036 /// Note that we have had a side-effect, and determine whether we should 1037 /// keep evaluating. 1038 bool noteSideEffect() { 1039 EvalStatus.HasSideEffects = true; 1040 return keepEvaluatingAfterSideEffect(); 1041 } 1042 1043 /// Should we continue evaluation after encountering undefined behavior? 1044 bool keepEvaluatingAfterUndefinedBehavior() { 1045 switch (EvalMode) { 1046 case EM_EvaluateForOverflow: 1047 case EM_IgnoreSideEffects: 1048 case EM_ConstantFold: 1049 return true; 1050 1051 case EM_PotentialConstantExpression: 1052 case EM_PotentialConstantExpressionUnevaluated: 1053 case EM_ConstantExpression: 1054 case EM_ConstantExpressionUnevaluated: 1055 return false; 1056 } 1057 llvm_unreachable("Missed EvalMode case"); 1058 } 1059 1060 /// Note that we hit something that was technically undefined behavior, but 1061 /// that we can evaluate past it (such as signed overflow or floating-point 1062 /// division by zero.) 1063 bool noteUndefinedBehavior() { 1064 EvalStatus.HasUndefinedBehavior = true; 1065 return keepEvaluatingAfterUndefinedBehavior(); 1066 } 1067 1068 /// Should we continue evaluation as much as possible after encountering a 1069 /// construct which can't be reduced to a value? 1070 bool keepEvaluatingAfterFailure() { 1071 if (!StepsLeft) 1072 return false; 1073 1074 switch (EvalMode) { 1075 case EM_PotentialConstantExpression: 1076 case EM_PotentialConstantExpressionUnevaluated: 1077 case EM_EvaluateForOverflow: 1078 return true; 1079 1080 case EM_ConstantExpression: 1081 case EM_ConstantExpressionUnevaluated: 1082 case EM_ConstantFold: 1083 case EM_IgnoreSideEffects: 1084 return false; 1085 } 1086 llvm_unreachable("Missed EvalMode case"); 1087 } 1088 1089 /// Notes that we failed to evaluate an expression that other expressions 1090 /// directly depend on, and determine if we should keep evaluating. This 1091 /// should only be called if we actually intend to keep evaluating. 1092 /// 1093 /// Call noteSideEffect() instead if we may be able to ignore the value that 1094 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1095 /// 1096 /// (Foo(), 1) // use noteSideEffect 1097 /// (Foo() || true) // use noteSideEffect 1098 /// Foo() + 1 // use noteFailure 1099 LLVM_NODISCARD bool noteFailure() { 1100 // Failure when evaluating some expression often means there is some 1101 // subexpression whose evaluation was skipped. Therefore, (because we 1102 // don't track whether we skipped an expression when unwinding after an 1103 // evaluation failure) every evaluation failure that bubbles up from a 1104 // subexpression implies that a side-effect has potentially happened. We 1105 // skip setting the HasSideEffects flag to true until we decide to 1106 // continue evaluating after that point, which happens here. 1107 bool KeepGoing = keepEvaluatingAfterFailure(); 1108 EvalStatus.HasSideEffects |= KeepGoing; 1109 return KeepGoing; 1110 } 1111 1112 class ArrayInitLoopIndex { 1113 EvalInfo &Info; 1114 uint64_t OuterIndex; 1115 1116 public: 1117 ArrayInitLoopIndex(EvalInfo &Info) 1118 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1119 Info.ArrayInitIndex = 0; 1120 } 1121 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1122 1123 operator uint64_t&() { return Info.ArrayInitIndex; } 1124 }; 1125 }; 1126 1127 /// Object used to treat all foldable expressions as constant expressions. 1128 struct FoldConstant { 1129 EvalInfo &Info; 1130 bool Enabled; 1131 bool HadNoPriorDiags; 1132 EvalInfo::EvaluationMode OldMode; 1133 1134 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1135 : Info(Info), 1136 Enabled(Enabled), 1137 HadNoPriorDiags(Info.EvalStatus.Diag && 1138 Info.EvalStatus.Diag->empty() && 1139 !Info.EvalStatus.HasSideEffects), 1140 OldMode(Info.EvalMode) { 1141 if (Enabled && 1142 (Info.EvalMode == EvalInfo::EM_ConstantExpression || 1143 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated)) 1144 Info.EvalMode = EvalInfo::EM_ConstantFold; 1145 } 1146 void keepDiagnostics() { Enabled = false; } 1147 ~FoldConstant() { 1148 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1149 !Info.EvalStatus.HasSideEffects) 1150 Info.EvalStatus.Diag->clear(); 1151 Info.EvalMode = OldMode; 1152 } 1153 }; 1154 1155 /// RAII object used to set the current evaluation mode to ignore 1156 /// side-effects. 1157 struct IgnoreSideEffectsRAII { 1158 EvalInfo &Info; 1159 EvalInfo::EvaluationMode OldMode; 1160 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1161 : Info(Info), OldMode(Info.EvalMode) { 1162 if (!Info.checkingPotentialConstantExpression()) 1163 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1164 } 1165 1166 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1167 }; 1168 1169 /// RAII object used to optionally suppress diagnostics and side-effects from 1170 /// a speculative evaluation. 1171 class SpeculativeEvaluationRAII { 1172 EvalInfo *Info = nullptr; 1173 Expr::EvalStatus OldStatus; 1174 unsigned OldSpeculativeEvaluationDepth; 1175 1176 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1177 Info = Other.Info; 1178 OldStatus = Other.OldStatus; 1179 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1180 Other.Info = nullptr; 1181 } 1182 1183 void maybeRestoreState() { 1184 if (!Info) 1185 return; 1186 1187 Info->EvalStatus = OldStatus; 1188 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1189 } 1190 1191 public: 1192 SpeculativeEvaluationRAII() = default; 1193 1194 SpeculativeEvaluationRAII( 1195 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1196 : Info(&Info), OldStatus(Info.EvalStatus), 1197 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1198 Info.EvalStatus.Diag = NewDiag; 1199 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1200 } 1201 1202 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1203 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1204 moveFromAndCancel(std::move(Other)); 1205 } 1206 1207 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1208 maybeRestoreState(); 1209 moveFromAndCancel(std::move(Other)); 1210 return *this; 1211 } 1212 1213 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1214 }; 1215 1216 /// RAII object wrapping a full-expression or block scope, and handling 1217 /// the ending of the lifetime of temporaries created within it. 1218 template<bool IsFullExpression> 1219 class ScopeRAII { 1220 EvalInfo &Info; 1221 unsigned OldStackSize; 1222 public: 1223 ScopeRAII(EvalInfo &Info) 1224 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1225 // Push a new temporary version. This is needed to distinguish between 1226 // temporaries created in different iterations of a loop. 1227 Info.CurrentCall->pushTempVersion(); 1228 } 1229 ~ScopeRAII() { 1230 // Body moved to a static method to encourage the compiler to inline away 1231 // instances of this class. 1232 cleanup(Info, OldStackSize); 1233 Info.CurrentCall->popTempVersion(); 1234 } 1235 private: 1236 static void cleanup(EvalInfo &Info, unsigned OldStackSize) { 1237 unsigned NewEnd = OldStackSize; 1238 for (unsigned I = OldStackSize, N = Info.CleanupStack.size(); 1239 I != N; ++I) { 1240 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) { 1241 // Full-expression cleanup of a lifetime-extended temporary: nothing 1242 // to do, just move this cleanup to the right place in the stack. 1243 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]); 1244 ++NewEnd; 1245 } else { 1246 // End the lifetime of the object. 1247 Info.CleanupStack[I].endLifetime(); 1248 } 1249 } 1250 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd, 1251 Info.CleanupStack.end()); 1252 } 1253 }; 1254 typedef ScopeRAII<false> BlockScopeRAII; 1255 typedef ScopeRAII<true> FullExpressionRAII; 1256 } 1257 1258 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1259 CheckSubobjectKind CSK) { 1260 if (Invalid) 1261 return false; 1262 if (isOnePastTheEnd()) { 1263 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1264 << CSK; 1265 setInvalid(); 1266 return false; 1267 } 1268 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1269 // must actually be at least one array element; even a VLA cannot have a 1270 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1271 return true; 1272 } 1273 1274 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1275 const Expr *E) { 1276 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1277 // Do not set the designator as invalid: we can represent this situation, 1278 // and correct handling of __builtin_object_size requires us to do so. 1279 } 1280 1281 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1282 const Expr *E, 1283 const APSInt &N) { 1284 // If we're complaining, we must be able to statically determine the size of 1285 // the most derived array. 1286 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1287 Info.CCEDiag(E, diag::note_constexpr_array_index) 1288 << N << /*array*/ 0 1289 << static_cast<unsigned>(getMostDerivedArraySize()); 1290 else 1291 Info.CCEDiag(E, diag::note_constexpr_array_index) 1292 << N << /*non-array*/ 1; 1293 setInvalid(); 1294 } 1295 1296 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1297 const FunctionDecl *Callee, const LValue *This, 1298 APValue *Arguments) 1299 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1300 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1301 Info.CurrentCall = this; 1302 ++Info.CallStackDepth; 1303 } 1304 1305 CallStackFrame::~CallStackFrame() { 1306 assert(Info.CurrentCall == this && "calls retired out of order"); 1307 --Info.CallStackDepth; 1308 Info.CurrentCall = Caller; 1309 } 1310 1311 APValue &CallStackFrame::createTemporary(const void *Key, 1312 bool IsLifetimeExtended) { 1313 unsigned Version = Info.CurrentCall->getTempVersion(); 1314 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1315 assert(Result.isAbsent() && "temporary created multiple times"); 1316 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended)); 1317 return Result; 1318 } 1319 1320 static void describeCall(CallStackFrame *Frame, raw_ostream &Out); 1321 1322 void EvalInfo::addCallStack(unsigned Limit) { 1323 // Determine which calls to skip, if any. 1324 unsigned ActiveCalls = CallStackDepth - 1; 1325 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart; 1326 if (Limit && Limit < ActiveCalls) { 1327 SkipStart = Limit / 2 + Limit % 2; 1328 SkipEnd = ActiveCalls - Limit / 2; 1329 } 1330 1331 // Walk the call stack and add the diagnostics. 1332 unsigned CallIdx = 0; 1333 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame; 1334 Frame = Frame->Caller, ++CallIdx) { 1335 // Skip this call? 1336 if (CallIdx >= SkipStart && CallIdx < SkipEnd) { 1337 if (CallIdx == SkipStart) { 1338 // Note that we're skipping calls. 1339 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed) 1340 << unsigned(ActiveCalls - Limit); 1341 } 1342 continue; 1343 } 1344 1345 // Use a different note for an inheriting constructor, because from the 1346 // user's perspective it's not really a function at all. 1347 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) { 1348 if (CD->isInheritingConstructor()) { 1349 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here) 1350 << CD->getParent(); 1351 continue; 1352 } 1353 } 1354 1355 SmallVector<char, 128> Buffer; 1356 llvm::raw_svector_ostream Out(Buffer); 1357 describeCall(Frame, Out); 1358 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str(); 1359 } 1360 } 1361 1362 /// Kinds of access we can perform on an object, for diagnostics. Note that 1363 /// we consider a member function call to be a kind of access, even though 1364 /// it is not formally an access of the object, because it has (largely) the 1365 /// same set of semantic restrictions. 1366 enum AccessKinds { 1367 AK_Read, 1368 AK_Assign, 1369 AK_Increment, 1370 AK_Decrement, 1371 AK_MemberCall, 1372 AK_DynamicCast, 1373 AK_TypeId, 1374 }; 1375 1376 static bool isModification(AccessKinds AK) { 1377 switch (AK) { 1378 case AK_Read: 1379 case AK_MemberCall: 1380 case AK_DynamicCast: 1381 case AK_TypeId: 1382 return false; 1383 case AK_Assign: 1384 case AK_Increment: 1385 case AK_Decrement: 1386 return true; 1387 } 1388 llvm_unreachable("unknown access kind"); 1389 } 1390 1391 /// Is this an access per the C++ definition? 1392 static bool isFormalAccess(AccessKinds AK) { 1393 return AK == AK_Read || isModification(AK); 1394 } 1395 1396 namespace { 1397 struct ComplexValue { 1398 private: 1399 bool IsInt; 1400 1401 public: 1402 APSInt IntReal, IntImag; 1403 APFloat FloatReal, FloatImag; 1404 1405 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1406 1407 void makeComplexFloat() { IsInt = false; } 1408 bool isComplexFloat() const { return !IsInt; } 1409 APFloat &getComplexFloatReal() { return FloatReal; } 1410 APFloat &getComplexFloatImag() { return FloatImag; } 1411 1412 void makeComplexInt() { IsInt = true; } 1413 bool isComplexInt() const { return IsInt; } 1414 APSInt &getComplexIntReal() { return IntReal; } 1415 APSInt &getComplexIntImag() { return IntImag; } 1416 1417 void moveInto(APValue &v) const { 1418 if (isComplexFloat()) 1419 v = APValue(FloatReal, FloatImag); 1420 else 1421 v = APValue(IntReal, IntImag); 1422 } 1423 void setFrom(const APValue &v) { 1424 assert(v.isComplexFloat() || v.isComplexInt()); 1425 if (v.isComplexFloat()) { 1426 makeComplexFloat(); 1427 FloatReal = v.getComplexFloatReal(); 1428 FloatImag = v.getComplexFloatImag(); 1429 } else { 1430 makeComplexInt(); 1431 IntReal = v.getComplexIntReal(); 1432 IntImag = v.getComplexIntImag(); 1433 } 1434 } 1435 }; 1436 1437 struct LValue { 1438 APValue::LValueBase Base; 1439 CharUnits Offset; 1440 SubobjectDesignator Designator; 1441 bool IsNullPtr : 1; 1442 bool InvalidBase : 1; 1443 1444 const APValue::LValueBase getLValueBase() const { return Base; } 1445 CharUnits &getLValueOffset() { return Offset; } 1446 const CharUnits &getLValueOffset() const { return Offset; } 1447 SubobjectDesignator &getLValueDesignator() { return Designator; } 1448 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1449 bool isNullPointer() const { return IsNullPtr;} 1450 1451 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1452 unsigned getLValueVersion() const { return Base.getVersion(); } 1453 1454 void moveInto(APValue &V) const { 1455 if (Designator.Invalid) 1456 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1457 else { 1458 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1459 V = APValue(Base, Offset, Designator.Entries, 1460 Designator.IsOnePastTheEnd, IsNullPtr); 1461 } 1462 } 1463 void setFrom(ASTContext &Ctx, const APValue &V) { 1464 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1465 Base = V.getLValueBase(); 1466 Offset = V.getLValueOffset(); 1467 InvalidBase = false; 1468 Designator = SubobjectDesignator(Ctx, V); 1469 IsNullPtr = V.isNullPointer(); 1470 } 1471 1472 void set(APValue::LValueBase B, bool BInvalid = false) { 1473 #ifndef NDEBUG 1474 // We only allow a few types of invalid bases. Enforce that here. 1475 if (BInvalid) { 1476 const auto *E = B.get<const Expr *>(); 1477 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1478 "Unexpected type of invalid base"); 1479 } 1480 #endif 1481 1482 Base = B; 1483 Offset = CharUnits::fromQuantity(0); 1484 InvalidBase = BInvalid; 1485 Designator = SubobjectDesignator(getType(B)); 1486 IsNullPtr = false; 1487 } 1488 1489 void setNull(QualType PointerTy, uint64_t TargetVal) { 1490 Base = (Expr *)nullptr; 1491 Offset = CharUnits::fromQuantity(TargetVal); 1492 InvalidBase = false; 1493 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1494 IsNullPtr = true; 1495 } 1496 1497 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1498 set(B, true); 1499 } 1500 1501 private: 1502 // Check that this LValue is not based on a null pointer. If it is, produce 1503 // a diagnostic and mark the designator as invalid. 1504 template <typename GenDiagType> 1505 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1506 if (Designator.Invalid) 1507 return false; 1508 if (IsNullPtr) { 1509 GenDiag(); 1510 Designator.setInvalid(); 1511 return false; 1512 } 1513 return true; 1514 } 1515 1516 public: 1517 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1518 CheckSubobjectKind CSK) { 1519 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1520 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1521 }); 1522 } 1523 1524 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1525 AccessKinds AK) { 1526 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1527 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1528 }); 1529 } 1530 1531 // Check this LValue refers to an object. If not, set the designator to be 1532 // invalid and emit a diagnostic. 1533 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1534 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1535 Designator.checkSubobject(Info, E, CSK); 1536 } 1537 1538 void addDecl(EvalInfo &Info, const Expr *E, 1539 const Decl *D, bool Virtual = false) { 1540 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1541 Designator.addDeclUnchecked(D, Virtual); 1542 } 1543 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1544 if (!Designator.Entries.empty()) { 1545 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1546 Designator.setInvalid(); 1547 return; 1548 } 1549 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1550 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1551 Designator.FirstEntryIsAnUnsizedArray = true; 1552 Designator.addUnsizedArrayUnchecked(ElemTy); 1553 } 1554 } 1555 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1556 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1557 Designator.addArrayUnchecked(CAT); 1558 } 1559 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1560 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1561 Designator.addComplexUnchecked(EltTy, Imag); 1562 } 1563 void clearIsNullPointer() { 1564 IsNullPtr = false; 1565 } 1566 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1567 const APSInt &Index, CharUnits ElementSize) { 1568 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1569 // but we're not required to diagnose it and it's valid in C++.) 1570 if (!Index) 1571 return; 1572 1573 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1574 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1575 // offsets. 1576 uint64_t Offset64 = Offset.getQuantity(); 1577 uint64_t ElemSize64 = ElementSize.getQuantity(); 1578 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1579 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1580 1581 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1582 Designator.adjustIndex(Info, E, Index); 1583 clearIsNullPointer(); 1584 } 1585 void adjustOffset(CharUnits N) { 1586 Offset += N; 1587 if (N.getQuantity()) 1588 clearIsNullPointer(); 1589 } 1590 }; 1591 1592 struct MemberPtr { 1593 MemberPtr() {} 1594 explicit MemberPtr(const ValueDecl *Decl) : 1595 DeclAndIsDerivedMember(Decl, false), Path() {} 1596 1597 /// The member or (direct or indirect) field referred to by this member 1598 /// pointer, or 0 if this is a null member pointer. 1599 const ValueDecl *getDecl() const { 1600 return DeclAndIsDerivedMember.getPointer(); 1601 } 1602 /// Is this actually a member of some type derived from the relevant class? 1603 bool isDerivedMember() const { 1604 return DeclAndIsDerivedMember.getInt(); 1605 } 1606 /// Get the class which the declaration actually lives in. 1607 const CXXRecordDecl *getContainingRecord() const { 1608 return cast<CXXRecordDecl>( 1609 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1610 } 1611 1612 void moveInto(APValue &V) const { 1613 V = APValue(getDecl(), isDerivedMember(), Path); 1614 } 1615 void setFrom(const APValue &V) { 1616 assert(V.isMemberPointer()); 1617 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1618 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1619 Path.clear(); 1620 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1621 Path.insert(Path.end(), P.begin(), P.end()); 1622 } 1623 1624 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1625 /// whether the member is a member of some class derived from the class type 1626 /// of the member pointer. 1627 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1628 /// Path - The path of base/derived classes from the member declaration's 1629 /// class (exclusive) to the class type of the member pointer (inclusive). 1630 SmallVector<const CXXRecordDecl*, 4> Path; 1631 1632 /// Perform a cast towards the class of the Decl (either up or down the 1633 /// hierarchy). 1634 bool castBack(const CXXRecordDecl *Class) { 1635 assert(!Path.empty()); 1636 const CXXRecordDecl *Expected; 1637 if (Path.size() >= 2) 1638 Expected = Path[Path.size() - 2]; 1639 else 1640 Expected = getContainingRecord(); 1641 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1642 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1643 // if B does not contain the original member and is not a base or 1644 // derived class of the class containing the original member, the result 1645 // of the cast is undefined. 1646 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1647 // (D::*). We consider that to be a language defect. 1648 return false; 1649 } 1650 Path.pop_back(); 1651 return true; 1652 } 1653 /// Perform a base-to-derived member pointer cast. 1654 bool castToDerived(const CXXRecordDecl *Derived) { 1655 if (!getDecl()) 1656 return true; 1657 if (!isDerivedMember()) { 1658 Path.push_back(Derived); 1659 return true; 1660 } 1661 if (!castBack(Derived)) 1662 return false; 1663 if (Path.empty()) 1664 DeclAndIsDerivedMember.setInt(false); 1665 return true; 1666 } 1667 /// Perform a derived-to-base member pointer cast. 1668 bool castToBase(const CXXRecordDecl *Base) { 1669 if (!getDecl()) 1670 return true; 1671 if (Path.empty()) 1672 DeclAndIsDerivedMember.setInt(true); 1673 if (isDerivedMember()) { 1674 Path.push_back(Base); 1675 return true; 1676 } 1677 return castBack(Base); 1678 } 1679 }; 1680 1681 /// Compare two member pointers, which are assumed to be of the same type. 1682 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1683 if (!LHS.getDecl() || !RHS.getDecl()) 1684 return !LHS.getDecl() && !RHS.getDecl(); 1685 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1686 return false; 1687 return LHS.Path == RHS.Path; 1688 } 1689 } 1690 1691 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1692 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1693 const LValue &This, const Expr *E, 1694 bool AllowNonLiteralTypes = false); 1695 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1696 bool InvalidBaseOK = false); 1697 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1698 bool InvalidBaseOK = false); 1699 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1700 EvalInfo &Info); 1701 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1702 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1703 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1704 EvalInfo &Info); 1705 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1706 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1707 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1708 EvalInfo &Info); 1709 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1710 1711 /// Evaluate an integer or fixed point expression into an APResult. 1712 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1713 EvalInfo &Info); 1714 1715 /// Evaluate only a fixed point expression into an APResult. 1716 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1717 EvalInfo &Info); 1718 1719 //===----------------------------------------------------------------------===// 1720 // Misc utilities 1721 //===----------------------------------------------------------------------===// 1722 1723 /// A helper function to create a temporary and set an LValue. 1724 template <class KeyTy> 1725 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended, 1726 LValue &LV, CallStackFrame &Frame) { 1727 LV.set({Key, Frame.Info.CurrentCall->Index, 1728 Frame.Info.CurrentCall->getTempVersion()}); 1729 return Frame.createTemporary(Key, IsLifetimeExtended); 1730 } 1731 1732 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1733 /// preserving its value (by extending by up to one bit as needed). 1734 static void negateAsSigned(APSInt &Int) { 1735 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1736 Int = Int.extend(Int.getBitWidth() + 1); 1737 Int.setIsSigned(true); 1738 } 1739 Int = -Int; 1740 } 1741 1742 /// Produce a string describing the given constexpr call. 1743 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) { 1744 unsigned ArgIndex = 0; 1745 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) && 1746 !isa<CXXConstructorDecl>(Frame->Callee) && 1747 cast<CXXMethodDecl>(Frame->Callee)->isInstance(); 1748 1749 if (!IsMemberCall) 1750 Out << *Frame->Callee << '('; 1751 1752 if (Frame->This && IsMemberCall) { 1753 APValue Val; 1754 Frame->This->moveInto(Val); 1755 Val.printPretty(Out, Frame->Info.Ctx, 1756 Frame->This->Designator.MostDerivedType); 1757 // FIXME: Add parens around Val if needed. 1758 Out << "->" << *Frame->Callee << '('; 1759 IsMemberCall = false; 1760 } 1761 1762 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(), 1763 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) { 1764 if (ArgIndex > (unsigned)IsMemberCall) 1765 Out << ", "; 1766 1767 const ParmVarDecl *Param = *I; 1768 const APValue &Arg = Frame->Arguments[ArgIndex]; 1769 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType()); 1770 1771 if (ArgIndex == 0 && IsMemberCall) 1772 Out << "->" << *Frame->Callee << '('; 1773 } 1774 1775 Out << ')'; 1776 } 1777 1778 /// Evaluate an expression to see if it had side-effects, and discard its 1779 /// result. 1780 /// \return \c true if the caller should keep evaluating. 1781 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1782 APValue Scratch; 1783 if (!Evaluate(Scratch, Info, E)) 1784 // We don't need the value, but we might have skipped a side effect here. 1785 return Info.noteSideEffect(); 1786 return true; 1787 } 1788 1789 /// Should this call expression be treated as a string literal? 1790 static bool IsStringLiteralCall(const CallExpr *E) { 1791 unsigned Builtin = E->getBuiltinCallee(); 1792 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1793 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1794 } 1795 1796 static bool IsGlobalLValue(APValue::LValueBase B) { 1797 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1798 // constant expression of pointer type that evaluates to... 1799 1800 // ... a null pointer value, or a prvalue core constant expression of type 1801 // std::nullptr_t. 1802 if (!B) return true; 1803 1804 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1805 // ... the address of an object with static storage duration, 1806 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1807 return VD->hasGlobalStorage(); 1808 // ... the address of a function, 1809 return isa<FunctionDecl>(D); 1810 } 1811 1812 if (B.is<TypeInfoLValue>()) 1813 return true; 1814 1815 const Expr *E = B.get<const Expr*>(); 1816 switch (E->getStmtClass()) { 1817 default: 1818 return false; 1819 case Expr::CompoundLiteralExprClass: { 1820 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1821 return CLE->isFileScope() && CLE->isLValue(); 1822 } 1823 case Expr::MaterializeTemporaryExprClass: 1824 // A materialized temporary might have been lifetime-extended to static 1825 // storage duration. 1826 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1827 // A string literal has static storage duration. 1828 case Expr::StringLiteralClass: 1829 case Expr::PredefinedExprClass: 1830 case Expr::ObjCStringLiteralClass: 1831 case Expr::ObjCEncodeExprClass: 1832 case Expr::CXXUuidofExprClass: 1833 return true; 1834 case Expr::ObjCBoxedExprClass: 1835 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1836 case Expr::CallExprClass: 1837 return IsStringLiteralCall(cast<CallExpr>(E)); 1838 // For GCC compatibility, &&label has static storage duration. 1839 case Expr::AddrLabelExprClass: 1840 return true; 1841 // A Block literal expression may be used as the initialization value for 1842 // Block variables at global or local static scope. 1843 case Expr::BlockExprClass: 1844 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1845 case Expr::ImplicitValueInitExprClass: 1846 // FIXME: 1847 // We can never form an lvalue with an implicit value initialization as its 1848 // base through expression evaluation, so these only appear in one case: the 1849 // implicit variable declaration we invent when checking whether a constexpr 1850 // constructor can produce a constant expression. We must assume that such 1851 // an expression might be a global lvalue. 1852 return true; 1853 } 1854 } 1855 1856 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1857 return LVal.Base.dyn_cast<const ValueDecl*>(); 1858 } 1859 1860 static bool IsLiteralLValue(const LValue &Value) { 1861 if (Value.getLValueCallIndex()) 1862 return false; 1863 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1864 return E && !isa<MaterializeTemporaryExpr>(E); 1865 } 1866 1867 static bool IsWeakLValue(const LValue &Value) { 1868 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1869 return Decl && Decl->isWeak(); 1870 } 1871 1872 static bool isZeroSized(const LValue &Value) { 1873 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1874 if (Decl && isa<VarDecl>(Decl)) { 1875 QualType Ty = Decl->getType(); 1876 if (Ty->isArrayType()) 1877 return Ty->isIncompleteType() || 1878 Decl->getASTContext().getTypeSize(Ty) == 0; 1879 } 1880 return false; 1881 } 1882 1883 static bool HasSameBase(const LValue &A, const LValue &B) { 1884 if (!A.getLValueBase()) 1885 return !B.getLValueBase(); 1886 if (!B.getLValueBase()) 1887 return false; 1888 1889 if (A.getLValueBase().getOpaqueValue() != 1890 B.getLValueBase().getOpaqueValue()) { 1891 const Decl *ADecl = GetLValueBaseDecl(A); 1892 if (!ADecl) 1893 return false; 1894 const Decl *BDecl = GetLValueBaseDecl(B); 1895 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1896 return false; 1897 } 1898 1899 return IsGlobalLValue(A.getLValueBase()) || 1900 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1901 A.getLValueVersion() == B.getLValueVersion()); 1902 } 1903 1904 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1905 assert(Base && "no location for a null lvalue"); 1906 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1907 if (VD) 1908 Info.Note(VD->getLocation(), diag::note_declared_at); 1909 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 1910 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 1911 // We have no information to show for a typeid(T) object. 1912 } 1913 1914 /// Check that this reference or pointer core constant expression is a valid 1915 /// value for an address or reference constant expression. Return true if we 1916 /// can fold this expression, whether or not it's a constant expression. 1917 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1918 QualType Type, const LValue &LVal, 1919 Expr::ConstExprUsage Usage) { 1920 bool IsReferenceType = Type->isReferenceType(); 1921 1922 APValue::LValueBase Base = LVal.getLValueBase(); 1923 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1924 1925 // Check that the object is a global. Note that the fake 'this' object we 1926 // manufacture when checking potential constant expressions is conservatively 1927 // assumed to be global here. 1928 if (!IsGlobalLValue(Base)) { 1929 if (Info.getLangOpts().CPlusPlus11) { 1930 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1931 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1932 << IsReferenceType << !Designator.Entries.empty() 1933 << !!VD << VD; 1934 NoteLValueLocation(Info, Base); 1935 } else { 1936 Info.FFDiag(Loc); 1937 } 1938 // Don't allow references to temporaries to escape. 1939 return false; 1940 } 1941 assert((Info.checkingPotentialConstantExpression() || 1942 LVal.getLValueCallIndex() == 0) && 1943 "have call index for global lvalue"); 1944 1945 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1946 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1947 // Check if this is a thread-local variable. 1948 if (Var->getTLSKind()) 1949 return false; 1950 1951 // A dllimport variable never acts like a constant. 1952 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 1953 return false; 1954 } 1955 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1956 // __declspec(dllimport) must be handled very carefully: 1957 // We must never initialize an expression with the thunk in C++. 1958 // Doing otherwise would allow the same id-expression to yield 1959 // different addresses for the same function in different translation 1960 // units. However, this means that we must dynamically initialize the 1961 // expression with the contents of the import address table at runtime. 1962 // 1963 // The C language has no notion of ODR; furthermore, it has no notion of 1964 // dynamic initialization. This means that we are permitted to 1965 // perform initialization with the address of the thunk. 1966 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 1967 FD->hasAttr<DLLImportAttr>()) 1968 return false; 1969 } 1970 } 1971 1972 // Allow address constant expressions to be past-the-end pointers. This is 1973 // an extension: the standard requires them to point to an object. 1974 if (!IsReferenceType) 1975 return true; 1976 1977 // A reference constant expression must refer to an object. 1978 if (!Base) { 1979 // FIXME: diagnostic 1980 Info.CCEDiag(Loc); 1981 return true; 1982 } 1983 1984 // Does this refer one past the end of some object? 1985 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 1986 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1987 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 1988 << !Designator.Entries.empty() << !!VD << VD; 1989 NoteLValueLocation(Info, Base); 1990 } 1991 1992 return true; 1993 } 1994 1995 /// Member pointers are constant expressions unless they point to a 1996 /// non-virtual dllimport member function. 1997 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 1998 SourceLocation Loc, 1999 QualType Type, 2000 const APValue &Value, 2001 Expr::ConstExprUsage Usage) { 2002 const ValueDecl *Member = Value.getMemberPointerDecl(); 2003 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2004 if (!FD) 2005 return true; 2006 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2007 !FD->hasAttr<DLLImportAttr>(); 2008 } 2009 2010 /// Check that this core constant expression is of literal type, and if not, 2011 /// produce an appropriate diagnostic. 2012 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2013 const LValue *This = nullptr) { 2014 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2015 return true; 2016 2017 // C++1y: A constant initializer for an object o [...] may also invoke 2018 // constexpr constructors for o and its subobjects even if those objects 2019 // are of non-literal class types. 2020 // 2021 // C++11 missed this detail for aggregates, so classes like this: 2022 // struct foo_t { union { int i; volatile int j; } u; }; 2023 // are not (obviously) initializable like so: 2024 // __attribute__((__require_constant_initialization__)) 2025 // static const foo_t x = {{0}}; 2026 // because "i" is a subobject with non-literal initialization (due to the 2027 // volatile member of the union). See: 2028 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2029 // Therefore, we use the C++1y behavior. 2030 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2031 return true; 2032 2033 // Prvalue constant expressions must be of literal types. 2034 if (Info.getLangOpts().CPlusPlus11) 2035 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2036 << E->getType(); 2037 else 2038 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2039 return false; 2040 } 2041 2042 /// Check that this core constant expression value is a valid value for a 2043 /// constant expression. If not, report an appropriate diagnostic. Does not 2044 /// check that the expression is of literal type. 2045 static bool 2046 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2047 const APValue &Value, 2048 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen, 2049 SourceLocation SubobjectLoc = SourceLocation()) { 2050 if (!Value.hasValue()) { 2051 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2052 << true << Type; 2053 if (SubobjectLoc.isValid()) 2054 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2055 return false; 2056 } 2057 2058 // We allow _Atomic(T) to be initialized from anything that T can be 2059 // initialized from. 2060 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2061 Type = AT->getValueType(); 2062 2063 // Core issue 1454: For a literal constant expression of array or class type, 2064 // each subobject of its value shall have been initialized by a constant 2065 // expression. 2066 if (Value.isArray()) { 2067 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2068 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2069 if (!CheckConstantExpression(Info, DiagLoc, EltTy, 2070 Value.getArrayInitializedElt(I), Usage, 2071 SubobjectLoc)) 2072 return false; 2073 } 2074 if (!Value.hasArrayFiller()) 2075 return true; 2076 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(), 2077 Usage, SubobjectLoc); 2078 } 2079 if (Value.isUnion() && Value.getUnionField()) { 2080 return CheckConstantExpression(Info, DiagLoc, 2081 Value.getUnionField()->getType(), 2082 Value.getUnionValue(), Usage, 2083 Value.getUnionField()->getLocation()); 2084 } 2085 if (Value.isStruct()) { 2086 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2087 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2088 unsigned BaseIndex = 0; 2089 for (const CXXBaseSpecifier &BS : CD->bases()) { 2090 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(), 2091 Value.getStructBase(BaseIndex), Usage, 2092 BS.getBeginLoc())) 2093 return false; 2094 ++BaseIndex; 2095 } 2096 } 2097 for (const auto *I : RD->fields()) { 2098 if (I->isUnnamedBitfield()) 2099 continue; 2100 2101 if (!CheckConstantExpression(Info, DiagLoc, I->getType(), 2102 Value.getStructField(I->getFieldIndex()), 2103 Usage, I->getLocation())) 2104 return false; 2105 } 2106 } 2107 2108 if (Value.isLValue()) { 2109 LValue LVal; 2110 LVal.setFrom(Info.Ctx, Value); 2111 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage); 2112 } 2113 2114 if (Value.isMemberPointer()) 2115 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2116 2117 // Everything else is fine. 2118 return true; 2119 } 2120 2121 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2122 // A null base expression indicates a null pointer. These are always 2123 // evaluatable, and they are false unless the offset is zero. 2124 if (!Value.getLValueBase()) { 2125 Result = !Value.getLValueOffset().isZero(); 2126 return true; 2127 } 2128 2129 // We have a non-null base. These are generally known to be true, but if it's 2130 // a weak declaration it can be null at runtime. 2131 Result = true; 2132 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2133 return !Decl || !Decl->isWeak(); 2134 } 2135 2136 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2137 switch (Val.getKind()) { 2138 case APValue::None: 2139 case APValue::Indeterminate: 2140 return false; 2141 case APValue::Int: 2142 Result = Val.getInt().getBoolValue(); 2143 return true; 2144 case APValue::FixedPoint: 2145 Result = Val.getFixedPoint().getBoolValue(); 2146 return true; 2147 case APValue::Float: 2148 Result = !Val.getFloat().isZero(); 2149 return true; 2150 case APValue::ComplexInt: 2151 Result = Val.getComplexIntReal().getBoolValue() || 2152 Val.getComplexIntImag().getBoolValue(); 2153 return true; 2154 case APValue::ComplexFloat: 2155 Result = !Val.getComplexFloatReal().isZero() || 2156 !Val.getComplexFloatImag().isZero(); 2157 return true; 2158 case APValue::LValue: 2159 return EvalPointerValueAsBool(Val, Result); 2160 case APValue::MemberPointer: 2161 Result = Val.getMemberPointerDecl(); 2162 return true; 2163 case APValue::Vector: 2164 case APValue::Array: 2165 case APValue::Struct: 2166 case APValue::Union: 2167 case APValue::AddrLabelDiff: 2168 return false; 2169 } 2170 2171 llvm_unreachable("unknown APValue kind"); 2172 } 2173 2174 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2175 EvalInfo &Info) { 2176 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2177 APValue Val; 2178 if (!Evaluate(Val, Info, E)) 2179 return false; 2180 return HandleConversionToBool(Val, Result); 2181 } 2182 2183 template<typename T> 2184 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2185 const T &SrcValue, QualType DestType) { 2186 Info.CCEDiag(E, diag::note_constexpr_overflow) 2187 << SrcValue << DestType; 2188 return Info.noteUndefinedBehavior(); 2189 } 2190 2191 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2192 QualType SrcType, const APFloat &Value, 2193 QualType DestType, APSInt &Result) { 2194 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2195 // Determine whether we are converting to unsigned or signed. 2196 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2197 2198 Result = APSInt(DestWidth, !DestSigned); 2199 bool ignored; 2200 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2201 & APFloat::opInvalidOp) 2202 return HandleOverflow(Info, E, Value, DestType); 2203 return true; 2204 } 2205 2206 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2207 QualType SrcType, QualType DestType, 2208 APFloat &Result) { 2209 APFloat Value = Result; 2210 bool ignored; 2211 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2212 APFloat::rmNearestTiesToEven, &ignored) 2213 & APFloat::opOverflow) 2214 return HandleOverflow(Info, E, Value, DestType); 2215 return true; 2216 } 2217 2218 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2219 QualType DestType, QualType SrcType, 2220 const APSInt &Value) { 2221 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2222 // Figure out if this is a truncate, extend or noop cast. 2223 // If the input is signed, do a sign extend, noop, or truncate. 2224 APSInt Result = Value.extOrTrunc(DestWidth); 2225 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2226 if (DestType->isBooleanType()) 2227 Result = Value.getBoolValue(); 2228 return Result; 2229 } 2230 2231 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2232 QualType SrcType, const APSInt &Value, 2233 QualType DestType, APFloat &Result) { 2234 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2235 if (Result.convertFromAPInt(Value, Value.isSigned(), 2236 APFloat::rmNearestTiesToEven) 2237 & APFloat::opOverflow) 2238 return HandleOverflow(Info, E, Value, DestType); 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()) { 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 if (LHS.isNegative()) 2394 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2395 else if (LHS.countLeadingZeros() < SA) 2396 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2397 } 2398 Result = LHS << SA; 2399 return true; 2400 } 2401 case BO_Shr: { 2402 if (Info.getLangOpts().OpenCL) 2403 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2404 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2405 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2406 RHS.isUnsigned()); 2407 else if (RHS.isSigned() && RHS.isNegative()) { 2408 // During constant-folding, a negative shift is an opposite shift. Such a 2409 // shift is not a constant expression. 2410 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2411 RHS = -RHS; 2412 goto shift_left; 2413 } 2414 shift_right: 2415 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2416 // shifted type. 2417 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2418 if (SA != RHS) 2419 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2420 << RHS << E->getType() << LHS.getBitWidth(); 2421 Result = LHS >> SA; 2422 return true; 2423 } 2424 2425 case BO_LT: Result = LHS < RHS; return true; 2426 case BO_GT: Result = LHS > RHS; return true; 2427 case BO_LE: Result = LHS <= RHS; return true; 2428 case BO_GE: Result = LHS >= RHS; return true; 2429 case BO_EQ: Result = LHS == RHS; return true; 2430 case BO_NE: Result = LHS != RHS; return true; 2431 case BO_Cmp: 2432 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2433 } 2434 } 2435 2436 /// Perform the given binary floating-point operation, in-place, on LHS. 2437 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2438 APFloat &LHS, BinaryOperatorKind Opcode, 2439 const APFloat &RHS) { 2440 switch (Opcode) { 2441 default: 2442 Info.FFDiag(E); 2443 return false; 2444 case BO_Mul: 2445 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2446 break; 2447 case BO_Add: 2448 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2449 break; 2450 case BO_Sub: 2451 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2452 break; 2453 case BO_Div: 2454 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2455 break; 2456 } 2457 2458 if (LHS.isInfinity() || LHS.isNaN()) { 2459 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2460 return Info.noteUndefinedBehavior(); 2461 } 2462 return true; 2463 } 2464 2465 /// Cast an lvalue referring to a base subobject to a derived class, by 2466 /// truncating the lvalue's path to the given length. 2467 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2468 const RecordDecl *TruncatedType, 2469 unsigned TruncatedElements) { 2470 SubobjectDesignator &D = Result.Designator; 2471 2472 // Check we actually point to a derived class object. 2473 if (TruncatedElements == D.Entries.size()) 2474 return true; 2475 assert(TruncatedElements >= D.MostDerivedPathLength && 2476 "not casting to a derived class"); 2477 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2478 return false; 2479 2480 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2481 const RecordDecl *RD = TruncatedType; 2482 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2483 if (RD->isInvalidDecl()) return false; 2484 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2485 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2486 if (isVirtualBaseClass(D.Entries[I])) 2487 Result.Offset -= Layout.getVBaseClassOffset(Base); 2488 else 2489 Result.Offset -= Layout.getBaseClassOffset(Base); 2490 RD = Base; 2491 } 2492 D.Entries.resize(TruncatedElements); 2493 return true; 2494 } 2495 2496 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2497 const CXXRecordDecl *Derived, 2498 const CXXRecordDecl *Base, 2499 const ASTRecordLayout *RL = nullptr) { 2500 if (!RL) { 2501 if (Derived->isInvalidDecl()) return false; 2502 RL = &Info.Ctx.getASTRecordLayout(Derived); 2503 } 2504 2505 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2506 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2507 return true; 2508 } 2509 2510 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2511 const CXXRecordDecl *DerivedDecl, 2512 const CXXBaseSpecifier *Base) { 2513 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2514 2515 if (!Base->isVirtual()) 2516 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2517 2518 SubobjectDesignator &D = Obj.Designator; 2519 if (D.Invalid) 2520 return false; 2521 2522 // Extract most-derived object and corresponding type. 2523 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2524 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2525 return false; 2526 2527 // Find the virtual base class. 2528 if (DerivedDecl->isInvalidDecl()) return false; 2529 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2530 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2531 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2532 return true; 2533 } 2534 2535 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2536 QualType Type, LValue &Result) { 2537 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2538 PathE = E->path_end(); 2539 PathI != PathE; ++PathI) { 2540 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2541 *PathI)) 2542 return false; 2543 Type = (*PathI)->getType(); 2544 } 2545 return true; 2546 } 2547 2548 /// Cast an lvalue referring to a derived class to a known base subobject. 2549 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2550 const CXXRecordDecl *DerivedRD, 2551 const CXXRecordDecl *BaseRD) { 2552 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2553 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2554 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2555 llvm_unreachable("Class must be derived from the passed in base class!"); 2556 2557 for (CXXBasePathElement &Elem : Paths.front()) 2558 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2559 return false; 2560 return true; 2561 } 2562 2563 /// Update LVal to refer to the given field, which must be a member of the type 2564 /// currently described by LVal. 2565 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2566 const FieldDecl *FD, 2567 const ASTRecordLayout *RL = nullptr) { 2568 if (!RL) { 2569 if (FD->getParent()->isInvalidDecl()) return false; 2570 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2571 } 2572 2573 unsigned I = FD->getFieldIndex(); 2574 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2575 LVal.addDecl(Info, E, FD); 2576 return true; 2577 } 2578 2579 /// Update LVal to refer to the given indirect field. 2580 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2581 LValue &LVal, 2582 const IndirectFieldDecl *IFD) { 2583 for (const auto *C : IFD->chain()) 2584 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2585 return false; 2586 return true; 2587 } 2588 2589 /// Get the size of the given type in char units. 2590 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2591 QualType Type, CharUnits &Size) { 2592 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2593 // extension. 2594 if (Type->isVoidType() || Type->isFunctionType()) { 2595 Size = CharUnits::One(); 2596 return true; 2597 } 2598 2599 if (Type->isDependentType()) { 2600 Info.FFDiag(Loc); 2601 return false; 2602 } 2603 2604 if (!Type->isConstantSizeType()) { 2605 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2606 // FIXME: Better diagnostic. 2607 Info.FFDiag(Loc); 2608 return false; 2609 } 2610 2611 Size = Info.Ctx.getTypeSizeInChars(Type); 2612 return true; 2613 } 2614 2615 /// Update a pointer value to model pointer arithmetic. 2616 /// \param Info - Information about the ongoing evaluation. 2617 /// \param E - The expression being evaluated, for diagnostic purposes. 2618 /// \param LVal - The pointer value to be updated. 2619 /// \param EltTy - The pointee type represented by LVal. 2620 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2621 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2622 LValue &LVal, QualType EltTy, 2623 APSInt Adjustment) { 2624 CharUnits SizeOfPointee; 2625 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2626 return false; 2627 2628 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2629 return true; 2630 } 2631 2632 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2633 LValue &LVal, QualType EltTy, 2634 int64_t Adjustment) { 2635 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2636 APSInt::get(Adjustment)); 2637 } 2638 2639 /// Update an lvalue to refer to a component of a complex number. 2640 /// \param Info - Information about the ongoing evaluation. 2641 /// \param LVal - The lvalue to be updated. 2642 /// \param EltTy - The complex number's component type. 2643 /// \param Imag - False for the real component, true for the imaginary. 2644 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2645 LValue &LVal, QualType EltTy, 2646 bool Imag) { 2647 if (Imag) { 2648 CharUnits SizeOfComponent; 2649 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2650 return false; 2651 LVal.Offset += SizeOfComponent; 2652 } 2653 LVal.addComplex(Info, E, EltTy, Imag); 2654 return true; 2655 } 2656 2657 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 2658 QualType Type, const LValue &LVal, 2659 APValue &RVal); 2660 2661 /// Try to evaluate the initializer for a variable declaration. 2662 /// 2663 /// \param Info Information about the ongoing evaluation. 2664 /// \param E An expression to be used when printing diagnostics. 2665 /// \param VD The variable whose initializer should be obtained. 2666 /// \param Frame The frame in which the variable was created. Must be null 2667 /// if this variable is not local to the evaluation. 2668 /// \param Result Filled in with a pointer to the value of the variable. 2669 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2670 const VarDecl *VD, CallStackFrame *Frame, 2671 APValue *&Result, const LValue *LVal) { 2672 2673 // If this is a parameter to an active constexpr function call, perform 2674 // argument substitution. 2675 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2676 // Assume arguments of a potential constant expression are unknown 2677 // constant expressions. 2678 if (Info.checkingPotentialConstantExpression()) 2679 return false; 2680 if (!Frame || !Frame->Arguments) { 2681 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2682 return false; 2683 } 2684 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2685 return true; 2686 } 2687 2688 // If this is a local variable, dig out its value. 2689 if (Frame) { 2690 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 2691 : Frame->getCurrentTemporary(VD); 2692 if (!Result) { 2693 // Assume variables referenced within a lambda's call operator that were 2694 // not declared within the call operator are captures and during checking 2695 // of a potential constant expression, assume they are unknown constant 2696 // expressions. 2697 assert(isLambdaCallOperator(Frame->Callee) && 2698 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2699 "missing value for local variable"); 2700 if (Info.checkingPotentialConstantExpression()) 2701 return false; 2702 // FIXME: implement capture evaluation during constant expr evaluation. 2703 Info.FFDiag(E->getBeginLoc(), 2704 diag::note_unimplemented_constexpr_lambda_feature_ast) 2705 << "captures not currently allowed"; 2706 return false; 2707 } 2708 return true; 2709 } 2710 2711 // Dig out the initializer, and use the declaration which it's attached to. 2712 const Expr *Init = VD->getAnyInitializer(VD); 2713 if (!Init || Init->isValueDependent()) { 2714 // If we're checking a potential constant expression, the variable could be 2715 // initialized later. 2716 if (!Info.checkingPotentialConstantExpression()) 2717 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2718 return false; 2719 } 2720 2721 // If we're currently evaluating the initializer of this declaration, use that 2722 // in-flight value. 2723 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2724 Result = Info.EvaluatingDeclValue; 2725 return true; 2726 } 2727 2728 // Never evaluate the initializer of a weak variable. We can't be sure that 2729 // this is the definition which will be used. 2730 if (VD->isWeak()) { 2731 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2732 return false; 2733 } 2734 2735 // Check that we can fold the initializer. In C++, we will have already done 2736 // this in the cases where it matters for conformance. 2737 SmallVector<PartialDiagnosticAt, 8> Notes; 2738 if (!VD->evaluateValue(Notes)) { 2739 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2740 Notes.size() + 1) << VD; 2741 Info.Note(VD->getLocation(), diag::note_declared_at); 2742 Info.addNotes(Notes); 2743 return false; 2744 } else if (!VD->checkInitIsICE()) { 2745 Info.CCEDiag(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 } 2750 2751 Result = VD->getEvaluatedValue(); 2752 return true; 2753 } 2754 2755 static bool IsConstNonVolatile(QualType T) { 2756 Qualifiers Quals = T.getQualifiers(); 2757 return Quals.hasConst() && !Quals.hasVolatile(); 2758 } 2759 2760 /// Get the base index of the given base class within an APValue representing 2761 /// the given derived class. 2762 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2763 const CXXRecordDecl *Base) { 2764 Base = Base->getCanonicalDecl(); 2765 unsigned Index = 0; 2766 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2767 E = Derived->bases_end(); I != E; ++I, ++Index) { 2768 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2769 return Index; 2770 } 2771 2772 llvm_unreachable("base class missing from derived class's bases list"); 2773 } 2774 2775 /// Extract the value of a character from a string literal. 2776 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2777 uint64_t Index) { 2778 assert(!isa<SourceLocExpr>(Lit) && 2779 "SourceLocExpr should have already been converted to a StringLiteral"); 2780 2781 // FIXME: Support MakeStringConstant 2782 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2783 std::string Str; 2784 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2785 assert(Index <= Str.size() && "Index too large"); 2786 return APSInt::getUnsigned(Str.c_str()[Index]); 2787 } 2788 2789 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2790 Lit = PE->getFunctionName(); 2791 const StringLiteral *S = cast<StringLiteral>(Lit); 2792 const ConstantArrayType *CAT = 2793 Info.Ctx.getAsConstantArrayType(S->getType()); 2794 assert(CAT && "string literal isn't an array"); 2795 QualType CharType = CAT->getElementType(); 2796 assert(CharType->isIntegerType() && "unexpected character type"); 2797 2798 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2799 CharType->isUnsignedIntegerType()); 2800 if (Index < S->getLength()) 2801 Value = S->getCodeUnit(Index); 2802 return Value; 2803 } 2804 2805 // Expand a string literal into an array of characters. 2806 // 2807 // FIXME: This is inefficient; we should probably introduce something similar 2808 // to the LLVM ConstantDataArray to make this cheaper. 2809 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 2810 APValue &Result) { 2811 const ConstantArrayType *CAT = 2812 Info.Ctx.getAsConstantArrayType(S->getType()); 2813 assert(CAT && "string literal isn't an array"); 2814 QualType CharType = CAT->getElementType(); 2815 assert(CharType->isIntegerType() && "unexpected character type"); 2816 2817 unsigned Elts = CAT->getSize().getZExtValue(); 2818 Result = APValue(APValue::UninitArray(), 2819 std::min(S->getLength(), Elts), Elts); 2820 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2821 CharType->isUnsignedIntegerType()); 2822 if (Result.hasArrayFiller()) 2823 Result.getArrayFiller() = APValue(Value); 2824 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2825 Value = S->getCodeUnit(I); 2826 Result.getArrayInitializedElt(I) = APValue(Value); 2827 } 2828 } 2829 2830 // Expand an array so that it has more than Index filled elements. 2831 static void expandArray(APValue &Array, unsigned Index) { 2832 unsigned Size = Array.getArraySize(); 2833 assert(Index < Size); 2834 2835 // Always at least double the number of elements for which we store a value. 2836 unsigned OldElts = Array.getArrayInitializedElts(); 2837 unsigned NewElts = std::max(Index+1, OldElts * 2); 2838 NewElts = std::min(Size, std::max(NewElts, 8u)); 2839 2840 // Copy the data across. 2841 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2842 for (unsigned I = 0; I != OldElts; ++I) 2843 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2844 for (unsigned I = OldElts; I != NewElts; ++I) 2845 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2846 if (NewValue.hasArrayFiller()) 2847 NewValue.getArrayFiller() = Array.getArrayFiller(); 2848 Array.swap(NewValue); 2849 } 2850 2851 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2852 /// conversion. If it's of class type, we may assume that the copy operation 2853 /// is trivial. Note that this is never true for a union type with fields 2854 /// (because the copy always "reads" the active member) and always true for 2855 /// a non-class type. 2856 static bool isReadByLvalueToRvalueConversion(QualType T) { 2857 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2858 if (!RD || (RD->isUnion() && !RD->field_empty())) 2859 return true; 2860 if (RD->isEmpty()) 2861 return false; 2862 2863 for (auto *Field : RD->fields()) 2864 if (isReadByLvalueToRvalueConversion(Field->getType())) 2865 return true; 2866 2867 for (auto &BaseSpec : RD->bases()) 2868 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2869 return true; 2870 2871 return false; 2872 } 2873 2874 /// Diagnose an attempt to read from any unreadable field within the specified 2875 /// type, which might be a class type. 2876 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E, 2877 QualType T) { 2878 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2879 if (!RD) 2880 return false; 2881 2882 if (!RD->hasMutableFields()) 2883 return false; 2884 2885 for (auto *Field : RD->fields()) { 2886 // If we're actually going to read this field in some way, then it can't 2887 // be mutable. If we're in a union, then assigning to a mutable field 2888 // (even an empty one) can change the active member, so that's not OK. 2889 // FIXME: Add core issue number for the union case. 2890 if (Field->isMutable() && 2891 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2892 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field; 2893 Info.Note(Field->getLocation(), diag::note_declared_at); 2894 return true; 2895 } 2896 2897 if (diagnoseUnreadableFields(Info, E, Field->getType())) 2898 return true; 2899 } 2900 2901 for (auto &BaseSpec : RD->bases()) 2902 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType())) 2903 return true; 2904 2905 // All mutable fields were empty, and thus not actually read. 2906 return false; 2907 } 2908 2909 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 2910 APValue::LValueBase Base) { 2911 // A temporary we created. 2912 if (Base.getCallIndex()) 2913 return true; 2914 2915 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 2916 if (!Evaluating) 2917 return false; 2918 2919 // The variable whose initializer we're evaluating. 2920 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>()) 2921 if (declaresSameEntity(Evaluating, BaseD)) 2922 return true; 2923 2924 // A temporary lifetime-extended by the variable whose initializer we're 2925 // evaluating. 2926 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 2927 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 2928 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating)) 2929 return true; 2930 2931 return false; 2932 } 2933 2934 namespace { 2935 /// A handle to a complete object (an object that is not a subobject of 2936 /// another object). 2937 struct CompleteObject { 2938 /// The identity of the object. 2939 APValue::LValueBase Base; 2940 /// The value of the complete object. 2941 APValue *Value; 2942 /// The type of the complete object. 2943 QualType Type; 2944 2945 CompleteObject() : Value(nullptr) {} 2946 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 2947 : Base(Base), Value(Value), Type(Type) {} 2948 2949 bool mayReadMutableMembers(EvalInfo &Info) const { 2950 // In C++14 onwards, it is permitted to read a mutable member whose 2951 // lifetime began within the evaluation. 2952 // FIXME: Should we also allow this in C++11? 2953 if (!Info.getLangOpts().CPlusPlus14) 2954 return false; 2955 return lifetimeStartedInEvaluation(Info, Base); 2956 } 2957 2958 explicit operator bool() const { return !Type.isNull(); } 2959 }; 2960 } // end anonymous namespace 2961 2962 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 2963 bool IsMutable = false) { 2964 // C++ [basic.type.qualifier]p1: 2965 // - A const object is an object of type const T or a non-mutable subobject 2966 // of a const object. 2967 if (ObjType.isConstQualified() && !IsMutable) 2968 SubobjType.addConst(); 2969 // - A volatile object is an object of type const T or a subobject of a 2970 // volatile object. 2971 if (ObjType.isVolatileQualified()) 2972 SubobjType.addVolatile(); 2973 return SubobjType; 2974 } 2975 2976 /// Find the designated sub-object of an rvalue. 2977 template<typename SubobjectHandler> 2978 typename SubobjectHandler::result_type 2979 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 2980 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 2981 if (Sub.Invalid) 2982 // A diagnostic will have already been produced. 2983 return handler.failed(); 2984 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 2985 if (Info.getLangOpts().CPlusPlus11) 2986 Info.FFDiag(E, Sub.isOnePastTheEnd() 2987 ? diag::note_constexpr_access_past_end 2988 : diag::note_constexpr_access_unsized_array) 2989 << handler.AccessKind; 2990 else 2991 Info.FFDiag(E); 2992 return handler.failed(); 2993 } 2994 2995 APValue *O = Obj.Value; 2996 QualType ObjType = Obj.Type; 2997 const FieldDecl *LastField = nullptr; 2998 const FieldDecl *VolatileField = nullptr; 2999 3000 // Walk the designator's path to find the subobject. 3001 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3002 // Reading an indeterminate value is undefined, but assigning over one is OK. 3003 if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) { 3004 if (!Info.checkingPotentialConstantExpression()) 3005 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3006 << handler.AccessKind << O->isIndeterminate(); 3007 return handler.failed(); 3008 } 3009 3010 // C++ [class.ctor]p5: 3011 // const and volatile semantics are not applied on an object under 3012 // construction. 3013 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3014 ObjType->isRecordType() && 3015 Info.isEvaluatingConstructor( 3016 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3017 Sub.Entries.begin() + I)) != 3018 ConstructionPhase::None) { 3019 ObjType = Info.Ctx.getCanonicalType(ObjType); 3020 ObjType.removeLocalConst(); 3021 ObjType.removeLocalVolatile(); 3022 } 3023 3024 // If this is our last pass, check that the final object type is OK. 3025 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3026 // Accesses to volatile objects are prohibited. 3027 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3028 if (Info.getLangOpts().CPlusPlus) { 3029 int DiagKind; 3030 SourceLocation Loc; 3031 const NamedDecl *Decl = nullptr; 3032 if (VolatileField) { 3033 DiagKind = 2; 3034 Loc = VolatileField->getLocation(); 3035 Decl = VolatileField; 3036 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3037 DiagKind = 1; 3038 Loc = VD->getLocation(); 3039 Decl = VD; 3040 } else { 3041 DiagKind = 0; 3042 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3043 Loc = E->getExprLoc(); 3044 } 3045 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3046 << handler.AccessKind << DiagKind << Decl; 3047 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3048 } else { 3049 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3050 } 3051 return handler.failed(); 3052 } 3053 3054 // If we are reading an object of class type, there may still be more 3055 // things we need to check: if there are any mutable subobjects, we 3056 // cannot perform this read. (This only happens when performing a trivial 3057 // copy or assignment.) 3058 if (ObjType->isRecordType() && handler.AccessKind == AK_Read && 3059 !Obj.mayReadMutableMembers(Info) && 3060 diagnoseUnreadableFields(Info, E, ObjType)) 3061 return handler.failed(); 3062 } 3063 3064 if (I == N) { 3065 if (!handler.found(*O, ObjType)) 3066 return false; 3067 3068 // If we modified a bit-field, truncate it to the right width. 3069 if (isModification(handler.AccessKind) && 3070 LastField && LastField->isBitField() && 3071 !truncateBitfieldValue(Info, E, *O, LastField)) 3072 return false; 3073 3074 return true; 3075 } 3076 3077 LastField = nullptr; 3078 if (ObjType->isArrayType()) { 3079 // Next subobject is an array element. 3080 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3081 assert(CAT && "vla in literal type?"); 3082 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3083 if (CAT->getSize().ule(Index)) { 3084 // Note, it should not be possible to form a pointer with a valid 3085 // designator which points more than one past the end of the array. 3086 if (Info.getLangOpts().CPlusPlus11) 3087 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3088 << handler.AccessKind; 3089 else 3090 Info.FFDiag(E); 3091 return handler.failed(); 3092 } 3093 3094 ObjType = CAT->getElementType(); 3095 3096 if (O->getArrayInitializedElts() > Index) 3097 O = &O->getArrayInitializedElt(Index); 3098 else if (handler.AccessKind != AK_Read) { 3099 expandArray(*O, Index); 3100 O = &O->getArrayInitializedElt(Index); 3101 } else 3102 O = &O->getArrayFiller(); 3103 } else if (ObjType->isAnyComplexType()) { 3104 // Next subobject is a complex number. 3105 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3106 if (Index > 1) { 3107 if (Info.getLangOpts().CPlusPlus11) 3108 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3109 << handler.AccessKind; 3110 else 3111 Info.FFDiag(E); 3112 return handler.failed(); 3113 } 3114 3115 ObjType = getSubobjectType( 3116 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3117 3118 assert(I == N - 1 && "extracting subobject of scalar?"); 3119 if (O->isComplexInt()) { 3120 return handler.found(Index ? O->getComplexIntImag() 3121 : O->getComplexIntReal(), ObjType); 3122 } else { 3123 assert(O->isComplexFloat()); 3124 return handler.found(Index ? O->getComplexFloatImag() 3125 : O->getComplexFloatReal(), ObjType); 3126 } 3127 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3128 if (Field->isMutable() && handler.AccessKind == AK_Read && 3129 !Obj.mayReadMutableMembers(Info)) { 3130 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) 3131 << Field; 3132 Info.Note(Field->getLocation(), diag::note_declared_at); 3133 return handler.failed(); 3134 } 3135 3136 // Next subobject is a class, struct or union field. 3137 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3138 if (RD->isUnion()) { 3139 const FieldDecl *UnionField = O->getUnionField(); 3140 if (!UnionField || 3141 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3142 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3143 << handler.AccessKind << Field << !UnionField << UnionField; 3144 return handler.failed(); 3145 } 3146 O = &O->getUnionValue(); 3147 } else 3148 O = &O->getStructField(Field->getFieldIndex()); 3149 3150 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3151 LastField = Field; 3152 if (Field->getType().isVolatileQualified()) 3153 VolatileField = Field; 3154 } else { 3155 // Next subobject is a base class. 3156 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3157 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3158 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3159 3160 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3161 } 3162 } 3163 } 3164 3165 namespace { 3166 struct ExtractSubobjectHandler { 3167 EvalInfo &Info; 3168 APValue &Result; 3169 3170 static const AccessKinds AccessKind = AK_Read; 3171 3172 typedef bool result_type; 3173 bool failed() { return false; } 3174 bool found(APValue &Subobj, QualType SubobjType) { 3175 Result = Subobj; 3176 return true; 3177 } 3178 bool found(APSInt &Value, QualType SubobjType) { 3179 Result = APValue(Value); 3180 return true; 3181 } 3182 bool found(APFloat &Value, QualType SubobjType) { 3183 Result = APValue(Value); 3184 return true; 3185 } 3186 }; 3187 } // end anonymous namespace 3188 3189 const AccessKinds ExtractSubobjectHandler::AccessKind; 3190 3191 /// Extract the designated sub-object of an rvalue. 3192 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3193 const CompleteObject &Obj, 3194 const SubobjectDesignator &Sub, 3195 APValue &Result) { 3196 ExtractSubobjectHandler Handler = { Info, Result }; 3197 return findSubobject(Info, E, Obj, Sub, Handler); 3198 } 3199 3200 namespace { 3201 struct ModifySubobjectHandler { 3202 EvalInfo &Info; 3203 APValue &NewVal; 3204 const Expr *E; 3205 3206 typedef bool result_type; 3207 static const AccessKinds AccessKind = AK_Assign; 3208 3209 bool checkConst(QualType QT) { 3210 // Assigning to a const object has undefined behavior. 3211 if (QT.isConstQualified()) { 3212 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3213 return false; 3214 } 3215 return true; 3216 } 3217 3218 bool failed() { return false; } 3219 bool found(APValue &Subobj, QualType SubobjType) { 3220 if (!checkConst(SubobjType)) 3221 return false; 3222 // We've been given ownership of NewVal, so just swap it in. 3223 Subobj.swap(NewVal); 3224 return true; 3225 } 3226 bool found(APSInt &Value, QualType SubobjType) { 3227 if (!checkConst(SubobjType)) 3228 return false; 3229 if (!NewVal.isInt()) { 3230 // Maybe trying to write a cast pointer value into a complex? 3231 Info.FFDiag(E); 3232 return false; 3233 } 3234 Value = NewVal.getInt(); 3235 return true; 3236 } 3237 bool found(APFloat &Value, QualType SubobjType) { 3238 if (!checkConst(SubobjType)) 3239 return false; 3240 Value = NewVal.getFloat(); 3241 return true; 3242 } 3243 }; 3244 } // end anonymous namespace 3245 3246 const AccessKinds ModifySubobjectHandler::AccessKind; 3247 3248 /// Update the designated sub-object of an rvalue to the given value. 3249 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3250 const CompleteObject &Obj, 3251 const SubobjectDesignator &Sub, 3252 APValue &NewVal) { 3253 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3254 return findSubobject(Info, E, Obj, Sub, Handler); 3255 } 3256 3257 /// Find the position where two subobject designators diverge, or equivalently 3258 /// the length of the common initial subsequence. 3259 static unsigned FindDesignatorMismatch(QualType ObjType, 3260 const SubobjectDesignator &A, 3261 const SubobjectDesignator &B, 3262 bool &WasArrayIndex) { 3263 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3264 for (/**/; I != N; ++I) { 3265 if (!ObjType.isNull() && 3266 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3267 // Next subobject is an array element. 3268 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3269 WasArrayIndex = true; 3270 return I; 3271 } 3272 if (ObjType->isAnyComplexType()) 3273 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3274 else 3275 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3276 } else { 3277 if (A.Entries[I].getAsBaseOrMember() != 3278 B.Entries[I].getAsBaseOrMember()) { 3279 WasArrayIndex = false; 3280 return I; 3281 } 3282 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3283 // Next subobject is a field. 3284 ObjType = FD->getType(); 3285 else 3286 // Next subobject is a base class. 3287 ObjType = QualType(); 3288 } 3289 } 3290 WasArrayIndex = false; 3291 return I; 3292 } 3293 3294 /// Determine whether the given subobject designators refer to elements of the 3295 /// same array object. 3296 static bool AreElementsOfSameArray(QualType ObjType, 3297 const SubobjectDesignator &A, 3298 const SubobjectDesignator &B) { 3299 if (A.Entries.size() != B.Entries.size()) 3300 return false; 3301 3302 bool IsArray = A.MostDerivedIsArrayElement; 3303 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3304 // A is a subobject of the array element. 3305 return false; 3306 3307 // If A (and B) designates an array element, the last entry will be the array 3308 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3309 // of length 1' case, and the entire path must match. 3310 bool WasArrayIndex; 3311 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3312 return CommonLength >= A.Entries.size() - IsArray; 3313 } 3314 3315 /// Find the complete object to which an LValue refers. 3316 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3317 AccessKinds AK, const LValue &LVal, 3318 QualType LValType) { 3319 if (LVal.InvalidBase) { 3320 Info.FFDiag(E); 3321 return CompleteObject(); 3322 } 3323 3324 if (!LVal.Base) { 3325 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3326 return CompleteObject(); 3327 } 3328 3329 CallStackFrame *Frame = nullptr; 3330 unsigned Depth = 0; 3331 if (LVal.getLValueCallIndex()) { 3332 std::tie(Frame, Depth) = 3333 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3334 if (!Frame) { 3335 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3336 << AK << LVal.Base.is<const ValueDecl*>(); 3337 NoteLValueLocation(Info, LVal.Base); 3338 return CompleteObject(); 3339 } 3340 } 3341 3342 bool IsAccess = isFormalAccess(AK); 3343 3344 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3345 // is not a constant expression (even if the object is non-volatile). We also 3346 // apply this rule to C++98, in order to conform to the expected 'volatile' 3347 // semantics. 3348 if (IsAccess && LValType.isVolatileQualified()) { 3349 if (Info.getLangOpts().CPlusPlus) 3350 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3351 << AK << LValType; 3352 else 3353 Info.FFDiag(E); 3354 return CompleteObject(); 3355 } 3356 3357 // Compute value storage location and type of base object. 3358 APValue *BaseVal = nullptr; 3359 QualType BaseType = getType(LVal.Base); 3360 3361 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3362 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3363 // In C++11, constexpr, non-volatile variables initialized with constant 3364 // expressions are constant expressions too. Inside constexpr functions, 3365 // parameters are constant expressions even if they're non-const. 3366 // In C++1y, objects local to a constant expression (those with a Frame) are 3367 // both readable and writable inside constant expressions. 3368 // In C, such things can also be folded, although they are not ICEs. 3369 const VarDecl *VD = dyn_cast<VarDecl>(D); 3370 if (VD) { 3371 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3372 VD = VDef; 3373 } 3374 if (!VD || VD->isInvalidDecl()) { 3375 Info.FFDiag(E); 3376 return CompleteObject(); 3377 } 3378 3379 // Unless we're looking at a local variable or argument in a constexpr call, 3380 // the variable we're reading must be const. 3381 if (!Frame) { 3382 if (Info.getLangOpts().CPlusPlus14 && 3383 declaresSameEntity( 3384 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) { 3385 // OK, we can read and modify an object if we're in the process of 3386 // evaluating its initializer, because its lifetime began in this 3387 // evaluation. 3388 } else if (isModification(AK)) { 3389 // All the remaining cases do not permit modification of the object. 3390 Info.FFDiag(E, diag::note_constexpr_modify_global); 3391 return CompleteObject(); 3392 } else if (VD->isConstexpr()) { 3393 // OK, we can read this variable. 3394 } else if (BaseType->isIntegralOrEnumerationType()) { 3395 // In OpenCL if a variable is in constant address space it is a const 3396 // value. 3397 if (!(BaseType.isConstQualified() || 3398 (Info.getLangOpts().OpenCL && 3399 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3400 if (!IsAccess) 3401 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3402 if (Info.getLangOpts().CPlusPlus) { 3403 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3404 Info.Note(VD->getLocation(), diag::note_declared_at); 3405 } else { 3406 Info.FFDiag(E); 3407 } 3408 return CompleteObject(); 3409 } 3410 } else if (!IsAccess) { 3411 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3412 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3413 // We support folding of const floating-point types, in order to make 3414 // static const data members of such types (supported as an extension) 3415 // more useful. 3416 if (Info.getLangOpts().CPlusPlus11) { 3417 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3418 Info.Note(VD->getLocation(), diag::note_declared_at); 3419 } else { 3420 Info.CCEDiag(E); 3421 } 3422 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3423 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3424 // Keep evaluating to see what we can do. 3425 } else { 3426 // FIXME: Allow folding of values of any literal type in all languages. 3427 if (Info.checkingPotentialConstantExpression() && 3428 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3429 // The definition of this variable could be constexpr. We can't 3430 // access it right now, but may be able to in future. 3431 } else if (Info.getLangOpts().CPlusPlus11) { 3432 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3433 Info.Note(VD->getLocation(), diag::note_declared_at); 3434 } else { 3435 Info.FFDiag(E); 3436 } 3437 return CompleteObject(); 3438 } 3439 } 3440 3441 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3442 return CompleteObject(); 3443 } else { 3444 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3445 3446 if (!Frame) { 3447 if (const MaterializeTemporaryExpr *MTE = 3448 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3449 assert(MTE->getStorageDuration() == SD_Static && 3450 "should have a frame for a non-global materialized temporary"); 3451 3452 // Per C++1y [expr.const]p2: 3453 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3454 // - a [...] glvalue of integral or enumeration type that refers to 3455 // a non-volatile const object [...] 3456 // [...] 3457 // - a [...] glvalue of literal type that refers to a non-volatile 3458 // object whose lifetime began within the evaluation of e. 3459 // 3460 // C++11 misses the 'began within the evaluation of e' check and 3461 // instead allows all temporaries, including things like: 3462 // int &&r = 1; 3463 // int x = ++r; 3464 // constexpr int k = r; 3465 // Therefore we use the C++14 rules in C++11 too. 3466 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3467 const ValueDecl *ED = MTE->getExtendingDecl(); 3468 if (!(BaseType.isConstQualified() && 3469 BaseType->isIntegralOrEnumerationType()) && 3470 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) { 3471 if (!IsAccess) 3472 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3473 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3474 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3475 return CompleteObject(); 3476 } 3477 3478 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3479 assert(BaseVal && "got reference to unevaluated temporary"); 3480 } else { 3481 if (!IsAccess) 3482 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3483 APValue Val; 3484 LVal.moveInto(Val); 3485 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 3486 << AK 3487 << Val.getAsString(Info.Ctx, 3488 Info.Ctx.getLValueReferenceType(LValType)); 3489 NoteLValueLocation(Info, LVal.Base); 3490 return CompleteObject(); 3491 } 3492 } else { 3493 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3494 assert(BaseVal && "missing value for temporary"); 3495 } 3496 } 3497 3498 // In C++14, we can't safely access any mutable state when we might be 3499 // evaluating after an unmodeled side effect. 3500 // 3501 // FIXME: Not all local state is mutable. Allow local constant subobjects 3502 // to be read here (but take care with 'mutable' fields). 3503 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3504 Info.EvalStatus.HasSideEffects) || 3505 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 3506 return CompleteObject(); 3507 3508 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 3509 } 3510 3511 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3512 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3513 /// glvalue referred to by an entity of reference type. 3514 /// 3515 /// \param Info - Information about the ongoing evaluation. 3516 /// \param Conv - The expression for which we are performing the conversion. 3517 /// Used for diagnostics. 3518 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3519 /// case of a non-class type). 3520 /// \param LVal - The glvalue on which we are attempting to perform this action. 3521 /// \param RVal - The produced value will be placed here. 3522 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, 3523 QualType Type, 3524 const LValue &LVal, APValue &RVal) { 3525 if (LVal.Designator.Invalid) 3526 return false; 3527 3528 // Check for special cases where there is no existing APValue to look at. 3529 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3530 3531 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 3532 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3533 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3534 // initializer until now for such expressions. Such an expression can't be 3535 // an ICE in C, so this only matters for fold. 3536 if (Type.isVolatileQualified()) { 3537 Info.FFDiag(Conv); 3538 return false; 3539 } 3540 APValue Lit; 3541 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3542 return false; 3543 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 3544 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal); 3545 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3546 // Special-case character extraction so we don't have to construct an 3547 // APValue for the whole string. 3548 assert(LVal.Designator.Entries.size() <= 1 && 3549 "Can only read characters from string literals"); 3550 if (LVal.Designator.Entries.empty()) { 3551 // Fail for now for LValue to RValue conversion of an array. 3552 // (This shouldn't show up in C/C++, but it could be triggered by a 3553 // weird EvaluateAsRValue call from a tool.) 3554 Info.FFDiag(Conv); 3555 return false; 3556 } 3557 if (LVal.Designator.isOnePastTheEnd()) { 3558 if (Info.getLangOpts().CPlusPlus11) 3559 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read; 3560 else 3561 Info.FFDiag(Conv); 3562 return false; 3563 } 3564 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 3565 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 3566 return true; 3567 } 3568 } 3569 3570 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type); 3571 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal); 3572 } 3573 3574 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3575 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3576 QualType LValType, APValue &Val) { 3577 if (LVal.Designator.Invalid) 3578 return false; 3579 3580 if (!Info.getLangOpts().CPlusPlus14) { 3581 Info.FFDiag(E); 3582 return false; 3583 } 3584 3585 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3586 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3587 } 3588 3589 namespace { 3590 struct CompoundAssignSubobjectHandler { 3591 EvalInfo &Info; 3592 const Expr *E; 3593 QualType PromotedLHSType; 3594 BinaryOperatorKind Opcode; 3595 const APValue &RHS; 3596 3597 static const AccessKinds AccessKind = AK_Assign; 3598 3599 typedef bool result_type; 3600 3601 bool checkConst(QualType QT) { 3602 // Assigning to a const object has undefined behavior. 3603 if (QT.isConstQualified()) { 3604 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3605 return false; 3606 } 3607 return true; 3608 } 3609 3610 bool failed() { return false; } 3611 bool found(APValue &Subobj, QualType SubobjType) { 3612 switch (Subobj.getKind()) { 3613 case APValue::Int: 3614 return found(Subobj.getInt(), SubobjType); 3615 case APValue::Float: 3616 return found(Subobj.getFloat(), SubobjType); 3617 case APValue::ComplexInt: 3618 case APValue::ComplexFloat: 3619 // FIXME: Implement complex compound assignment. 3620 Info.FFDiag(E); 3621 return false; 3622 case APValue::LValue: 3623 return foundPointer(Subobj, SubobjType); 3624 default: 3625 // FIXME: can this happen? 3626 Info.FFDiag(E); 3627 return false; 3628 } 3629 } 3630 bool found(APSInt &Value, QualType SubobjType) { 3631 if (!checkConst(SubobjType)) 3632 return false; 3633 3634 if (!SubobjType->isIntegerType()) { 3635 // We don't support compound assignment on integer-cast-to-pointer 3636 // values. 3637 Info.FFDiag(E); 3638 return false; 3639 } 3640 3641 if (RHS.isInt()) { 3642 APSInt LHS = 3643 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 3644 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3645 return false; 3646 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3647 return true; 3648 } else if (RHS.isFloat()) { 3649 APFloat FValue(0.0); 3650 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 3651 FValue) && 3652 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 3653 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 3654 Value); 3655 } 3656 3657 Info.FFDiag(E); 3658 return false; 3659 } 3660 bool found(APFloat &Value, QualType SubobjType) { 3661 return checkConst(SubobjType) && 3662 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3663 Value) && 3664 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3665 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3666 } 3667 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3668 if (!checkConst(SubobjType)) 3669 return false; 3670 3671 QualType PointeeType; 3672 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3673 PointeeType = PT->getPointeeType(); 3674 3675 if (PointeeType.isNull() || !RHS.isInt() || 3676 (Opcode != BO_Add && Opcode != BO_Sub)) { 3677 Info.FFDiag(E); 3678 return false; 3679 } 3680 3681 APSInt Offset = RHS.getInt(); 3682 if (Opcode == BO_Sub) 3683 negateAsSigned(Offset); 3684 3685 LValue LVal; 3686 LVal.setFrom(Info.Ctx, Subobj); 3687 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3688 return false; 3689 LVal.moveInto(Subobj); 3690 return true; 3691 } 3692 }; 3693 } // end anonymous namespace 3694 3695 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3696 3697 /// Perform a compound assignment of LVal <op>= RVal. 3698 static bool handleCompoundAssignment( 3699 EvalInfo &Info, const Expr *E, 3700 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3701 BinaryOperatorKind Opcode, const APValue &RVal) { 3702 if (LVal.Designator.Invalid) 3703 return false; 3704 3705 if (!Info.getLangOpts().CPlusPlus14) { 3706 Info.FFDiag(E); 3707 return false; 3708 } 3709 3710 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3711 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3712 RVal }; 3713 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3714 } 3715 3716 namespace { 3717 struct IncDecSubobjectHandler { 3718 EvalInfo &Info; 3719 const UnaryOperator *E; 3720 AccessKinds AccessKind; 3721 APValue *Old; 3722 3723 typedef bool result_type; 3724 3725 bool checkConst(QualType QT) { 3726 // Assigning to a const object has undefined behavior. 3727 if (QT.isConstQualified()) { 3728 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3729 return false; 3730 } 3731 return true; 3732 } 3733 3734 bool failed() { return false; } 3735 bool found(APValue &Subobj, QualType SubobjType) { 3736 // Stash the old value. Also clear Old, so we don't clobber it later 3737 // if we're post-incrementing a complex. 3738 if (Old) { 3739 *Old = Subobj; 3740 Old = nullptr; 3741 } 3742 3743 switch (Subobj.getKind()) { 3744 case APValue::Int: 3745 return found(Subobj.getInt(), SubobjType); 3746 case APValue::Float: 3747 return found(Subobj.getFloat(), SubobjType); 3748 case APValue::ComplexInt: 3749 return found(Subobj.getComplexIntReal(), 3750 SubobjType->castAs<ComplexType>()->getElementType() 3751 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3752 case APValue::ComplexFloat: 3753 return found(Subobj.getComplexFloatReal(), 3754 SubobjType->castAs<ComplexType>()->getElementType() 3755 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3756 case APValue::LValue: 3757 return foundPointer(Subobj, SubobjType); 3758 default: 3759 // FIXME: can this happen? 3760 Info.FFDiag(E); 3761 return false; 3762 } 3763 } 3764 bool found(APSInt &Value, QualType SubobjType) { 3765 if (!checkConst(SubobjType)) 3766 return false; 3767 3768 if (!SubobjType->isIntegerType()) { 3769 // We don't support increment / decrement on integer-cast-to-pointer 3770 // values. 3771 Info.FFDiag(E); 3772 return false; 3773 } 3774 3775 if (Old) *Old = APValue(Value); 3776 3777 // bool arithmetic promotes to int, and the conversion back to bool 3778 // doesn't reduce mod 2^n, so special-case it. 3779 if (SubobjType->isBooleanType()) { 3780 if (AccessKind == AK_Increment) 3781 Value = 1; 3782 else 3783 Value = !Value; 3784 return true; 3785 } 3786 3787 bool WasNegative = Value.isNegative(); 3788 if (AccessKind == AK_Increment) { 3789 ++Value; 3790 3791 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 3792 APSInt ActualValue(Value, /*IsUnsigned*/true); 3793 return HandleOverflow(Info, E, ActualValue, SubobjType); 3794 } 3795 } else { 3796 --Value; 3797 3798 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 3799 unsigned BitWidth = Value.getBitWidth(); 3800 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3801 ActualValue.setBit(BitWidth); 3802 return HandleOverflow(Info, E, ActualValue, SubobjType); 3803 } 3804 } 3805 return true; 3806 } 3807 bool found(APFloat &Value, QualType SubobjType) { 3808 if (!checkConst(SubobjType)) 3809 return false; 3810 3811 if (Old) *Old = APValue(Value); 3812 3813 APFloat One(Value.getSemantics(), 1); 3814 if (AccessKind == AK_Increment) 3815 Value.add(One, APFloat::rmNearestTiesToEven); 3816 else 3817 Value.subtract(One, APFloat::rmNearestTiesToEven); 3818 return true; 3819 } 3820 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3821 if (!checkConst(SubobjType)) 3822 return false; 3823 3824 QualType PointeeType; 3825 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3826 PointeeType = PT->getPointeeType(); 3827 else { 3828 Info.FFDiag(E); 3829 return false; 3830 } 3831 3832 LValue LVal; 3833 LVal.setFrom(Info.Ctx, Subobj); 3834 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3835 AccessKind == AK_Increment ? 1 : -1)) 3836 return false; 3837 LVal.moveInto(Subobj); 3838 return true; 3839 } 3840 }; 3841 } // end anonymous namespace 3842 3843 /// Perform an increment or decrement on LVal. 3844 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3845 QualType LValType, bool IsIncrement, APValue *Old) { 3846 if (LVal.Designator.Invalid) 3847 return false; 3848 3849 if (!Info.getLangOpts().CPlusPlus14) { 3850 Info.FFDiag(E); 3851 return false; 3852 } 3853 3854 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3855 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3856 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 3857 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3858 } 3859 3860 /// Build an lvalue for the object argument of a member function call. 3861 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3862 LValue &This) { 3863 if (Object->getType()->isPointerType()) 3864 return EvaluatePointer(Object, This, Info); 3865 3866 if (Object->isGLValue()) 3867 return EvaluateLValue(Object, This, Info); 3868 3869 if (Object->getType()->isLiteralType(Info.Ctx)) 3870 return EvaluateTemporary(Object, This, Info); 3871 3872 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 3873 return false; 3874 } 3875 3876 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 3877 /// lvalue referring to the result. 3878 /// 3879 /// \param Info - Information about the ongoing evaluation. 3880 /// \param LV - An lvalue referring to the base of the member pointer. 3881 /// \param RHS - The member pointer expression. 3882 /// \param IncludeMember - Specifies whether the member itself is included in 3883 /// the resulting LValue subobject designator. This is not possible when 3884 /// creating a bound member function. 3885 /// \return The field or method declaration to which the member pointer refers, 3886 /// or 0 if evaluation fails. 3887 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3888 QualType LVType, 3889 LValue &LV, 3890 const Expr *RHS, 3891 bool IncludeMember = true) { 3892 MemberPtr MemPtr; 3893 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 3894 return nullptr; 3895 3896 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 3897 // member value, the behavior is undefined. 3898 if (!MemPtr.getDecl()) { 3899 // FIXME: Specific diagnostic. 3900 Info.FFDiag(RHS); 3901 return nullptr; 3902 } 3903 3904 if (MemPtr.isDerivedMember()) { 3905 // This is a member of some derived class. Truncate LV appropriately. 3906 // The end of the derived-to-base path for the base object must match the 3907 // derived-to-base path for the member pointer. 3908 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 3909 LV.Designator.Entries.size()) { 3910 Info.FFDiag(RHS); 3911 return nullptr; 3912 } 3913 unsigned PathLengthToMember = 3914 LV.Designator.Entries.size() - MemPtr.Path.size(); 3915 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 3916 const CXXRecordDecl *LVDecl = getAsBaseClass( 3917 LV.Designator.Entries[PathLengthToMember + I]); 3918 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 3919 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 3920 Info.FFDiag(RHS); 3921 return nullptr; 3922 } 3923 } 3924 3925 // Truncate the lvalue to the appropriate derived class. 3926 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 3927 PathLengthToMember)) 3928 return nullptr; 3929 } else if (!MemPtr.Path.empty()) { 3930 // Extend the LValue path with the member pointer's path. 3931 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 3932 MemPtr.Path.size() + IncludeMember); 3933 3934 // Walk down to the appropriate base class. 3935 if (const PointerType *PT = LVType->getAs<PointerType>()) 3936 LVType = PT->getPointeeType(); 3937 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 3938 assert(RD && "member pointer access on non-class-type expression"); 3939 // The first class in the path is that of the lvalue. 3940 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 3941 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 3942 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 3943 return nullptr; 3944 RD = Base; 3945 } 3946 // Finally cast to the class containing the member. 3947 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 3948 MemPtr.getContainingRecord())) 3949 return nullptr; 3950 } 3951 3952 // Add the member. Note that we cannot build bound member functions here. 3953 if (IncludeMember) { 3954 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 3955 if (!HandleLValueMember(Info, RHS, LV, FD)) 3956 return nullptr; 3957 } else if (const IndirectFieldDecl *IFD = 3958 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 3959 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 3960 return nullptr; 3961 } else { 3962 llvm_unreachable("can't construct reference to bound member function"); 3963 } 3964 } 3965 3966 return MemPtr.getDecl(); 3967 } 3968 3969 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 3970 const BinaryOperator *BO, 3971 LValue &LV, 3972 bool IncludeMember = true) { 3973 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 3974 3975 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 3976 if (Info.noteFailure()) { 3977 MemberPtr MemPtr; 3978 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 3979 } 3980 return nullptr; 3981 } 3982 3983 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 3984 BO->getRHS(), IncludeMember); 3985 } 3986 3987 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 3988 /// the provided lvalue, which currently refers to the base object. 3989 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 3990 LValue &Result) { 3991 SubobjectDesignator &D = Result.Designator; 3992 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 3993 return false; 3994 3995 QualType TargetQT = E->getType(); 3996 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 3997 TargetQT = PT->getPointeeType(); 3998 3999 // Check this cast lands within the final derived-to-base subobject path. 4000 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4001 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4002 << D.MostDerivedType << TargetQT; 4003 return false; 4004 } 4005 4006 // Check the type of the final cast. We don't need to check the path, 4007 // since a cast can only be formed if the path is unique. 4008 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4009 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4010 const CXXRecordDecl *FinalType; 4011 if (NewEntriesSize == D.MostDerivedPathLength) 4012 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4013 else 4014 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4015 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4016 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4017 << D.MostDerivedType << TargetQT; 4018 return false; 4019 } 4020 4021 // Truncate the lvalue to the appropriate derived class. 4022 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4023 } 4024 4025 namespace { 4026 enum EvalStmtResult { 4027 /// Evaluation failed. 4028 ESR_Failed, 4029 /// Hit a 'return' statement. 4030 ESR_Returned, 4031 /// Evaluation succeeded. 4032 ESR_Succeeded, 4033 /// Hit a 'continue' statement. 4034 ESR_Continue, 4035 /// Hit a 'break' statement. 4036 ESR_Break, 4037 /// Still scanning for 'case' or 'default' statement. 4038 ESR_CaseNotFound 4039 }; 4040 } 4041 4042 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4043 // We don't need to evaluate the initializer for a static local. 4044 if (!VD->hasLocalStorage()) 4045 return true; 4046 4047 LValue Result; 4048 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall); 4049 4050 const Expr *InitE = VD->getInit(); 4051 if (!InitE) { 4052 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized) 4053 << false << VD->getType(); 4054 Val = APValue(); 4055 return false; 4056 } 4057 4058 if (InitE->isValueDependent()) 4059 return false; 4060 4061 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4062 // Wipe out any partially-computed value, to allow tracking that this 4063 // evaluation failed. 4064 Val = APValue(); 4065 return false; 4066 } 4067 4068 return true; 4069 } 4070 4071 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4072 bool OK = true; 4073 4074 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4075 OK &= EvaluateVarDecl(Info, VD); 4076 4077 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4078 for (auto *BD : DD->bindings()) 4079 if (auto *VD = BD->getHoldingVar()) 4080 OK &= EvaluateDecl(Info, VD); 4081 4082 return OK; 4083 } 4084 4085 4086 /// Evaluate a condition (either a variable declaration or an expression). 4087 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4088 const Expr *Cond, bool &Result) { 4089 FullExpressionRAII Scope(Info); 4090 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4091 return false; 4092 return EvaluateAsBooleanCondition(Cond, Result, Info); 4093 } 4094 4095 namespace { 4096 /// A location where the result (returned value) of evaluating a 4097 /// statement should be stored. 4098 struct StmtResult { 4099 /// The APValue that should be filled in with the returned value. 4100 APValue &Value; 4101 /// The location containing the result, if any (used to support RVO). 4102 const LValue *Slot; 4103 }; 4104 4105 struct TempVersionRAII { 4106 CallStackFrame &Frame; 4107 4108 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4109 Frame.pushTempVersion(); 4110 } 4111 4112 ~TempVersionRAII() { 4113 Frame.popTempVersion(); 4114 } 4115 }; 4116 4117 } 4118 4119 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4120 const Stmt *S, 4121 const SwitchCase *SC = nullptr); 4122 4123 /// Evaluate the body of a loop, and translate the result as appropriate. 4124 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4125 const Stmt *Body, 4126 const SwitchCase *Case = nullptr) { 4127 BlockScopeRAII Scope(Info); 4128 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) { 4129 case ESR_Break: 4130 return ESR_Succeeded; 4131 case ESR_Succeeded: 4132 case ESR_Continue: 4133 return ESR_Continue; 4134 case ESR_Failed: 4135 case ESR_Returned: 4136 case ESR_CaseNotFound: 4137 return ESR; 4138 } 4139 llvm_unreachable("Invalid EvalStmtResult!"); 4140 } 4141 4142 /// Evaluate a switch statement. 4143 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4144 const SwitchStmt *SS) { 4145 BlockScopeRAII Scope(Info); 4146 4147 // Evaluate the switch condition. 4148 APSInt Value; 4149 { 4150 FullExpressionRAII Scope(Info); 4151 if (const Stmt *Init = SS->getInit()) { 4152 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4153 if (ESR != ESR_Succeeded) 4154 return ESR; 4155 } 4156 if (SS->getConditionVariable() && 4157 !EvaluateDecl(Info, SS->getConditionVariable())) 4158 return ESR_Failed; 4159 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4160 return ESR_Failed; 4161 } 4162 4163 // Find the switch case corresponding to the value of the condition. 4164 // FIXME: Cache this lookup. 4165 const SwitchCase *Found = nullptr; 4166 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4167 SC = SC->getNextSwitchCase()) { 4168 if (isa<DefaultStmt>(SC)) { 4169 Found = SC; 4170 continue; 4171 } 4172 4173 const CaseStmt *CS = cast<CaseStmt>(SC); 4174 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4175 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4176 : LHS; 4177 if (LHS <= Value && Value <= RHS) { 4178 Found = SC; 4179 break; 4180 } 4181 } 4182 4183 if (!Found) 4184 return ESR_Succeeded; 4185 4186 // Search the switch body for the switch case and evaluate it from there. 4187 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) { 4188 case ESR_Break: 4189 return ESR_Succeeded; 4190 case ESR_Succeeded: 4191 case ESR_Continue: 4192 case ESR_Failed: 4193 case ESR_Returned: 4194 return ESR; 4195 case ESR_CaseNotFound: 4196 // This can only happen if the switch case is nested within a statement 4197 // expression. We have no intention of supporting that. 4198 Info.FFDiag(Found->getBeginLoc(), 4199 diag::note_constexpr_stmt_expr_unsupported); 4200 return ESR_Failed; 4201 } 4202 llvm_unreachable("Invalid EvalStmtResult!"); 4203 } 4204 4205 // Evaluate a statement. 4206 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4207 const Stmt *S, const SwitchCase *Case) { 4208 if (!Info.nextStep(S)) 4209 return ESR_Failed; 4210 4211 // If we're hunting down a 'case' or 'default' label, recurse through 4212 // substatements until we hit the label. 4213 if (Case) { 4214 // FIXME: We don't start the lifetime of objects whose initialization we 4215 // jump over. However, such objects must be of class type with a trivial 4216 // default constructor that initialize all subobjects, so must be empty, 4217 // so this almost never matters. 4218 switch (S->getStmtClass()) { 4219 case Stmt::CompoundStmtClass: 4220 // FIXME: Precompute which substatement of a compound statement we 4221 // would jump to, and go straight there rather than performing a 4222 // linear scan each time. 4223 case Stmt::LabelStmtClass: 4224 case Stmt::AttributedStmtClass: 4225 case Stmt::DoStmtClass: 4226 break; 4227 4228 case Stmt::CaseStmtClass: 4229 case Stmt::DefaultStmtClass: 4230 if (Case == S) 4231 Case = nullptr; 4232 break; 4233 4234 case Stmt::IfStmtClass: { 4235 // FIXME: Precompute which side of an 'if' we would jump to, and go 4236 // straight there rather than scanning both sides. 4237 const IfStmt *IS = cast<IfStmt>(S); 4238 4239 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4240 // preceded by our switch label. 4241 BlockScopeRAII Scope(Info); 4242 4243 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4244 if (ESR != ESR_CaseNotFound || !IS->getElse()) 4245 return ESR; 4246 return EvaluateStmt(Result, Info, IS->getElse(), Case); 4247 } 4248 4249 case Stmt::WhileStmtClass: { 4250 EvalStmtResult ESR = 4251 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4252 if (ESR != ESR_Continue) 4253 return ESR; 4254 break; 4255 } 4256 4257 case Stmt::ForStmtClass: { 4258 const ForStmt *FS = cast<ForStmt>(S); 4259 EvalStmtResult ESR = 4260 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4261 if (ESR != ESR_Continue) 4262 return ESR; 4263 if (FS->getInc()) { 4264 FullExpressionRAII IncScope(Info); 4265 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4266 return ESR_Failed; 4267 } 4268 break; 4269 } 4270 4271 case Stmt::DeclStmtClass: 4272 // FIXME: If the variable has initialization that can't be jumped over, 4273 // bail out of any immediately-surrounding compound-statement too. 4274 default: 4275 return ESR_CaseNotFound; 4276 } 4277 } 4278 4279 switch (S->getStmtClass()) { 4280 default: 4281 if (const Expr *E = dyn_cast<Expr>(S)) { 4282 // Don't bother evaluating beyond an expression-statement which couldn't 4283 // be evaluated. 4284 FullExpressionRAII Scope(Info); 4285 if (!EvaluateIgnoredValue(Info, E)) 4286 return ESR_Failed; 4287 return ESR_Succeeded; 4288 } 4289 4290 Info.FFDiag(S->getBeginLoc()); 4291 return ESR_Failed; 4292 4293 case Stmt::NullStmtClass: 4294 return ESR_Succeeded; 4295 4296 case Stmt::DeclStmtClass: { 4297 const DeclStmt *DS = cast<DeclStmt>(S); 4298 for (const auto *DclIt : DS->decls()) { 4299 // Each declaration initialization is its own full-expression. 4300 // FIXME: This isn't quite right; if we're performing aggregate 4301 // initialization, each braced subexpression is its own full-expression. 4302 FullExpressionRAII Scope(Info); 4303 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure()) 4304 return ESR_Failed; 4305 } 4306 return ESR_Succeeded; 4307 } 4308 4309 case Stmt::ReturnStmtClass: { 4310 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4311 FullExpressionRAII Scope(Info); 4312 if (RetExpr && 4313 !(Result.Slot 4314 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4315 : Evaluate(Result.Value, Info, RetExpr))) 4316 return ESR_Failed; 4317 return ESR_Returned; 4318 } 4319 4320 case Stmt::CompoundStmtClass: { 4321 BlockScopeRAII Scope(Info); 4322 4323 const CompoundStmt *CS = cast<CompoundStmt>(S); 4324 for (const auto *BI : CS->body()) { 4325 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4326 if (ESR == ESR_Succeeded) 4327 Case = nullptr; 4328 else if (ESR != ESR_CaseNotFound) 4329 return ESR; 4330 } 4331 return Case ? ESR_CaseNotFound : ESR_Succeeded; 4332 } 4333 4334 case Stmt::IfStmtClass: { 4335 const IfStmt *IS = cast<IfStmt>(S); 4336 4337 // Evaluate the condition, as either a var decl or as an expression. 4338 BlockScopeRAII Scope(Info); 4339 if (const Stmt *Init = IS->getInit()) { 4340 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4341 if (ESR != ESR_Succeeded) 4342 return ESR; 4343 } 4344 bool Cond; 4345 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4346 return ESR_Failed; 4347 4348 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4349 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4350 if (ESR != ESR_Succeeded) 4351 return ESR; 4352 } 4353 return ESR_Succeeded; 4354 } 4355 4356 case Stmt::WhileStmtClass: { 4357 const WhileStmt *WS = cast<WhileStmt>(S); 4358 while (true) { 4359 BlockScopeRAII Scope(Info); 4360 bool Continue; 4361 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4362 Continue)) 4363 return ESR_Failed; 4364 if (!Continue) 4365 break; 4366 4367 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4368 if (ESR != ESR_Continue) 4369 return ESR; 4370 } 4371 return ESR_Succeeded; 4372 } 4373 4374 case Stmt::DoStmtClass: { 4375 const DoStmt *DS = cast<DoStmt>(S); 4376 bool Continue; 4377 do { 4378 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4379 if (ESR != ESR_Continue) 4380 return ESR; 4381 Case = nullptr; 4382 4383 FullExpressionRAII CondScope(Info); 4384 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info)) 4385 return ESR_Failed; 4386 } while (Continue); 4387 return ESR_Succeeded; 4388 } 4389 4390 case Stmt::ForStmtClass: { 4391 const ForStmt *FS = cast<ForStmt>(S); 4392 BlockScopeRAII Scope(Info); 4393 if (FS->getInit()) { 4394 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4395 if (ESR != ESR_Succeeded) 4396 return ESR; 4397 } 4398 while (true) { 4399 BlockScopeRAII Scope(Info); 4400 bool Continue = true; 4401 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4402 FS->getCond(), Continue)) 4403 return ESR_Failed; 4404 if (!Continue) 4405 break; 4406 4407 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4408 if (ESR != ESR_Continue) 4409 return ESR; 4410 4411 if (FS->getInc()) { 4412 FullExpressionRAII IncScope(Info); 4413 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4414 return ESR_Failed; 4415 } 4416 } 4417 return ESR_Succeeded; 4418 } 4419 4420 case Stmt::CXXForRangeStmtClass: { 4421 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4422 BlockScopeRAII Scope(Info); 4423 4424 // Evaluate the init-statement if present. 4425 if (FS->getInit()) { 4426 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4427 if (ESR != ESR_Succeeded) 4428 return ESR; 4429 } 4430 4431 // Initialize the __range variable. 4432 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4433 if (ESR != ESR_Succeeded) 4434 return ESR; 4435 4436 // Create the __begin and __end iterators. 4437 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4438 if (ESR != ESR_Succeeded) 4439 return ESR; 4440 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4441 if (ESR != ESR_Succeeded) 4442 return ESR; 4443 4444 while (true) { 4445 // Condition: __begin != __end. 4446 { 4447 bool Continue = true; 4448 FullExpressionRAII CondExpr(Info); 4449 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4450 return ESR_Failed; 4451 if (!Continue) 4452 break; 4453 } 4454 4455 // User's variable declaration, initialized by *__begin. 4456 BlockScopeRAII InnerScope(Info); 4457 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4458 if (ESR != ESR_Succeeded) 4459 return ESR; 4460 4461 // Loop body. 4462 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4463 if (ESR != ESR_Continue) 4464 return ESR; 4465 4466 // Increment: ++__begin 4467 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4468 return ESR_Failed; 4469 } 4470 4471 return ESR_Succeeded; 4472 } 4473 4474 case Stmt::SwitchStmtClass: 4475 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4476 4477 case Stmt::ContinueStmtClass: 4478 return ESR_Continue; 4479 4480 case Stmt::BreakStmtClass: 4481 return ESR_Break; 4482 4483 case Stmt::LabelStmtClass: 4484 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4485 4486 case Stmt::AttributedStmtClass: 4487 // As a general principle, C++11 attributes can be ignored without 4488 // any semantic impact. 4489 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4490 Case); 4491 4492 case Stmt::CaseStmtClass: 4493 case Stmt::DefaultStmtClass: 4494 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4495 case Stmt::CXXTryStmtClass: 4496 // Evaluate try blocks by evaluating all sub statements. 4497 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 4498 } 4499 } 4500 4501 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4502 /// default constructor. If so, we'll fold it whether or not it's marked as 4503 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4504 /// so we need special handling. 4505 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4506 const CXXConstructorDecl *CD, 4507 bool IsValueInitialization) { 4508 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4509 return false; 4510 4511 // Value-initialization does not call a trivial default constructor, so such a 4512 // call is a core constant expression whether or not the constructor is 4513 // constexpr. 4514 if (!CD->isConstexpr() && !IsValueInitialization) { 4515 if (Info.getLangOpts().CPlusPlus11) { 4516 // FIXME: If DiagDecl is an implicitly-declared special member function, 4517 // we should be much more explicit about why it's not constexpr. 4518 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4519 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4520 Info.Note(CD->getLocation(), diag::note_declared_at); 4521 } else { 4522 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4523 } 4524 } 4525 return true; 4526 } 4527 4528 /// CheckConstexprFunction - Check that a function can be called in a constant 4529 /// expression. 4530 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4531 const FunctionDecl *Declaration, 4532 const FunctionDecl *Definition, 4533 const Stmt *Body) { 4534 // Potential constant expressions can contain calls to declared, but not yet 4535 // defined, constexpr functions. 4536 if (Info.checkingPotentialConstantExpression() && !Definition && 4537 Declaration->isConstexpr()) 4538 return false; 4539 4540 // Bail out if the function declaration itself is invalid. We will 4541 // have produced a relevant diagnostic while parsing it, so just 4542 // note the problematic sub-expression. 4543 if (Declaration->isInvalidDecl()) { 4544 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4545 return false; 4546 } 4547 4548 // DR1872: An instantiated virtual constexpr function can't be called in a 4549 // constant expression (prior to C++20). We can still constant-fold such a 4550 // call. 4551 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) && 4552 cast<CXXMethodDecl>(Declaration)->isVirtual()) 4553 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 4554 4555 if (Definition && Definition->isInvalidDecl()) { 4556 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4557 return false; 4558 } 4559 4560 // Can we evaluate this function call? 4561 if (Definition && Definition->isConstexpr() && Body) 4562 return true; 4563 4564 if (Info.getLangOpts().CPlusPlus11) { 4565 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4566 4567 // If this function is not constexpr because it is an inherited 4568 // non-constexpr constructor, diagnose that directly. 4569 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4570 if (CD && CD->isInheritingConstructor()) { 4571 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4572 if (!Inherited->isConstexpr()) 4573 DiagDecl = CD = Inherited; 4574 } 4575 4576 // FIXME: If DiagDecl is an implicitly-declared special member function 4577 // or an inheriting constructor, we should be much more explicit about why 4578 // it's not constexpr. 4579 if (CD && CD->isInheritingConstructor()) 4580 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4581 << CD->getInheritedConstructor().getConstructor()->getParent(); 4582 else 4583 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4584 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4585 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4586 } else { 4587 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4588 } 4589 return false; 4590 } 4591 4592 namespace { 4593 struct CheckDynamicTypeHandler { 4594 AccessKinds AccessKind; 4595 typedef bool result_type; 4596 bool failed() { return false; } 4597 bool found(APValue &Subobj, QualType SubobjType) { return true; } 4598 bool found(APSInt &Value, QualType SubobjType) { return true; } 4599 bool found(APFloat &Value, QualType SubobjType) { return true; } 4600 }; 4601 } // end anonymous namespace 4602 4603 /// Check that we can access the notional vptr of an object / determine its 4604 /// dynamic type. 4605 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 4606 AccessKinds AK, bool Polymorphic) { 4607 if (This.Designator.Invalid) 4608 return false; 4609 4610 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 4611 4612 if (!Obj) 4613 return false; 4614 4615 if (!Obj.Value) { 4616 // The object is not usable in constant expressions, so we can't inspect 4617 // its value to see if it's in-lifetime or what the active union members 4618 // are. We can still check for a one-past-the-end lvalue. 4619 if (This.Designator.isOnePastTheEnd() || 4620 This.Designator.isMostDerivedAnUnsizedArray()) { 4621 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 4622 ? diag::note_constexpr_access_past_end 4623 : diag::note_constexpr_access_unsized_array) 4624 << AK; 4625 return false; 4626 } else if (Polymorphic) { 4627 // Conservatively refuse to perform a polymorphic operation if we would 4628 // not be able to read a notional 'vptr' value. 4629 APValue Val; 4630 This.moveInto(Val); 4631 QualType StarThisType = 4632 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 4633 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 4634 << AK << Val.getAsString(Info.Ctx, StarThisType); 4635 return false; 4636 } 4637 return true; 4638 } 4639 4640 CheckDynamicTypeHandler Handler{AK}; 4641 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 4642 } 4643 4644 /// Check that the pointee of the 'this' pointer in a member function call is 4645 /// either within its lifetime or in its period of construction or destruction. 4646 static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 4647 const LValue &This) { 4648 return checkDynamicType(Info, E, This, AK_MemberCall, false); 4649 } 4650 4651 struct DynamicType { 4652 /// The dynamic class type of the object. 4653 const CXXRecordDecl *Type; 4654 /// The corresponding path length in the lvalue. 4655 unsigned PathLength; 4656 }; 4657 4658 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 4659 unsigned PathLength) { 4660 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 4661 Designator.Entries.size() && "invalid path length"); 4662 return (PathLength == Designator.MostDerivedPathLength) 4663 ? Designator.MostDerivedType->getAsCXXRecordDecl() 4664 : getAsBaseClass(Designator.Entries[PathLength - 1]); 4665 } 4666 4667 /// Determine the dynamic type of an object. 4668 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 4669 LValue &This, AccessKinds AK) { 4670 // If we don't have an lvalue denoting an object of class type, there is no 4671 // meaningful dynamic type. (We consider objects of non-class type to have no 4672 // dynamic type.) 4673 if (!checkDynamicType(Info, E, This, AK, true)) 4674 return None; 4675 4676 // Refuse to compute a dynamic type in the presence of virtual bases. This 4677 // shouldn't happen other than in constant-folding situations, since literal 4678 // types can't have virtual bases. 4679 // 4680 // Note that consumers of DynamicType assume that the type has no virtual 4681 // bases, and will need modifications if this restriction is relaxed. 4682 const CXXRecordDecl *Class = 4683 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 4684 if (!Class || Class->getNumVBases()) { 4685 Info.FFDiag(E); 4686 return None; 4687 } 4688 4689 // FIXME: For very deep class hierarchies, it might be beneficial to use a 4690 // binary search here instead. But the overwhelmingly common case is that 4691 // we're not in the middle of a constructor, so it probably doesn't matter 4692 // in practice. 4693 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 4694 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 4695 PathLength <= Path.size(); ++PathLength) { 4696 switch (Info.isEvaluatingConstructor(This.getLValueBase(), 4697 Path.slice(0, PathLength))) { 4698 case ConstructionPhase::Bases: 4699 // We're constructing a base class. This is not the dynamic type. 4700 break; 4701 4702 case ConstructionPhase::None: 4703 case ConstructionPhase::AfterBases: 4704 // We've finished constructing the base classes, so this is the dynamic 4705 // type. 4706 return DynamicType{getBaseClassType(This.Designator, PathLength), 4707 PathLength}; 4708 } 4709 } 4710 4711 // CWG issue 1517: we're constructing a base class of the object described by 4712 // 'This', so that object has not yet begun its period of construction and 4713 // any polymorphic operation on it results in undefined behavior. 4714 Info.FFDiag(E); 4715 return None; 4716 } 4717 4718 /// Perform virtual dispatch. 4719 static const CXXMethodDecl *HandleVirtualDispatch( 4720 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 4721 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 4722 Optional<DynamicType> DynType = 4723 ComputeDynamicType(Info, E, This, AK_MemberCall); 4724 if (!DynType) 4725 return nullptr; 4726 4727 // Find the final overrider. It must be declared in one of the classes on the 4728 // path from the dynamic type to the static type. 4729 // FIXME: If we ever allow literal types to have virtual base classes, that 4730 // won't be true. 4731 const CXXMethodDecl *Callee = Found; 4732 unsigned PathLength = DynType->PathLength; 4733 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 4734 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 4735 const CXXMethodDecl *Overrider = 4736 Found->getCorrespondingMethodDeclaredInClass(Class, false); 4737 if (Overrider) { 4738 Callee = Overrider; 4739 break; 4740 } 4741 } 4742 4743 // C++2a [class.abstract]p6: 4744 // the effect of making a virtual call to a pure virtual function [...] is 4745 // undefined 4746 if (Callee->isPure()) { 4747 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 4748 Info.Note(Callee->getLocation(), diag::note_declared_at); 4749 return nullptr; 4750 } 4751 4752 // If necessary, walk the rest of the path to determine the sequence of 4753 // covariant adjustment steps to apply. 4754 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 4755 Found->getReturnType())) { 4756 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 4757 for (unsigned CovariantPathLength = PathLength + 1; 4758 CovariantPathLength != This.Designator.Entries.size(); 4759 ++CovariantPathLength) { 4760 const CXXRecordDecl *NextClass = 4761 getBaseClassType(This.Designator, CovariantPathLength); 4762 const CXXMethodDecl *Next = 4763 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 4764 if (Next && !Info.Ctx.hasSameUnqualifiedType( 4765 Next->getReturnType(), CovariantAdjustmentPath.back())) 4766 CovariantAdjustmentPath.push_back(Next->getReturnType()); 4767 } 4768 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 4769 CovariantAdjustmentPath.back())) 4770 CovariantAdjustmentPath.push_back(Found->getReturnType()); 4771 } 4772 4773 // Perform 'this' adjustment. 4774 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 4775 return nullptr; 4776 4777 return Callee; 4778 } 4779 4780 /// Perform the adjustment from a value returned by a virtual function to 4781 /// a value of the statically expected type, which may be a pointer or 4782 /// reference to a base class of the returned type. 4783 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 4784 APValue &Result, 4785 ArrayRef<QualType> Path) { 4786 assert(Result.isLValue() && 4787 "unexpected kind of APValue for covariant return"); 4788 if (Result.isNullPointer()) 4789 return true; 4790 4791 LValue LVal; 4792 LVal.setFrom(Info.Ctx, Result); 4793 4794 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 4795 for (unsigned I = 1; I != Path.size(); ++I) { 4796 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 4797 assert(OldClass && NewClass && "unexpected kind of covariant return"); 4798 if (OldClass != NewClass && 4799 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 4800 return false; 4801 OldClass = NewClass; 4802 } 4803 4804 LVal.moveInto(Result); 4805 return true; 4806 } 4807 4808 /// Determine whether \p Base, which is known to be a direct base class of 4809 /// \p Derived, is a public base class. 4810 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 4811 const CXXRecordDecl *Base) { 4812 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 4813 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 4814 if (BaseClass && declaresSameEntity(BaseClass, Base)) 4815 return BaseSpec.getAccessSpecifier() == AS_public; 4816 } 4817 llvm_unreachable("Base is not a direct base of Derived"); 4818 } 4819 4820 /// Apply the given dynamic cast operation on the provided lvalue. 4821 /// 4822 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 4823 /// to find a suitable target subobject. 4824 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 4825 LValue &Ptr) { 4826 // We can't do anything with a non-symbolic pointer value. 4827 SubobjectDesignator &D = Ptr.Designator; 4828 if (D.Invalid) 4829 return false; 4830 4831 // C++ [expr.dynamic.cast]p6: 4832 // If v is a null pointer value, the result is a null pointer value. 4833 if (Ptr.isNullPointer() && !E->isGLValue()) 4834 return true; 4835 4836 // For all the other cases, we need the pointer to point to an object within 4837 // its lifetime / period of construction / destruction, and we need to know 4838 // its dynamic type. 4839 Optional<DynamicType> DynType = 4840 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 4841 if (!DynType) 4842 return false; 4843 4844 // C++ [expr.dynamic.cast]p7: 4845 // If T is "pointer to cv void", then the result is a pointer to the most 4846 // derived object 4847 if (E->getType()->isVoidPointerType()) 4848 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 4849 4850 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 4851 assert(C && "dynamic_cast target is not void pointer nor class"); 4852 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 4853 4854 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 4855 // C++ [expr.dynamic.cast]p9: 4856 if (!E->isGLValue()) { 4857 // The value of a failed cast to pointer type is the null pointer value 4858 // of the required result type. 4859 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 4860 Ptr.setNull(E->getType(), TargetVal); 4861 return true; 4862 } 4863 4864 // A failed cast to reference type throws [...] std::bad_cast. 4865 unsigned DiagKind; 4866 if (!Paths && (declaresSameEntity(DynType->Type, C) || 4867 DynType->Type->isDerivedFrom(C))) 4868 DiagKind = 0; 4869 else if (!Paths || Paths->begin() == Paths->end()) 4870 DiagKind = 1; 4871 else if (Paths->isAmbiguous(CQT)) 4872 DiagKind = 2; 4873 else { 4874 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 4875 DiagKind = 3; 4876 } 4877 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 4878 << DiagKind << Ptr.Designator.getType(Info.Ctx) 4879 << Info.Ctx.getRecordType(DynType->Type) 4880 << E->getType().getUnqualifiedType(); 4881 return false; 4882 }; 4883 4884 // Runtime check, phase 1: 4885 // Walk from the base subobject towards the derived object looking for the 4886 // target type. 4887 for (int PathLength = Ptr.Designator.Entries.size(); 4888 PathLength >= (int)DynType->PathLength; --PathLength) { 4889 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 4890 if (declaresSameEntity(Class, C)) 4891 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 4892 // We can only walk across public inheritance edges. 4893 if (PathLength > (int)DynType->PathLength && 4894 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 4895 Class)) 4896 return RuntimeCheckFailed(nullptr); 4897 } 4898 4899 // Runtime check, phase 2: 4900 // Search the dynamic type for an unambiguous public base of type C. 4901 CXXBasePaths Paths(/*FindAmbiguities=*/true, 4902 /*RecordPaths=*/true, /*DetectVirtual=*/false); 4903 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 4904 Paths.front().Access == AS_public) { 4905 // Downcast to the dynamic type... 4906 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 4907 return false; 4908 // ... then upcast to the chosen base class subobject. 4909 for (CXXBasePathElement &Elem : Paths.front()) 4910 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 4911 return false; 4912 return true; 4913 } 4914 4915 // Otherwise, the runtime check fails. 4916 return RuntimeCheckFailed(&Paths); 4917 } 4918 4919 namespace { 4920 struct StartLifetimeOfUnionMemberHandler { 4921 const FieldDecl *Field; 4922 4923 static const AccessKinds AccessKind = AK_Assign; 4924 4925 APValue getDefaultInitValue(QualType SubobjType) { 4926 if (auto *RD = SubobjType->getAsCXXRecordDecl()) { 4927 if (RD->isUnion()) 4928 return APValue((const FieldDecl*)nullptr); 4929 4930 APValue Struct(APValue::UninitStruct(), RD->getNumBases(), 4931 std::distance(RD->field_begin(), RD->field_end())); 4932 4933 unsigned Index = 0; 4934 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4935 End = RD->bases_end(); I != End; ++I, ++Index) 4936 Struct.getStructBase(Index) = getDefaultInitValue(I->getType()); 4937 4938 for (const auto *I : RD->fields()) { 4939 if (I->isUnnamedBitfield()) 4940 continue; 4941 Struct.getStructField(I->getFieldIndex()) = 4942 getDefaultInitValue(I->getType()); 4943 } 4944 return Struct; 4945 } 4946 4947 if (auto *AT = dyn_cast_or_null<ConstantArrayType>( 4948 SubobjType->getAsArrayTypeUnsafe())) { 4949 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4950 if (Array.hasArrayFiller()) 4951 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType()); 4952 return Array; 4953 } 4954 4955 return APValue::IndeterminateValue(); 4956 } 4957 4958 typedef bool result_type; 4959 bool failed() { return false; } 4960 bool found(APValue &Subobj, QualType SubobjType) { 4961 // We are supposed to perform no initialization but begin the lifetime of 4962 // the object. We interpret that as meaning to do what default 4963 // initialization of the object would do if all constructors involved were 4964 // trivial: 4965 // * All base, non-variant member, and array element subobjects' lifetimes 4966 // begin 4967 // * No variant members' lifetimes begin 4968 // * All scalar subobjects whose lifetimes begin have indeterminate values 4969 assert(SubobjType->isUnionType()); 4970 if (!declaresSameEntity(Subobj.getUnionField(), Field)) 4971 Subobj.setUnion(Field, getDefaultInitValue(Field->getType())); 4972 return true; 4973 } 4974 bool found(APSInt &Value, QualType SubobjType) { 4975 llvm_unreachable("wrong value kind for union object"); 4976 } 4977 bool found(APFloat &Value, QualType SubobjType) { 4978 llvm_unreachable("wrong value kind for union object"); 4979 } 4980 }; 4981 } // end anonymous namespace 4982 4983 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 4984 4985 /// Handle a builtin simple-assignment or a call to a trivial assignment 4986 /// operator whose left-hand side might involve a union member access. If it 4987 /// does, implicitly start the lifetime of any accessed union elements per 4988 /// C++20 [class.union]5. 4989 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 4990 const LValue &LHS) { 4991 if (LHS.InvalidBase || LHS.Designator.Invalid) 4992 return false; 4993 4994 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 4995 // C++ [class.union]p5: 4996 // define the set S(E) of subexpressions of E as follows: 4997 unsigned PathLength = LHS.Designator.Entries.size(); 4998 for (const Expr *E = LHSExpr; E != nullptr;) { 4999 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5000 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5001 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5002 if (!FD) 5003 break; 5004 5005 // ... and also contains A.B if B names a union member 5006 if (FD->getParent()->isUnion()) 5007 UnionPathLengths.push_back({PathLength - 1, FD}); 5008 5009 E = ME->getBase(); 5010 --PathLength; 5011 assert(declaresSameEntity(FD, 5012 LHS.Designator.Entries[PathLength] 5013 .getAsBaseOrMember().getPointer())); 5014 5015 // -- If E is of the form A[B] and is interpreted as a built-in array 5016 // subscripting operator, S(E) is [S(the array operand, if any)]. 5017 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5018 // Step over an ArrayToPointerDecay implicit cast. 5019 auto *Base = ASE->getBase()->IgnoreImplicit(); 5020 if (!Base->getType()->isArrayType()) 5021 break; 5022 5023 E = Base; 5024 --PathLength; 5025 5026 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5027 // Step over a derived-to-base conversion. 5028 E = ICE->getSubExpr(); 5029 if (ICE->getCastKind() == CK_NoOp) 5030 continue; 5031 if (ICE->getCastKind() != CK_DerivedToBase && 5032 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5033 break; 5034 for (const CXXBaseSpecifier *Elt : ICE->path()) { 5035 --PathLength; 5036 (void)Elt; 5037 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5038 LHS.Designator.Entries[PathLength] 5039 .getAsBaseOrMember().getPointer())); 5040 } 5041 5042 // -- Otherwise, S(E) is empty. 5043 } else { 5044 break; 5045 } 5046 } 5047 5048 // Common case: no unions' lifetimes are started. 5049 if (UnionPathLengths.empty()) 5050 return true; 5051 5052 // if modification of X [would access an inactive union member], an object 5053 // of the type of X is implicitly created 5054 CompleteObject Obj = 5055 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5056 if (!Obj) 5057 return false; 5058 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5059 llvm::reverse(UnionPathLengths)) { 5060 // Form a designator for the union object. 5061 SubobjectDesignator D = LHS.Designator; 5062 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5063 5064 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second}; 5065 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5066 return false; 5067 } 5068 5069 return true; 5070 } 5071 5072 /// Determine if a class has any fields that might need to be copied by a 5073 /// trivial copy or move operation. 5074 static bool hasFields(const CXXRecordDecl *RD) { 5075 if (!RD || RD->isEmpty()) 5076 return false; 5077 for (auto *FD : RD->fields()) { 5078 if (FD->isUnnamedBitfield()) 5079 continue; 5080 return true; 5081 } 5082 for (auto &Base : RD->bases()) 5083 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 5084 return true; 5085 return false; 5086 } 5087 5088 namespace { 5089 typedef SmallVector<APValue, 8> ArgVector; 5090 } 5091 5092 /// EvaluateArgs - Evaluate the arguments to a function call. 5093 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues, 5094 EvalInfo &Info) { 5095 bool Success = true; 5096 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 5097 I != E; ++I) { 5098 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 5099 // If we're checking for a potential constant expression, evaluate all 5100 // initializers even if some of them fail. 5101 if (!Info.noteFailure()) 5102 return false; 5103 Success = false; 5104 } 5105 } 5106 return Success; 5107 } 5108 5109 /// Evaluate a function call. 5110 static bool HandleFunctionCall(SourceLocation CallLoc, 5111 const FunctionDecl *Callee, const LValue *This, 5112 ArrayRef<const Expr*> Args, const Stmt *Body, 5113 EvalInfo &Info, APValue &Result, 5114 const LValue *ResultSlot) { 5115 ArgVector ArgValues(Args.size()); 5116 if (!EvaluateArgs(Args, ArgValues, Info)) 5117 return false; 5118 5119 if (!Info.CheckCallLimit(CallLoc)) 5120 return false; 5121 5122 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 5123 5124 // For a trivial copy or move assignment, perform an APValue copy. This is 5125 // essential for unions, where the operations performed by the assignment 5126 // operator cannot be represented as statements. 5127 // 5128 // Skip this for non-union classes with no fields; in that case, the defaulted 5129 // copy/move does not actually read the object. 5130 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5131 if (MD && MD->isDefaulted() && 5132 (MD->getParent()->isUnion() || 5133 (MD->isTrivial() && hasFields(MD->getParent())))) { 5134 assert(This && 5135 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5136 LValue RHS; 5137 RHS.setFrom(Info.Ctx, ArgValues[0]); 5138 APValue RHSValue; 5139 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), 5140 RHS, RHSValue)) 5141 return false; 5142 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() && 5143 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5144 return false; 5145 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5146 RHSValue)) 5147 return false; 5148 This->moveInto(Result); 5149 return true; 5150 } else if (MD && isLambdaCallOperator(MD)) { 5151 // We're in a lambda; determine the lambda capture field maps unless we're 5152 // just constexpr checking a lambda's call operator. constexpr checking is 5153 // done before the captures have been added to the closure object (unless 5154 // we're inferring constexpr-ness), so we don't have access to them in this 5155 // case. But since we don't need the captures to constexpr check, we can 5156 // just ignore them. 5157 if (!Info.checkingPotentialConstantExpression()) 5158 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5159 Frame.LambdaThisCaptureField); 5160 } 5161 5162 StmtResult Ret = {Result, ResultSlot}; 5163 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5164 if (ESR == ESR_Succeeded) { 5165 if (Callee->getReturnType()->isVoidType()) 5166 return true; 5167 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5168 } 5169 return ESR == ESR_Returned; 5170 } 5171 5172 /// Evaluate a constructor call. 5173 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5174 APValue *ArgValues, 5175 const CXXConstructorDecl *Definition, 5176 EvalInfo &Info, APValue &Result) { 5177 SourceLocation CallLoc = E->getExprLoc(); 5178 if (!Info.CheckCallLimit(CallLoc)) 5179 return false; 5180 5181 const CXXRecordDecl *RD = Definition->getParent(); 5182 if (RD->getNumVBases()) { 5183 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5184 return false; 5185 } 5186 5187 EvalInfo::EvaluatingConstructorRAII EvalObj( 5188 Info, 5189 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5190 RD->getNumBases()); 5191 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5192 5193 // FIXME: Creating an APValue just to hold a nonexistent return value is 5194 // wasteful. 5195 APValue RetVal; 5196 StmtResult Ret = {RetVal, nullptr}; 5197 5198 // If it's a delegating constructor, delegate. 5199 if (Definition->isDelegatingConstructor()) { 5200 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5201 { 5202 FullExpressionRAII InitScope(Info); 5203 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit())) 5204 return false; 5205 } 5206 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5207 } 5208 5209 // For a trivial copy or move constructor, perform an APValue copy. This is 5210 // essential for unions (or classes with anonymous union members), where the 5211 // operations performed by the constructor cannot be represented by 5212 // ctor-initializers. 5213 // 5214 // Skip this for empty non-union classes; we should not perform an 5215 // lvalue-to-rvalue conversion on them because their copy constructor does not 5216 // actually read them. 5217 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5218 (Definition->getParent()->isUnion() || 5219 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 5220 LValue RHS; 5221 RHS.setFrom(Info.Ctx, ArgValues[0]); 5222 return handleLValueToRValueConversion( 5223 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5224 RHS, Result); 5225 } 5226 5227 // Reserve space for the struct members. 5228 if (!RD->isUnion() && !Result.hasValue()) 5229 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5230 std::distance(RD->field_begin(), RD->field_end())); 5231 5232 if (RD->isInvalidDecl()) return false; 5233 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5234 5235 // A scope for temporaries lifetime-extended by reference members. 5236 BlockScopeRAII LifetimeExtendedScope(Info); 5237 5238 bool Success = true; 5239 unsigned BasesSeen = 0; 5240 #ifndef NDEBUG 5241 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5242 #endif 5243 for (const auto *I : Definition->inits()) { 5244 LValue Subobject = This; 5245 LValue SubobjectParent = This; 5246 APValue *Value = &Result; 5247 5248 // Determine the subobject to initialize. 5249 FieldDecl *FD = nullptr; 5250 if (I->isBaseInitializer()) { 5251 QualType BaseType(I->getBaseClass(), 0); 5252 #ifndef NDEBUG 5253 // Non-virtual base classes are initialized in the order in the class 5254 // definition. We have already checked for virtual base classes. 5255 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 5256 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 5257 "base class initializers not in expected order"); 5258 ++BaseIt; 5259 #endif 5260 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 5261 BaseType->getAsCXXRecordDecl(), &Layout)) 5262 return false; 5263 Value = &Result.getStructBase(BasesSeen++); 5264 } else if ((FD = I->getMember())) { 5265 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 5266 return false; 5267 if (RD->isUnion()) { 5268 Result = APValue(FD); 5269 Value = &Result.getUnionValue(); 5270 } else { 5271 Value = &Result.getStructField(FD->getFieldIndex()); 5272 } 5273 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 5274 // Walk the indirect field decl's chain to find the object to initialize, 5275 // and make sure we've initialized every step along it. 5276 auto IndirectFieldChain = IFD->chain(); 5277 for (auto *C : IndirectFieldChain) { 5278 FD = cast<FieldDecl>(C); 5279 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 5280 // Switch the union field if it differs. This happens if we had 5281 // preceding zero-initialization, and we're now initializing a union 5282 // subobject other than the first. 5283 // FIXME: In this case, the values of the other subobjects are 5284 // specified, since zero-initialization sets all padding bits to zero. 5285 if (!Value->hasValue() || 5286 (Value->isUnion() && Value->getUnionField() != FD)) { 5287 if (CD->isUnion()) 5288 *Value = APValue(FD); 5289 else 5290 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(), 5291 std::distance(CD->field_begin(), CD->field_end())); 5292 } 5293 // Store Subobject as its parent before updating it for the last element 5294 // in the chain. 5295 if (C == IndirectFieldChain.back()) 5296 SubobjectParent = Subobject; 5297 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 5298 return false; 5299 if (CD->isUnion()) 5300 Value = &Value->getUnionValue(); 5301 else 5302 Value = &Value->getStructField(FD->getFieldIndex()); 5303 } 5304 } else { 5305 llvm_unreachable("unknown base initializer kind"); 5306 } 5307 5308 // Need to override This for implicit field initializers as in this case 5309 // This refers to innermost anonymous struct/union containing initializer, 5310 // not to currently constructed class. 5311 const Expr *Init = I->getInit(); 5312 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 5313 isa<CXXDefaultInitExpr>(Init)); 5314 FullExpressionRAII InitScope(Info); 5315 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 5316 (FD && FD->isBitField() && 5317 !truncateBitfieldValue(Info, Init, *Value, FD))) { 5318 // If we're checking for a potential constant expression, evaluate all 5319 // initializers even if some of them fail. 5320 if (!Info.noteFailure()) 5321 return false; 5322 Success = false; 5323 } 5324 5325 // This is the point at which the dynamic type of the object becomes this 5326 // class type. 5327 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 5328 EvalObj.finishedConstructingBases(); 5329 } 5330 5331 return Success && 5332 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5333 } 5334 5335 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5336 ArrayRef<const Expr*> Args, 5337 const CXXConstructorDecl *Definition, 5338 EvalInfo &Info, APValue &Result) { 5339 ArgVector ArgValues(Args.size()); 5340 if (!EvaluateArgs(Args, ArgValues, Info)) 5341 return false; 5342 5343 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 5344 Info, Result); 5345 } 5346 5347 //===----------------------------------------------------------------------===// 5348 // Generic Evaluation 5349 //===----------------------------------------------------------------------===// 5350 namespace { 5351 5352 template <class Derived> 5353 class ExprEvaluatorBase 5354 : public ConstStmtVisitor<Derived, bool> { 5355 private: 5356 Derived &getDerived() { return static_cast<Derived&>(*this); } 5357 bool DerivedSuccess(const APValue &V, const Expr *E) { 5358 return getDerived().Success(V, E); 5359 } 5360 bool DerivedZeroInitialization(const Expr *E) { 5361 return getDerived().ZeroInitialization(E); 5362 } 5363 5364 // Check whether a conditional operator with a non-constant condition is a 5365 // potential constant expression. If neither arm is a potential constant 5366 // expression, then the conditional operator is not either. 5367 template<typename ConditionalOperator> 5368 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 5369 assert(Info.checkingPotentialConstantExpression()); 5370 5371 // Speculatively evaluate both arms. 5372 SmallVector<PartialDiagnosticAt, 8> Diag; 5373 { 5374 SpeculativeEvaluationRAII Speculate(Info, &Diag); 5375 StmtVisitorTy::Visit(E->getFalseExpr()); 5376 if (Diag.empty()) 5377 return; 5378 } 5379 5380 { 5381 SpeculativeEvaluationRAII Speculate(Info, &Diag); 5382 Diag.clear(); 5383 StmtVisitorTy::Visit(E->getTrueExpr()); 5384 if (Diag.empty()) 5385 return; 5386 } 5387 5388 Error(E, diag::note_constexpr_conditional_never_const); 5389 } 5390 5391 5392 template<typename ConditionalOperator> 5393 bool HandleConditionalOperator(const ConditionalOperator *E) { 5394 bool BoolResult; 5395 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 5396 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 5397 CheckPotentialConstantConditional(E); 5398 return false; 5399 } 5400 if (Info.noteFailure()) { 5401 StmtVisitorTy::Visit(E->getTrueExpr()); 5402 StmtVisitorTy::Visit(E->getFalseExpr()); 5403 } 5404 return false; 5405 } 5406 5407 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 5408 return StmtVisitorTy::Visit(EvalExpr); 5409 } 5410 5411 protected: 5412 EvalInfo &Info; 5413 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 5414 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 5415 5416 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 5417 return Info.CCEDiag(E, D); 5418 } 5419 5420 bool ZeroInitialization(const Expr *E) { return Error(E); } 5421 5422 public: 5423 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 5424 5425 EvalInfo &getEvalInfo() { return Info; } 5426 5427 /// Report an evaluation error. This should only be called when an error is 5428 /// first discovered. When propagating an error, just return false. 5429 bool Error(const Expr *E, diag::kind D) { 5430 Info.FFDiag(E, D); 5431 return false; 5432 } 5433 bool Error(const Expr *E) { 5434 return Error(E, diag::note_invalid_subexpr_in_const_expr); 5435 } 5436 5437 bool VisitStmt(const Stmt *) { 5438 llvm_unreachable("Expression evaluator should not be called on stmts"); 5439 } 5440 bool VisitExpr(const Expr *E) { 5441 return Error(E); 5442 } 5443 5444 bool VisitConstantExpr(const ConstantExpr *E) 5445 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5446 bool VisitParenExpr(const ParenExpr *E) 5447 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5448 bool VisitUnaryExtension(const UnaryOperator *E) 5449 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5450 bool VisitUnaryPlus(const UnaryOperator *E) 5451 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5452 bool VisitChooseExpr(const ChooseExpr *E) 5453 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 5454 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 5455 { return StmtVisitorTy::Visit(E->getResultExpr()); } 5456 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 5457 { return StmtVisitorTy::Visit(E->getReplacement()); } 5458 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 5459 TempVersionRAII RAII(*Info.CurrentCall); 5460 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 5461 return StmtVisitorTy::Visit(E->getExpr()); 5462 } 5463 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 5464 TempVersionRAII RAII(*Info.CurrentCall); 5465 // The initializer may not have been parsed yet, or might be erroneous. 5466 if (!E->getExpr()) 5467 return Error(E); 5468 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 5469 return StmtVisitorTy::Visit(E->getExpr()); 5470 } 5471 5472 // We cannot create any objects for which cleanups are required, so there is 5473 // nothing to do here; all cleanups must come from unevaluated subexpressions. 5474 bool VisitExprWithCleanups(const ExprWithCleanups *E) 5475 { return StmtVisitorTy::Visit(E->getSubExpr()); } 5476 5477 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 5478 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 5479 return static_cast<Derived*>(this)->VisitCastExpr(E); 5480 } 5481 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 5482 if (!Info.Ctx.getLangOpts().CPlusPlus2a) 5483 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 5484 return static_cast<Derived*>(this)->VisitCastExpr(E); 5485 } 5486 5487 bool VisitBinaryOperator(const BinaryOperator *E) { 5488 switch (E->getOpcode()) { 5489 default: 5490 return Error(E); 5491 5492 case BO_Comma: 5493 VisitIgnoredValue(E->getLHS()); 5494 return StmtVisitorTy::Visit(E->getRHS()); 5495 5496 case BO_PtrMemD: 5497 case BO_PtrMemI: { 5498 LValue Obj; 5499 if (!HandleMemberPointerAccess(Info, E, Obj)) 5500 return false; 5501 APValue Result; 5502 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 5503 return false; 5504 return DerivedSuccess(Result, E); 5505 } 5506 } 5507 } 5508 5509 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 5510 // Evaluate and cache the common expression. We treat it as a temporary, 5511 // even though it's not quite the same thing. 5512 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false), 5513 Info, E->getCommon())) 5514 return false; 5515 5516 return HandleConditionalOperator(E); 5517 } 5518 5519 bool VisitConditionalOperator(const ConditionalOperator *E) { 5520 bool IsBcpCall = false; 5521 // If the condition (ignoring parens) is a __builtin_constant_p call, 5522 // the result is a constant expression if it can be folded without 5523 // side-effects. This is an important GNU extension. See GCC PR38377 5524 // for discussion. 5525 if (const CallExpr *CallCE = 5526 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 5527 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 5528 IsBcpCall = true; 5529 5530 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 5531 // constant expression; we can't check whether it's potentially foldable. 5532 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 5533 return false; 5534 5535 FoldConstant Fold(Info, IsBcpCall); 5536 if (!HandleConditionalOperator(E)) { 5537 Fold.keepDiagnostics(); 5538 return false; 5539 } 5540 5541 return true; 5542 } 5543 5544 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 5545 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 5546 return DerivedSuccess(*Value, E); 5547 5548 const Expr *Source = E->getSourceExpr(); 5549 if (!Source) 5550 return Error(E); 5551 if (Source == E) { // sanity checking. 5552 assert(0 && "OpaqueValueExpr recursively refers to itself"); 5553 return Error(E); 5554 } 5555 return StmtVisitorTy::Visit(Source); 5556 } 5557 5558 bool VisitCallExpr(const CallExpr *E) { 5559 APValue Result; 5560 if (!handleCallExpr(E, Result, nullptr)) 5561 return false; 5562 return DerivedSuccess(Result, E); 5563 } 5564 5565 bool handleCallExpr(const CallExpr *E, APValue &Result, 5566 const LValue *ResultSlot) { 5567 const Expr *Callee = E->getCallee()->IgnoreParens(); 5568 QualType CalleeType = Callee->getType(); 5569 5570 const FunctionDecl *FD = nullptr; 5571 LValue *This = nullptr, ThisVal; 5572 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 5573 bool HasQualifier = false; 5574 5575 // Extract function decl and 'this' pointer from the callee. 5576 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 5577 const CXXMethodDecl *Member = nullptr; 5578 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 5579 // Explicit bound member calls, such as x.f() or p->g(); 5580 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 5581 return false; 5582 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 5583 if (!Member) 5584 return Error(Callee); 5585 This = &ThisVal; 5586 HasQualifier = ME->hasQualifier(); 5587 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 5588 // Indirect bound member calls ('.*' or '->*'). 5589 Member = dyn_cast_or_null<CXXMethodDecl>( 5590 HandleMemberPointerAccess(Info, BE, ThisVal, false)); 5591 if (!Member) 5592 return Error(Callee); 5593 This = &ThisVal; 5594 } else 5595 return Error(Callee); 5596 FD = Member; 5597 } else if (CalleeType->isFunctionPointerType()) { 5598 LValue Call; 5599 if (!EvaluatePointer(Callee, Call, Info)) 5600 return false; 5601 5602 if (!Call.getLValueOffset().isZero()) 5603 return Error(Callee); 5604 FD = dyn_cast_or_null<FunctionDecl>( 5605 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 5606 if (!FD) 5607 return Error(Callee); 5608 // Don't call function pointers which have been cast to some other type. 5609 // Per DR (no number yet), the caller and callee can differ in noexcept. 5610 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 5611 CalleeType->getPointeeType(), FD->getType())) { 5612 return Error(E); 5613 } 5614 5615 // Overloaded operator calls to member functions are represented as normal 5616 // calls with '*this' as the first argument. 5617 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 5618 if (MD && !MD->isStatic()) { 5619 // FIXME: When selecting an implicit conversion for an overloaded 5620 // operator delete, we sometimes try to evaluate calls to conversion 5621 // operators without a 'this' parameter! 5622 if (Args.empty()) 5623 return Error(E); 5624 5625 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 5626 return false; 5627 This = &ThisVal; 5628 Args = Args.slice(1); 5629 } else if (MD && MD->isLambdaStaticInvoker()) { 5630 // Map the static invoker for the lambda back to the call operator. 5631 // Conveniently, we don't have to slice out the 'this' argument (as is 5632 // being done for the non-static case), since a static member function 5633 // doesn't have an implicit argument passed in. 5634 const CXXRecordDecl *ClosureClass = MD->getParent(); 5635 assert( 5636 ClosureClass->captures_begin() == ClosureClass->captures_end() && 5637 "Number of captures must be zero for conversion to function-ptr"); 5638 5639 const CXXMethodDecl *LambdaCallOp = 5640 ClosureClass->getLambdaCallOperator(); 5641 5642 // Set 'FD', the function that will be called below, to the call 5643 // operator. If the closure object represents a generic lambda, find 5644 // the corresponding specialization of the call operator. 5645 5646 if (ClosureClass->isGenericLambda()) { 5647 assert(MD->isFunctionTemplateSpecialization() && 5648 "A generic lambda's static-invoker function must be a " 5649 "template specialization"); 5650 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 5651 FunctionTemplateDecl *CallOpTemplate = 5652 LambdaCallOp->getDescribedFunctionTemplate(); 5653 void *InsertPos = nullptr; 5654 FunctionDecl *CorrespondingCallOpSpecialization = 5655 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 5656 assert(CorrespondingCallOpSpecialization && 5657 "We must always have a function call operator specialization " 5658 "that corresponds to our static invoker specialization"); 5659 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 5660 } else 5661 FD = LambdaCallOp; 5662 } 5663 } else 5664 return Error(E); 5665 5666 SmallVector<QualType, 4> CovariantAdjustmentPath; 5667 if (This) { 5668 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 5669 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 5670 // Perform virtual dispatch, if necessary. 5671 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 5672 CovariantAdjustmentPath); 5673 if (!FD) 5674 return false; 5675 } else { 5676 // Check that the 'this' pointer points to an object of the right type. 5677 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This)) 5678 return false; 5679 } 5680 } 5681 5682 const FunctionDecl *Definition = nullptr; 5683 Stmt *Body = FD->getBody(Definition); 5684 5685 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 5686 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 5687 Result, ResultSlot)) 5688 return false; 5689 5690 if (!CovariantAdjustmentPath.empty() && 5691 !HandleCovariantReturnAdjustment(Info, E, Result, 5692 CovariantAdjustmentPath)) 5693 return false; 5694 5695 return true; 5696 } 5697 5698 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 5699 return StmtVisitorTy::Visit(E->getInitializer()); 5700 } 5701 bool VisitInitListExpr(const InitListExpr *E) { 5702 if (E->getNumInits() == 0) 5703 return DerivedZeroInitialization(E); 5704 if (E->getNumInits() == 1) 5705 return StmtVisitorTy::Visit(E->getInit(0)); 5706 return Error(E); 5707 } 5708 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 5709 return DerivedZeroInitialization(E); 5710 } 5711 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 5712 return DerivedZeroInitialization(E); 5713 } 5714 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 5715 return DerivedZeroInitialization(E); 5716 } 5717 5718 /// A member expression where the object is a prvalue is itself a prvalue. 5719 bool VisitMemberExpr(const MemberExpr *E) { 5720 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 5721 "missing temporary materialization conversion"); 5722 assert(!E->isArrow() && "missing call to bound member function?"); 5723 5724 APValue Val; 5725 if (!Evaluate(Val, Info, E->getBase())) 5726 return false; 5727 5728 QualType BaseTy = E->getBase()->getType(); 5729 5730 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 5731 if (!FD) return Error(E); 5732 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 5733 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 5734 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 5735 5736 // Note: there is no lvalue base here. But this case should only ever 5737 // happen in C or in C++98, where we cannot be evaluating a constexpr 5738 // constructor, which is the only case the base matters. 5739 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 5740 SubobjectDesignator Designator(BaseTy); 5741 Designator.addDeclUnchecked(FD); 5742 5743 APValue Result; 5744 return extractSubobject(Info, E, Obj, Designator, Result) && 5745 DerivedSuccess(Result, E); 5746 } 5747 5748 bool VisitCastExpr(const CastExpr *E) { 5749 switch (E->getCastKind()) { 5750 default: 5751 break; 5752 5753 case CK_AtomicToNonAtomic: { 5754 APValue AtomicVal; 5755 // This does not need to be done in place even for class/array types: 5756 // atomic-to-non-atomic conversion implies copying the object 5757 // representation. 5758 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 5759 return false; 5760 return DerivedSuccess(AtomicVal, E); 5761 } 5762 5763 case CK_NoOp: 5764 case CK_UserDefinedConversion: 5765 return StmtVisitorTy::Visit(E->getSubExpr()); 5766 5767 case CK_LValueToRValue: { 5768 LValue LVal; 5769 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 5770 return false; 5771 APValue RVal; 5772 // Note, we use the subexpression's type in order to retain cv-qualifiers. 5773 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 5774 LVal, RVal)) 5775 return false; 5776 return DerivedSuccess(RVal, E); 5777 } 5778 } 5779 5780 return Error(E); 5781 } 5782 5783 bool VisitUnaryPostInc(const UnaryOperator *UO) { 5784 return VisitUnaryPostIncDec(UO); 5785 } 5786 bool VisitUnaryPostDec(const UnaryOperator *UO) { 5787 return VisitUnaryPostIncDec(UO); 5788 } 5789 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 5790 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 5791 return Error(UO); 5792 5793 LValue LVal; 5794 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 5795 return false; 5796 APValue RVal; 5797 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 5798 UO->isIncrementOp(), &RVal)) 5799 return false; 5800 return DerivedSuccess(RVal, UO); 5801 } 5802 5803 bool VisitStmtExpr(const StmtExpr *E) { 5804 // We will have checked the full-expressions inside the statement expression 5805 // when they were completed, and don't need to check them again now. 5806 if (Info.checkingForOverflow()) 5807 return Error(E); 5808 5809 BlockScopeRAII Scope(Info); 5810 const CompoundStmt *CS = E->getSubStmt(); 5811 if (CS->body_empty()) 5812 return true; 5813 5814 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 5815 BE = CS->body_end(); 5816 /**/; ++BI) { 5817 if (BI + 1 == BE) { 5818 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 5819 if (!FinalExpr) { 5820 Info.FFDiag((*BI)->getBeginLoc(), 5821 diag::note_constexpr_stmt_expr_unsupported); 5822 return false; 5823 } 5824 return this->Visit(FinalExpr); 5825 } 5826 5827 APValue ReturnValue; 5828 StmtResult Result = { ReturnValue, nullptr }; 5829 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 5830 if (ESR != ESR_Succeeded) { 5831 // FIXME: If the statement-expression terminated due to 'return', 5832 // 'break', or 'continue', it would be nice to propagate that to 5833 // the outer statement evaluation rather than bailing out. 5834 if (ESR != ESR_Failed) 5835 Info.FFDiag((*BI)->getBeginLoc(), 5836 diag::note_constexpr_stmt_expr_unsupported); 5837 return false; 5838 } 5839 } 5840 5841 llvm_unreachable("Return from function from the loop above."); 5842 } 5843 5844 /// Visit a value which is evaluated, but whose value is ignored. 5845 void VisitIgnoredValue(const Expr *E) { 5846 EvaluateIgnoredValue(Info, E); 5847 } 5848 5849 /// Potentially visit a MemberExpr's base expression. 5850 void VisitIgnoredBaseExpression(const Expr *E) { 5851 // While MSVC doesn't evaluate the base expression, it does diagnose the 5852 // presence of side-effecting behavior. 5853 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 5854 return; 5855 VisitIgnoredValue(E); 5856 } 5857 }; 5858 5859 } // namespace 5860 5861 //===----------------------------------------------------------------------===// 5862 // Common base class for lvalue and temporary evaluation. 5863 //===----------------------------------------------------------------------===// 5864 namespace { 5865 template<class Derived> 5866 class LValueExprEvaluatorBase 5867 : public ExprEvaluatorBase<Derived> { 5868 protected: 5869 LValue &Result; 5870 bool InvalidBaseOK; 5871 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 5872 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 5873 5874 bool Success(APValue::LValueBase B) { 5875 Result.set(B); 5876 return true; 5877 } 5878 5879 bool evaluatePointer(const Expr *E, LValue &Result) { 5880 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 5881 } 5882 5883 public: 5884 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 5885 : ExprEvaluatorBaseTy(Info), Result(Result), 5886 InvalidBaseOK(InvalidBaseOK) {} 5887 5888 bool Success(const APValue &V, const Expr *E) { 5889 Result.setFrom(this->Info.Ctx, V); 5890 return true; 5891 } 5892 5893 bool VisitMemberExpr(const MemberExpr *E) { 5894 // Handle non-static data members. 5895 QualType BaseTy; 5896 bool EvalOK; 5897 if (E->isArrow()) { 5898 EvalOK = evaluatePointer(E->getBase(), Result); 5899 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 5900 } else if (E->getBase()->isRValue()) { 5901 assert(E->getBase()->getType()->isRecordType()); 5902 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 5903 BaseTy = E->getBase()->getType(); 5904 } else { 5905 EvalOK = this->Visit(E->getBase()); 5906 BaseTy = E->getBase()->getType(); 5907 } 5908 if (!EvalOK) { 5909 if (!InvalidBaseOK) 5910 return false; 5911 Result.setInvalid(E); 5912 return true; 5913 } 5914 5915 const ValueDecl *MD = E->getMemberDecl(); 5916 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 5917 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 5918 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 5919 (void)BaseTy; 5920 if (!HandleLValueMember(this->Info, E, Result, FD)) 5921 return false; 5922 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 5923 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 5924 return false; 5925 } else 5926 return this->Error(E); 5927 5928 if (MD->getType()->isReferenceType()) { 5929 APValue RefValue; 5930 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 5931 RefValue)) 5932 return false; 5933 return Success(RefValue, E); 5934 } 5935 return true; 5936 } 5937 5938 bool VisitBinaryOperator(const BinaryOperator *E) { 5939 switch (E->getOpcode()) { 5940 default: 5941 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 5942 5943 case BO_PtrMemD: 5944 case BO_PtrMemI: 5945 return HandleMemberPointerAccess(this->Info, E, Result); 5946 } 5947 } 5948 5949 bool VisitCastExpr(const CastExpr *E) { 5950 switch (E->getCastKind()) { 5951 default: 5952 return ExprEvaluatorBaseTy::VisitCastExpr(E); 5953 5954 case CK_DerivedToBase: 5955 case CK_UncheckedDerivedToBase: 5956 if (!this->Visit(E->getSubExpr())) 5957 return false; 5958 5959 // Now figure out the necessary offset to add to the base LV to get from 5960 // the derived class to the base class. 5961 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 5962 Result); 5963 } 5964 } 5965 }; 5966 } 5967 5968 //===----------------------------------------------------------------------===// 5969 // LValue Evaluation 5970 // 5971 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 5972 // function designators (in C), decl references to void objects (in C), and 5973 // temporaries (if building with -Wno-address-of-temporary). 5974 // 5975 // LValue evaluation produces values comprising a base expression of one of the 5976 // following types: 5977 // - Declarations 5978 // * VarDecl 5979 // * FunctionDecl 5980 // - Literals 5981 // * CompoundLiteralExpr in C (and in global scope in C++) 5982 // * StringLiteral 5983 // * PredefinedExpr 5984 // * ObjCStringLiteralExpr 5985 // * ObjCEncodeExpr 5986 // * AddrLabelExpr 5987 // * BlockExpr 5988 // * CallExpr for a MakeStringConstant builtin 5989 // - typeid(T) expressions, as TypeInfoLValues 5990 // - Locals and temporaries 5991 // * MaterializeTemporaryExpr 5992 // * Any Expr, with a CallIndex indicating the function in which the temporary 5993 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 5994 // from the AST (FIXME). 5995 // * A MaterializeTemporaryExpr that has static storage duration, with no 5996 // CallIndex, for a lifetime-extended temporary. 5997 // plus an offset in bytes. 5998 //===----------------------------------------------------------------------===// 5999 namespace { 6000 class LValueExprEvaluator 6001 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 6002 public: 6003 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 6004 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 6005 6006 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 6007 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 6008 6009 bool VisitDeclRefExpr(const DeclRefExpr *E); 6010 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 6011 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 6012 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 6013 bool VisitMemberExpr(const MemberExpr *E); 6014 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 6015 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 6016 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 6017 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 6018 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 6019 bool VisitUnaryDeref(const UnaryOperator *E); 6020 bool VisitUnaryReal(const UnaryOperator *E); 6021 bool VisitUnaryImag(const UnaryOperator *E); 6022 bool VisitUnaryPreInc(const UnaryOperator *UO) { 6023 return VisitUnaryPreIncDec(UO); 6024 } 6025 bool VisitUnaryPreDec(const UnaryOperator *UO) { 6026 return VisitUnaryPreIncDec(UO); 6027 } 6028 bool VisitBinAssign(const BinaryOperator *BO); 6029 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 6030 6031 bool VisitCastExpr(const CastExpr *E) { 6032 switch (E->getCastKind()) { 6033 default: 6034 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 6035 6036 case CK_LValueBitCast: 6037 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 6038 if (!Visit(E->getSubExpr())) 6039 return false; 6040 Result.Designator.setInvalid(); 6041 return true; 6042 6043 case CK_BaseToDerived: 6044 if (!Visit(E->getSubExpr())) 6045 return false; 6046 return HandleBaseToDerivedCast(Info, E, Result); 6047 6048 case CK_Dynamic: 6049 if (!Visit(E->getSubExpr())) 6050 return false; 6051 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 6052 } 6053 } 6054 }; 6055 } // end anonymous namespace 6056 6057 /// Evaluate an expression as an lvalue. This can be legitimately called on 6058 /// expressions which are not glvalues, in three cases: 6059 /// * function designators in C, and 6060 /// * "extern void" objects 6061 /// * @selector() expressions in Objective-C 6062 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 6063 bool InvalidBaseOK) { 6064 assert(E->isGLValue() || E->getType()->isFunctionType() || 6065 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 6066 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 6067 } 6068 6069 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 6070 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 6071 return Success(FD); 6072 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 6073 return VisitVarDecl(E, VD); 6074 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 6075 return Visit(BD->getBinding()); 6076 return Error(E); 6077 } 6078 6079 6080 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 6081 6082 // If we are within a lambda's call operator, check whether the 'VD' referred 6083 // to within 'E' actually represents a lambda-capture that maps to a 6084 // data-member/field within the closure object, and if so, evaluate to the 6085 // field or what the field refers to. 6086 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 6087 isa<DeclRefExpr>(E) && 6088 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 6089 // We don't always have a complete capture-map when checking or inferring if 6090 // the function call operator meets the requirements of a constexpr function 6091 // - but we don't need to evaluate the captures to determine constexprness 6092 // (dcl.constexpr C++17). 6093 if (Info.checkingPotentialConstantExpression()) 6094 return false; 6095 6096 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 6097 // Start with 'Result' referring to the complete closure object... 6098 Result = *Info.CurrentCall->This; 6099 // ... then update it to refer to the field of the closure object 6100 // that represents the capture. 6101 if (!HandleLValueMember(Info, E, Result, FD)) 6102 return false; 6103 // And if the field is of reference type, update 'Result' to refer to what 6104 // the field refers to. 6105 if (FD->getType()->isReferenceType()) { 6106 APValue RVal; 6107 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 6108 RVal)) 6109 return false; 6110 Result.setFrom(Info.Ctx, RVal); 6111 } 6112 return true; 6113 } 6114 } 6115 CallStackFrame *Frame = nullptr; 6116 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 6117 // Only if a local variable was declared in the function currently being 6118 // evaluated, do we expect to be able to find its value in the current 6119 // frame. (Otherwise it was likely declared in an enclosing context and 6120 // could either have a valid evaluatable value (for e.g. a constexpr 6121 // variable) or be ill-formed (and trigger an appropriate evaluation 6122 // diagnostic)). 6123 if (Info.CurrentCall->Callee && 6124 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 6125 Frame = Info.CurrentCall; 6126 } 6127 } 6128 6129 if (!VD->getType()->isReferenceType()) { 6130 if (Frame) { 6131 Result.set({VD, Frame->Index, 6132 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 6133 return true; 6134 } 6135 return Success(VD); 6136 } 6137 6138 APValue *V; 6139 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 6140 return false; 6141 if (!V->hasValue()) { 6142 // FIXME: Is it possible for V to be indeterminate here? If so, we should 6143 // adjust the diagnostic to say that. 6144 if (!Info.checkingPotentialConstantExpression()) 6145 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 6146 return false; 6147 } 6148 return Success(*V, E); 6149 } 6150 6151 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 6152 const MaterializeTemporaryExpr *E) { 6153 // Walk through the expression to find the materialized temporary itself. 6154 SmallVector<const Expr *, 2> CommaLHSs; 6155 SmallVector<SubobjectAdjustment, 2> Adjustments; 6156 const Expr *Inner = E->GetTemporaryExpr()-> 6157 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 6158 6159 // If we passed any comma operators, evaluate their LHSs. 6160 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 6161 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 6162 return false; 6163 6164 // A materialized temporary with static storage duration can appear within the 6165 // result of a constant expression evaluation, so we need to preserve its 6166 // value for use outside this evaluation. 6167 APValue *Value; 6168 if (E->getStorageDuration() == SD_Static) { 6169 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 6170 *Value = APValue(); 6171 Result.set(E); 6172 } else { 6173 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result, 6174 *Info.CurrentCall); 6175 } 6176 6177 QualType Type = Inner->getType(); 6178 6179 // Materialize the temporary itself. 6180 if (!EvaluateInPlace(*Value, Info, Result, Inner) || 6181 (E->getStorageDuration() == SD_Static && 6182 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) { 6183 *Value = APValue(); 6184 return false; 6185 } 6186 6187 // Adjust our lvalue to refer to the desired subobject. 6188 for (unsigned I = Adjustments.size(); I != 0; /**/) { 6189 --I; 6190 switch (Adjustments[I].Kind) { 6191 case SubobjectAdjustment::DerivedToBaseAdjustment: 6192 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 6193 Type, Result)) 6194 return false; 6195 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 6196 break; 6197 6198 case SubobjectAdjustment::FieldAdjustment: 6199 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 6200 return false; 6201 Type = Adjustments[I].Field->getType(); 6202 break; 6203 6204 case SubobjectAdjustment::MemberPointerAdjustment: 6205 if (!HandleMemberPointerAccess(this->Info, Type, Result, 6206 Adjustments[I].Ptr.RHS)) 6207 return false; 6208 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 6209 break; 6210 } 6211 } 6212 6213 return true; 6214 } 6215 6216 bool 6217 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 6218 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 6219 "lvalue compound literal in c++?"); 6220 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 6221 // only see this when folding in C, so there's no standard to follow here. 6222 return Success(E); 6223 } 6224 6225 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 6226 TypeInfoLValue TypeInfo; 6227 6228 if (!E->isPotentiallyEvaluated()) { 6229 if (E->isTypeOperand()) 6230 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 6231 else 6232 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 6233 } else { 6234 if (!Info.Ctx.getLangOpts().CPlusPlus2a) { 6235 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 6236 << E->getExprOperand()->getType() 6237 << E->getExprOperand()->getSourceRange(); 6238 } 6239 6240 if (!Visit(E->getExprOperand())) 6241 return false; 6242 6243 Optional<DynamicType> DynType = 6244 ComputeDynamicType(Info, E, Result, AK_TypeId); 6245 if (!DynType) 6246 return false; 6247 6248 TypeInfo = 6249 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 6250 } 6251 6252 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 6253 } 6254 6255 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 6256 return Success(E); 6257 } 6258 6259 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 6260 // Handle static data members. 6261 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 6262 VisitIgnoredBaseExpression(E->getBase()); 6263 return VisitVarDecl(E, VD); 6264 } 6265 6266 // Handle static member functions. 6267 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 6268 if (MD->isStatic()) { 6269 VisitIgnoredBaseExpression(E->getBase()); 6270 return Success(MD); 6271 } 6272 } 6273 6274 // Handle non-static data members. 6275 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 6276 } 6277 6278 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 6279 // FIXME: Deal with vectors as array subscript bases. 6280 if (E->getBase()->getType()->isVectorType()) 6281 return Error(E); 6282 6283 bool Success = true; 6284 if (!evaluatePointer(E->getBase(), Result)) { 6285 if (!Info.noteFailure()) 6286 return false; 6287 Success = false; 6288 } 6289 6290 APSInt Index; 6291 if (!EvaluateInteger(E->getIdx(), Index, Info)) 6292 return false; 6293 6294 return Success && 6295 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 6296 } 6297 6298 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 6299 return evaluatePointer(E->getSubExpr(), Result); 6300 } 6301 6302 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 6303 if (!Visit(E->getSubExpr())) 6304 return false; 6305 // __real is a no-op on scalar lvalues. 6306 if (E->getSubExpr()->getType()->isAnyComplexType()) 6307 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 6308 return true; 6309 } 6310 6311 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 6312 assert(E->getSubExpr()->getType()->isAnyComplexType() && 6313 "lvalue __imag__ on scalar?"); 6314 if (!Visit(E->getSubExpr())) 6315 return false; 6316 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 6317 return true; 6318 } 6319 6320 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 6321 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6322 return Error(UO); 6323 6324 if (!this->Visit(UO->getSubExpr())) 6325 return false; 6326 6327 return handleIncDec( 6328 this->Info, UO, Result, UO->getSubExpr()->getType(), 6329 UO->isIncrementOp(), nullptr); 6330 } 6331 6332 bool LValueExprEvaluator::VisitCompoundAssignOperator( 6333 const CompoundAssignOperator *CAO) { 6334 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6335 return Error(CAO); 6336 6337 APValue RHS; 6338 6339 // The overall lvalue result is the result of evaluating the LHS. 6340 if (!this->Visit(CAO->getLHS())) { 6341 if (Info.noteFailure()) 6342 Evaluate(RHS, this->Info, CAO->getRHS()); 6343 return false; 6344 } 6345 6346 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 6347 return false; 6348 6349 return handleCompoundAssignment( 6350 this->Info, CAO, 6351 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 6352 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 6353 } 6354 6355 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 6356 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6357 return Error(E); 6358 6359 APValue NewVal; 6360 6361 if (!this->Visit(E->getLHS())) { 6362 if (Info.noteFailure()) 6363 Evaluate(NewVal, this->Info, E->getRHS()); 6364 return false; 6365 } 6366 6367 if (!Evaluate(NewVal, this->Info, E->getRHS())) 6368 return false; 6369 6370 if (Info.getLangOpts().CPlusPlus2a && 6371 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 6372 return false; 6373 6374 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 6375 NewVal); 6376 } 6377 6378 //===----------------------------------------------------------------------===// 6379 // Pointer Evaluation 6380 //===----------------------------------------------------------------------===// 6381 6382 /// Attempts to compute the number of bytes available at the pointer 6383 /// returned by a function with the alloc_size attribute. Returns true if we 6384 /// were successful. Places an unsigned number into `Result`. 6385 /// 6386 /// This expects the given CallExpr to be a call to a function with an 6387 /// alloc_size attribute. 6388 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 6389 const CallExpr *Call, 6390 llvm::APInt &Result) { 6391 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 6392 6393 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 6394 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 6395 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 6396 if (Call->getNumArgs() <= SizeArgNo) 6397 return false; 6398 6399 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 6400 Expr::EvalResult ExprResult; 6401 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 6402 return false; 6403 Into = ExprResult.Val.getInt(); 6404 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 6405 return false; 6406 Into = Into.zextOrSelf(BitsInSizeT); 6407 return true; 6408 }; 6409 6410 APSInt SizeOfElem; 6411 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 6412 return false; 6413 6414 if (!AllocSize->getNumElemsParam().isValid()) { 6415 Result = std::move(SizeOfElem); 6416 return true; 6417 } 6418 6419 APSInt NumberOfElems; 6420 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 6421 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 6422 return false; 6423 6424 bool Overflow; 6425 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 6426 if (Overflow) 6427 return false; 6428 6429 Result = std::move(BytesAvailable); 6430 return true; 6431 } 6432 6433 /// Convenience function. LVal's base must be a call to an alloc_size 6434 /// function. 6435 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 6436 const LValue &LVal, 6437 llvm::APInt &Result) { 6438 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 6439 "Can't get the size of a non alloc_size function"); 6440 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 6441 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 6442 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 6443 } 6444 6445 /// Attempts to evaluate the given LValueBase as the result of a call to 6446 /// a function with the alloc_size attribute. If it was possible to do so, this 6447 /// function will return true, make Result's Base point to said function call, 6448 /// and mark Result's Base as invalid. 6449 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 6450 LValue &Result) { 6451 if (Base.isNull()) 6452 return false; 6453 6454 // Because we do no form of static analysis, we only support const variables. 6455 // 6456 // Additionally, we can't support parameters, nor can we support static 6457 // variables (in the latter case, use-before-assign isn't UB; in the former, 6458 // we have no clue what they'll be assigned to). 6459 const auto *VD = 6460 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 6461 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 6462 return false; 6463 6464 const Expr *Init = VD->getAnyInitializer(); 6465 if (!Init) 6466 return false; 6467 6468 const Expr *E = Init->IgnoreParens(); 6469 if (!tryUnwrapAllocSizeCall(E)) 6470 return false; 6471 6472 // Store E instead of E unwrapped so that the type of the LValue's base is 6473 // what the user wanted. 6474 Result.setInvalid(E); 6475 6476 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 6477 Result.addUnsizedArray(Info, E, Pointee); 6478 return true; 6479 } 6480 6481 namespace { 6482 class PointerExprEvaluator 6483 : public ExprEvaluatorBase<PointerExprEvaluator> { 6484 LValue &Result; 6485 bool InvalidBaseOK; 6486 6487 bool Success(const Expr *E) { 6488 Result.set(E); 6489 return true; 6490 } 6491 6492 bool evaluateLValue(const Expr *E, LValue &Result) { 6493 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 6494 } 6495 6496 bool evaluatePointer(const Expr *E, LValue &Result) { 6497 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 6498 } 6499 6500 bool visitNonBuiltinCallExpr(const CallExpr *E); 6501 public: 6502 6503 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 6504 : ExprEvaluatorBaseTy(info), Result(Result), 6505 InvalidBaseOK(InvalidBaseOK) {} 6506 6507 bool Success(const APValue &V, const Expr *E) { 6508 Result.setFrom(Info.Ctx, V); 6509 return true; 6510 } 6511 bool ZeroInitialization(const Expr *E) { 6512 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 6513 Result.setNull(E->getType(), TargetVal); 6514 return true; 6515 } 6516 6517 bool VisitBinaryOperator(const BinaryOperator *E); 6518 bool VisitCastExpr(const CastExpr* E); 6519 bool VisitUnaryAddrOf(const UnaryOperator *E); 6520 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 6521 { return Success(E); } 6522 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 6523 if (E->isExpressibleAsConstantInitializer()) 6524 return Success(E); 6525 if (Info.noteFailure()) 6526 EvaluateIgnoredValue(Info, E->getSubExpr()); 6527 return Error(E); 6528 } 6529 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 6530 { return Success(E); } 6531 bool VisitCallExpr(const CallExpr *E); 6532 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 6533 bool VisitBlockExpr(const BlockExpr *E) { 6534 if (!E->getBlockDecl()->hasCaptures()) 6535 return Success(E); 6536 return Error(E); 6537 } 6538 bool VisitCXXThisExpr(const CXXThisExpr *E) { 6539 // Can't look at 'this' when checking a potential constant expression. 6540 if (Info.checkingPotentialConstantExpression()) 6541 return false; 6542 if (!Info.CurrentCall->This) { 6543 if (Info.getLangOpts().CPlusPlus11) 6544 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 6545 else 6546 Info.FFDiag(E); 6547 return false; 6548 } 6549 Result = *Info.CurrentCall->This; 6550 // If we are inside a lambda's call operator, the 'this' expression refers 6551 // to the enclosing '*this' object (either by value or reference) which is 6552 // either copied into the closure object's field that represents the '*this' 6553 // or refers to '*this'. 6554 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 6555 // Update 'Result' to refer to the data member/field of the closure object 6556 // that represents the '*this' capture. 6557 if (!HandleLValueMember(Info, E, Result, 6558 Info.CurrentCall->LambdaThisCaptureField)) 6559 return false; 6560 // If we captured '*this' by reference, replace the field with its referent. 6561 if (Info.CurrentCall->LambdaThisCaptureField->getType() 6562 ->isPointerType()) { 6563 APValue RVal; 6564 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 6565 RVal)) 6566 return false; 6567 6568 Result.setFrom(Info.Ctx, RVal); 6569 } 6570 } 6571 return true; 6572 } 6573 6574 bool VisitSourceLocExpr(const SourceLocExpr *E) { 6575 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 6576 APValue LValResult = E->EvaluateInContext( 6577 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 6578 Result.setFrom(Info.Ctx, LValResult); 6579 return true; 6580 } 6581 6582 // FIXME: Missing: @protocol, @selector 6583 }; 6584 } // end anonymous namespace 6585 6586 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 6587 bool InvalidBaseOK) { 6588 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 6589 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 6590 } 6591 6592 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 6593 if (E->getOpcode() != BO_Add && 6594 E->getOpcode() != BO_Sub) 6595 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 6596 6597 const Expr *PExp = E->getLHS(); 6598 const Expr *IExp = E->getRHS(); 6599 if (IExp->getType()->isPointerType()) 6600 std::swap(PExp, IExp); 6601 6602 bool EvalPtrOK = evaluatePointer(PExp, Result); 6603 if (!EvalPtrOK && !Info.noteFailure()) 6604 return false; 6605 6606 llvm::APSInt Offset; 6607 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 6608 return false; 6609 6610 if (E->getOpcode() == BO_Sub) 6611 negateAsSigned(Offset); 6612 6613 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 6614 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 6615 } 6616 6617 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 6618 return evaluateLValue(E->getSubExpr(), Result); 6619 } 6620 6621 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 6622 const Expr *SubExpr = E->getSubExpr(); 6623 6624 switch (E->getCastKind()) { 6625 default: 6626 break; 6627 6628 case CK_BitCast: 6629 case CK_CPointerToObjCPointerCast: 6630 case CK_BlockPointerToObjCPointerCast: 6631 case CK_AnyPointerToBlockPointerCast: 6632 case CK_AddressSpaceConversion: 6633 if (!Visit(SubExpr)) 6634 return false; 6635 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 6636 // permitted in constant expressions in C++11. Bitcasts from cv void* are 6637 // also static_casts, but we disallow them as a resolution to DR1312. 6638 if (!E->getType()->isVoidPointerType()) { 6639 Result.Designator.setInvalid(); 6640 if (SubExpr->getType()->isVoidPointerType()) 6641 CCEDiag(E, diag::note_constexpr_invalid_cast) 6642 << 3 << SubExpr->getType(); 6643 else 6644 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 6645 } 6646 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 6647 ZeroInitialization(E); 6648 return true; 6649 6650 case CK_DerivedToBase: 6651 case CK_UncheckedDerivedToBase: 6652 if (!evaluatePointer(E->getSubExpr(), Result)) 6653 return false; 6654 if (!Result.Base && Result.Offset.isZero()) 6655 return true; 6656 6657 // Now figure out the necessary offset to add to the base LV to get from 6658 // the derived class to the base class. 6659 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 6660 castAs<PointerType>()->getPointeeType(), 6661 Result); 6662 6663 case CK_BaseToDerived: 6664 if (!Visit(E->getSubExpr())) 6665 return false; 6666 if (!Result.Base && Result.Offset.isZero()) 6667 return true; 6668 return HandleBaseToDerivedCast(Info, E, Result); 6669 6670 case CK_Dynamic: 6671 if (!Visit(E->getSubExpr())) 6672 return false; 6673 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 6674 6675 case CK_NullToPointer: 6676 VisitIgnoredValue(E->getSubExpr()); 6677 return ZeroInitialization(E); 6678 6679 case CK_IntegralToPointer: { 6680 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 6681 6682 APValue Value; 6683 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 6684 break; 6685 6686 if (Value.isInt()) { 6687 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 6688 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 6689 Result.Base = (Expr*)nullptr; 6690 Result.InvalidBase = false; 6691 Result.Offset = CharUnits::fromQuantity(N); 6692 Result.Designator.setInvalid(); 6693 Result.IsNullPtr = false; 6694 return true; 6695 } else { 6696 // Cast is of an lvalue, no need to change value. 6697 Result.setFrom(Info.Ctx, Value); 6698 return true; 6699 } 6700 } 6701 6702 case CK_ArrayToPointerDecay: { 6703 if (SubExpr->isGLValue()) { 6704 if (!evaluateLValue(SubExpr, Result)) 6705 return false; 6706 } else { 6707 APValue &Value = createTemporary(SubExpr, false, Result, 6708 *Info.CurrentCall); 6709 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 6710 return false; 6711 } 6712 // The result is a pointer to the first element of the array. 6713 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 6714 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 6715 Result.addArray(Info, E, CAT); 6716 else 6717 Result.addUnsizedArray(Info, E, AT->getElementType()); 6718 return true; 6719 } 6720 6721 case CK_FunctionToPointerDecay: 6722 return evaluateLValue(SubExpr, Result); 6723 6724 case CK_LValueToRValue: { 6725 LValue LVal; 6726 if (!evaluateLValue(E->getSubExpr(), LVal)) 6727 return false; 6728 6729 APValue RVal; 6730 // Note, we use the subexpression's type in order to retain cv-qualifiers. 6731 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 6732 LVal, RVal)) 6733 return InvalidBaseOK && 6734 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 6735 return Success(RVal, E); 6736 } 6737 } 6738 6739 return ExprEvaluatorBaseTy::VisitCastExpr(E); 6740 } 6741 6742 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 6743 UnaryExprOrTypeTrait ExprKind) { 6744 // C++ [expr.alignof]p3: 6745 // When alignof is applied to a reference type, the result is the 6746 // alignment of the referenced type. 6747 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 6748 T = Ref->getPointeeType(); 6749 6750 if (T.getQualifiers().hasUnaligned()) 6751 return CharUnits::One(); 6752 6753 const bool AlignOfReturnsPreferred = 6754 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 6755 6756 // __alignof is defined to return the preferred alignment. 6757 // Before 8, clang returned the preferred alignment for alignof and _Alignof 6758 // as well. 6759 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 6760 return Info.Ctx.toCharUnitsFromBits( 6761 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 6762 // alignof and _Alignof are defined to return the ABI alignment. 6763 else if (ExprKind == UETT_AlignOf) 6764 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 6765 else 6766 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 6767 } 6768 6769 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 6770 UnaryExprOrTypeTrait ExprKind) { 6771 E = E->IgnoreParens(); 6772 6773 // The kinds of expressions that we have special-case logic here for 6774 // should be kept up to date with the special checks for those 6775 // expressions in Sema. 6776 6777 // alignof decl is always accepted, even if it doesn't make sense: we default 6778 // to 1 in those cases. 6779 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 6780 return Info.Ctx.getDeclAlign(DRE->getDecl(), 6781 /*RefAsPointee*/true); 6782 6783 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 6784 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 6785 /*RefAsPointee*/true); 6786 6787 return GetAlignOfType(Info, E->getType(), ExprKind); 6788 } 6789 6790 // To be clear: this happily visits unsupported builtins. Better name welcomed. 6791 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 6792 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 6793 return true; 6794 6795 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 6796 return false; 6797 6798 Result.setInvalid(E); 6799 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 6800 Result.addUnsizedArray(Info, E, PointeeTy); 6801 return true; 6802 } 6803 6804 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 6805 if (IsStringLiteralCall(E)) 6806 return Success(E); 6807 6808 if (unsigned BuiltinOp = E->getBuiltinCallee()) 6809 return VisitBuiltinCallExpr(E, BuiltinOp); 6810 6811 return visitNonBuiltinCallExpr(E); 6812 } 6813 6814 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 6815 unsigned BuiltinOp) { 6816 switch (BuiltinOp) { 6817 case Builtin::BI__builtin_addressof: 6818 return evaluateLValue(E->getArg(0), Result); 6819 case Builtin::BI__builtin_assume_aligned: { 6820 // We need to be very careful here because: if the pointer does not have the 6821 // asserted alignment, then the behavior is undefined, and undefined 6822 // behavior is non-constant. 6823 if (!evaluatePointer(E->getArg(0), Result)) 6824 return false; 6825 6826 LValue OffsetResult(Result); 6827 APSInt Alignment; 6828 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 6829 return false; 6830 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 6831 6832 if (E->getNumArgs() > 2) { 6833 APSInt Offset; 6834 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 6835 return false; 6836 6837 int64_t AdditionalOffset = -Offset.getZExtValue(); 6838 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 6839 } 6840 6841 // If there is a base object, then it must have the correct alignment. 6842 if (OffsetResult.Base) { 6843 CharUnits BaseAlignment; 6844 if (const ValueDecl *VD = 6845 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 6846 BaseAlignment = Info.Ctx.getDeclAlign(VD); 6847 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) { 6848 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf); 6849 } else { 6850 BaseAlignment = GetAlignOfType( 6851 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf); 6852 } 6853 6854 if (BaseAlignment < Align) { 6855 Result.Designator.setInvalid(); 6856 // FIXME: Add support to Diagnostic for long / long long. 6857 CCEDiag(E->getArg(0), 6858 diag::note_constexpr_baa_insufficient_alignment) << 0 6859 << (unsigned)BaseAlignment.getQuantity() 6860 << (unsigned)Align.getQuantity(); 6861 return false; 6862 } 6863 } 6864 6865 // The offset must also have the correct alignment. 6866 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 6867 Result.Designator.setInvalid(); 6868 6869 (OffsetResult.Base 6870 ? CCEDiag(E->getArg(0), 6871 diag::note_constexpr_baa_insufficient_alignment) << 1 6872 : CCEDiag(E->getArg(0), 6873 diag::note_constexpr_baa_value_insufficient_alignment)) 6874 << (int)OffsetResult.Offset.getQuantity() 6875 << (unsigned)Align.getQuantity(); 6876 return false; 6877 } 6878 6879 return true; 6880 } 6881 case Builtin::BI__builtin_launder: 6882 return evaluatePointer(E->getArg(0), Result); 6883 case Builtin::BIstrchr: 6884 case Builtin::BIwcschr: 6885 case Builtin::BImemchr: 6886 case Builtin::BIwmemchr: 6887 if (Info.getLangOpts().CPlusPlus11) 6888 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6889 << /*isConstexpr*/0 << /*isConstructor*/0 6890 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 6891 else 6892 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6893 LLVM_FALLTHROUGH; 6894 case Builtin::BI__builtin_strchr: 6895 case Builtin::BI__builtin_wcschr: 6896 case Builtin::BI__builtin_memchr: 6897 case Builtin::BI__builtin_char_memchr: 6898 case Builtin::BI__builtin_wmemchr: { 6899 if (!Visit(E->getArg(0))) 6900 return false; 6901 APSInt Desired; 6902 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 6903 return false; 6904 uint64_t MaxLength = uint64_t(-1); 6905 if (BuiltinOp != Builtin::BIstrchr && 6906 BuiltinOp != Builtin::BIwcschr && 6907 BuiltinOp != Builtin::BI__builtin_strchr && 6908 BuiltinOp != Builtin::BI__builtin_wcschr) { 6909 APSInt N; 6910 if (!EvaluateInteger(E->getArg(2), N, Info)) 6911 return false; 6912 MaxLength = N.getExtValue(); 6913 } 6914 // We cannot find the value if there are no candidates to match against. 6915 if (MaxLength == 0u) 6916 return ZeroInitialization(E); 6917 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 6918 Result.Designator.Invalid) 6919 return false; 6920 QualType CharTy = Result.Designator.getType(Info.Ctx); 6921 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 6922 BuiltinOp == Builtin::BI__builtin_memchr; 6923 assert(IsRawByte || 6924 Info.Ctx.hasSameUnqualifiedType( 6925 CharTy, E->getArg(0)->getType()->getPointeeType())); 6926 // Pointers to const void may point to objects of incomplete type. 6927 if (IsRawByte && CharTy->isIncompleteType()) { 6928 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 6929 return false; 6930 } 6931 // Give up on byte-oriented matching against multibyte elements. 6932 // FIXME: We can compare the bytes in the correct order. 6933 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One()) 6934 return false; 6935 // Figure out what value we're actually looking for (after converting to 6936 // the corresponding unsigned type if necessary). 6937 uint64_t DesiredVal; 6938 bool StopAtNull = false; 6939 switch (BuiltinOp) { 6940 case Builtin::BIstrchr: 6941 case Builtin::BI__builtin_strchr: 6942 // strchr compares directly to the passed integer, and therefore 6943 // always fails if given an int that is not a char. 6944 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 6945 E->getArg(1)->getType(), 6946 Desired), 6947 Desired)) 6948 return ZeroInitialization(E); 6949 StopAtNull = true; 6950 LLVM_FALLTHROUGH; 6951 case Builtin::BImemchr: 6952 case Builtin::BI__builtin_memchr: 6953 case Builtin::BI__builtin_char_memchr: 6954 // memchr compares by converting both sides to unsigned char. That's also 6955 // correct for strchr if we get this far (to cope with plain char being 6956 // unsigned in the strchr case). 6957 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 6958 break; 6959 6960 case Builtin::BIwcschr: 6961 case Builtin::BI__builtin_wcschr: 6962 StopAtNull = true; 6963 LLVM_FALLTHROUGH; 6964 case Builtin::BIwmemchr: 6965 case Builtin::BI__builtin_wmemchr: 6966 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 6967 DesiredVal = Desired.getZExtValue(); 6968 break; 6969 } 6970 6971 for (; MaxLength; --MaxLength) { 6972 APValue Char; 6973 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 6974 !Char.isInt()) 6975 return false; 6976 if (Char.getInt().getZExtValue() == DesiredVal) 6977 return true; 6978 if (StopAtNull && !Char.getInt()) 6979 break; 6980 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 6981 return false; 6982 } 6983 // Not found: return nullptr. 6984 return ZeroInitialization(E); 6985 } 6986 6987 case Builtin::BImemcpy: 6988 case Builtin::BImemmove: 6989 case Builtin::BIwmemcpy: 6990 case Builtin::BIwmemmove: 6991 if (Info.getLangOpts().CPlusPlus11) 6992 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 6993 << /*isConstexpr*/0 << /*isConstructor*/0 6994 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 6995 else 6996 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 6997 LLVM_FALLTHROUGH; 6998 case Builtin::BI__builtin_memcpy: 6999 case Builtin::BI__builtin_memmove: 7000 case Builtin::BI__builtin_wmemcpy: 7001 case Builtin::BI__builtin_wmemmove: { 7002 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 7003 BuiltinOp == Builtin::BIwmemmove || 7004 BuiltinOp == Builtin::BI__builtin_wmemcpy || 7005 BuiltinOp == Builtin::BI__builtin_wmemmove; 7006 bool Move = BuiltinOp == Builtin::BImemmove || 7007 BuiltinOp == Builtin::BIwmemmove || 7008 BuiltinOp == Builtin::BI__builtin_memmove || 7009 BuiltinOp == Builtin::BI__builtin_wmemmove; 7010 7011 // The result of mem* is the first argument. 7012 if (!Visit(E->getArg(0))) 7013 return false; 7014 LValue Dest = Result; 7015 7016 LValue Src; 7017 if (!EvaluatePointer(E->getArg(1), Src, Info)) 7018 return false; 7019 7020 APSInt N; 7021 if (!EvaluateInteger(E->getArg(2), N, Info)) 7022 return false; 7023 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 7024 7025 // If the size is zero, we treat this as always being a valid no-op. 7026 // (Even if one of the src and dest pointers is null.) 7027 if (!N) 7028 return true; 7029 7030 // Otherwise, if either of the operands is null, we can't proceed. Don't 7031 // try to determine the type of the copied objects, because there aren't 7032 // any. 7033 if (!Src.Base || !Dest.Base) { 7034 APValue Val; 7035 (!Src.Base ? Src : Dest).moveInto(Val); 7036 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 7037 << Move << WChar << !!Src.Base 7038 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 7039 return false; 7040 } 7041 if (Src.Designator.Invalid || Dest.Designator.Invalid) 7042 return false; 7043 7044 // We require that Src and Dest are both pointers to arrays of 7045 // trivially-copyable type. (For the wide version, the designator will be 7046 // invalid if the designated object is not a wchar_t.) 7047 QualType T = Dest.Designator.getType(Info.Ctx); 7048 QualType SrcT = Src.Designator.getType(Info.Ctx); 7049 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 7050 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 7051 return false; 7052 } 7053 if (T->isIncompleteType()) { 7054 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 7055 return false; 7056 } 7057 if (!T.isTriviallyCopyableType(Info.Ctx)) { 7058 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 7059 return false; 7060 } 7061 7062 // Figure out how many T's we're copying. 7063 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 7064 if (!WChar) { 7065 uint64_t Remainder; 7066 llvm::APInt OrigN = N; 7067 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 7068 if (Remainder) { 7069 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 7070 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 7071 << (unsigned)TSize; 7072 return false; 7073 } 7074 } 7075 7076 // Check that the copying will remain within the arrays, just so that we 7077 // can give a more meaningful diagnostic. This implicitly also checks that 7078 // N fits into 64 bits. 7079 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 7080 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 7081 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 7082 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 7083 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 7084 << N.toString(10, /*Signed*/false); 7085 return false; 7086 } 7087 uint64_t NElems = N.getZExtValue(); 7088 uint64_t NBytes = NElems * TSize; 7089 7090 // Check for overlap. 7091 int Direction = 1; 7092 if (HasSameBase(Src, Dest)) { 7093 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 7094 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 7095 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 7096 // Dest is inside the source region. 7097 if (!Move) { 7098 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 7099 return false; 7100 } 7101 // For memmove and friends, copy backwards. 7102 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 7103 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 7104 return false; 7105 Direction = -1; 7106 } else if (!Move && SrcOffset >= DestOffset && 7107 SrcOffset - DestOffset < NBytes) { 7108 // Src is inside the destination region for memcpy: invalid. 7109 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 7110 return false; 7111 } 7112 } 7113 7114 while (true) { 7115 APValue Val; 7116 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 7117 !handleAssignment(Info, E, Dest, T, Val)) 7118 return false; 7119 // Do not iterate past the last element; if we're copying backwards, that 7120 // might take us off the start of the array. 7121 if (--NElems == 0) 7122 return true; 7123 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 7124 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 7125 return false; 7126 } 7127 } 7128 7129 default: 7130 return visitNonBuiltinCallExpr(E); 7131 } 7132 } 7133 7134 //===----------------------------------------------------------------------===// 7135 // Member Pointer Evaluation 7136 //===----------------------------------------------------------------------===// 7137 7138 namespace { 7139 class MemberPointerExprEvaluator 7140 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 7141 MemberPtr &Result; 7142 7143 bool Success(const ValueDecl *D) { 7144 Result = MemberPtr(D); 7145 return true; 7146 } 7147 public: 7148 7149 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 7150 : ExprEvaluatorBaseTy(Info), Result(Result) {} 7151 7152 bool Success(const APValue &V, const Expr *E) { 7153 Result.setFrom(V); 7154 return true; 7155 } 7156 bool ZeroInitialization(const Expr *E) { 7157 return Success((const ValueDecl*)nullptr); 7158 } 7159 7160 bool VisitCastExpr(const CastExpr *E); 7161 bool VisitUnaryAddrOf(const UnaryOperator *E); 7162 }; 7163 } // end anonymous namespace 7164 7165 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 7166 EvalInfo &Info) { 7167 assert(E->isRValue() && E->getType()->isMemberPointerType()); 7168 return MemberPointerExprEvaluator(Info, Result).Visit(E); 7169 } 7170 7171 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 7172 switch (E->getCastKind()) { 7173 default: 7174 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7175 7176 case CK_NullToMemberPointer: 7177 VisitIgnoredValue(E->getSubExpr()); 7178 return ZeroInitialization(E); 7179 7180 case CK_BaseToDerivedMemberPointer: { 7181 if (!Visit(E->getSubExpr())) 7182 return false; 7183 if (E->path_empty()) 7184 return true; 7185 // Base-to-derived member pointer casts store the path in derived-to-base 7186 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 7187 // the wrong end of the derived->base arc, so stagger the path by one class. 7188 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 7189 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 7190 PathI != PathE; ++PathI) { 7191 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 7192 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 7193 if (!Result.castToDerived(Derived)) 7194 return Error(E); 7195 } 7196 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 7197 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 7198 return Error(E); 7199 return true; 7200 } 7201 7202 case CK_DerivedToBaseMemberPointer: 7203 if (!Visit(E->getSubExpr())) 7204 return false; 7205 for (CastExpr::path_const_iterator PathI = E->path_begin(), 7206 PathE = E->path_end(); PathI != PathE; ++PathI) { 7207 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 7208 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 7209 if (!Result.castToBase(Base)) 7210 return Error(E); 7211 } 7212 return true; 7213 } 7214 } 7215 7216 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 7217 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 7218 // member can be formed. 7219 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 7220 } 7221 7222 //===----------------------------------------------------------------------===// 7223 // Record Evaluation 7224 //===----------------------------------------------------------------------===// 7225 7226 namespace { 7227 class RecordExprEvaluator 7228 : public ExprEvaluatorBase<RecordExprEvaluator> { 7229 const LValue &This; 7230 APValue &Result; 7231 public: 7232 7233 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 7234 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 7235 7236 bool Success(const APValue &V, const Expr *E) { 7237 Result = V; 7238 return true; 7239 } 7240 bool ZeroInitialization(const Expr *E) { 7241 return ZeroInitialization(E, E->getType()); 7242 } 7243 bool ZeroInitialization(const Expr *E, QualType T); 7244 7245 bool VisitCallExpr(const CallExpr *E) { 7246 return handleCallExpr(E, Result, &This); 7247 } 7248 bool VisitCastExpr(const CastExpr *E); 7249 bool VisitInitListExpr(const InitListExpr *E); 7250 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 7251 return VisitCXXConstructExpr(E, E->getType()); 7252 } 7253 bool VisitLambdaExpr(const LambdaExpr *E); 7254 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 7255 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 7256 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 7257 7258 bool VisitBinCmp(const BinaryOperator *E); 7259 }; 7260 } 7261 7262 /// Perform zero-initialization on an object of non-union class type. 7263 /// C++11 [dcl.init]p5: 7264 /// To zero-initialize an object or reference of type T means: 7265 /// [...] 7266 /// -- if T is a (possibly cv-qualified) non-union class type, 7267 /// each non-static data member and each base-class subobject is 7268 /// zero-initialized 7269 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 7270 const RecordDecl *RD, 7271 const LValue &This, APValue &Result) { 7272 assert(!RD->isUnion() && "Expected non-union class type"); 7273 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 7274 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 7275 std::distance(RD->field_begin(), RD->field_end())); 7276 7277 if (RD->isInvalidDecl()) return false; 7278 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7279 7280 if (CD) { 7281 unsigned Index = 0; 7282 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 7283 End = CD->bases_end(); I != End; ++I, ++Index) { 7284 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 7285 LValue Subobject = This; 7286 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 7287 return false; 7288 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 7289 Result.getStructBase(Index))) 7290 return false; 7291 } 7292 } 7293 7294 for (const auto *I : RD->fields()) { 7295 // -- if T is a reference type, no initialization is performed. 7296 if (I->getType()->isReferenceType()) 7297 continue; 7298 7299 LValue Subobject = This; 7300 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 7301 return false; 7302 7303 ImplicitValueInitExpr VIE(I->getType()); 7304 if (!EvaluateInPlace( 7305 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 7306 return false; 7307 } 7308 7309 return true; 7310 } 7311 7312 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 7313 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 7314 if (RD->isInvalidDecl()) return false; 7315 if (RD->isUnion()) { 7316 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 7317 // object's first non-static named data member is zero-initialized 7318 RecordDecl::field_iterator I = RD->field_begin(); 7319 if (I == RD->field_end()) { 7320 Result = APValue((const FieldDecl*)nullptr); 7321 return true; 7322 } 7323 7324 LValue Subobject = This; 7325 if (!HandleLValueMember(Info, E, Subobject, *I)) 7326 return false; 7327 Result = APValue(*I); 7328 ImplicitValueInitExpr VIE(I->getType()); 7329 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 7330 } 7331 7332 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 7333 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 7334 return false; 7335 } 7336 7337 return HandleClassZeroInitialization(Info, E, RD, This, Result); 7338 } 7339 7340 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 7341 switch (E->getCastKind()) { 7342 default: 7343 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7344 7345 case CK_ConstructorConversion: 7346 return Visit(E->getSubExpr()); 7347 7348 case CK_DerivedToBase: 7349 case CK_UncheckedDerivedToBase: { 7350 APValue DerivedObject; 7351 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 7352 return false; 7353 if (!DerivedObject.isStruct()) 7354 return Error(E->getSubExpr()); 7355 7356 // Derived-to-base rvalue conversion: just slice off the derived part. 7357 APValue *Value = &DerivedObject; 7358 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 7359 for (CastExpr::path_const_iterator PathI = E->path_begin(), 7360 PathE = E->path_end(); PathI != PathE; ++PathI) { 7361 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 7362 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 7363 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 7364 RD = Base; 7365 } 7366 Result = *Value; 7367 return true; 7368 } 7369 } 7370 } 7371 7372 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7373 if (E->isTransparent()) 7374 return Visit(E->getInit(0)); 7375 7376 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 7377 if (RD->isInvalidDecl()) return false; 7378 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 7379 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 7380 7381 EvalInfo::EvaluatingConstructorRAII EvalObj( 7382 Info, 7383 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 7384 CXXRD && CXXRD->getNumBases()); 7385 7386 if (RD->isUnion()) { 7387 const FieldDecl *Field = E->getInitializedFieldInUnion(); 7388 Result = APValue(Field); 7389 if (!Field) 7390 return true; 7391 7392 // If the initializer list for a union does not contain any elements, the 7393 // first element of the union is value-initialized. 7394 // FIXME: The element should be initialized from an initializer list. 7395 // Is this difference ever observable for initializer lists which 7396 // we don't build? 7397 ImplicitValueInitExpr VIE(Field->getType()); 7398 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 7399 7400 LValue Subobject = This; 7401 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 7402 return false; 7403 7404 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 7405 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 7406 isa<CXXDefaultInitExpr>(InitExpr)); 7407 7408 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 7409 } 7410 7411 if (!Result.hasValue()) 7412 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 7413 std::distance(RD->field_begin(), RD->field_end())); 7414 unsigned ElementNo = 0; 7415 bool Success = true; 7416 7417 // Initialize base classes. 7418 if (CXXRD && CXXRD->getNumBases()) { 7419 for (const auto &Base : CXXRD->bases()) { 7420 assert(ElementNo < E->getNumInits() && "missing init for base class"); 7421 const Expr *Init = E->getInit(ElementNo); 7422 7423 LValue Subobject = This; 7424 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 7425 return false; 7426 7427 APValue &FieldVal = Result.getStructBase(ElementNo); 7428 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 7429 if (!Info.noteFailure()) 7430 return false; 7431 Success = false; 7432 } 7433 ++ElementNo; 7434 } 7435 7436 EvalObj.finishedConstructingBases(); 7437 } 7438 7439 // Initialize members. 7440 for (const auto *Field : RD->fields()) { 7441 // Anonymous bit-fields are not considered members of the class for 7442 // purposes of aggregate initialization. 7443 if (Field->isUnnamedBitfield()) 7444 continue; 7445 7446 LValue Subobject = This; 7447 7448 bool HaveInit = ElementNo < E->getNumInits(); 7449 7450 // FIXME: Diagnostics here should point to the end of the initializer 7451 // list, not the start. 7452 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 7453 Subobject, Field, &Layout)) 7454 return false; 7455 7456 // Perform an implicit value-initialization for members beyond the end of 7457 // the initializer list. 7458 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 7459 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 7460 7461 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 7462 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 7463 isa<CXXDefaultInitExpr>(Init)); 7464 7465 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 7466 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 7467 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 7468 FieldVal, Field))) { 7469 if (!Info.noteFailure()) 7470 return false; 7471 Success = false; 7472 } 7473 } 7474 7475 return Success; 7476 } 7477 7478 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 7479 QualType T) { 7480 // Note that E's type is not necessarily the type of our class here; we might 7481 // be initializing an array element instead. 7482 const CXXConstructorDecl *FD = E->getConstructor(); 7483 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 7484 7485 bool ZeroInit = E->requiresZeroInitialization(); 7486 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 7487 // If we've already performed zero-initialization, we're already done. 7488 if (Result.hasValue()) 7489 return true; 7490 7491 // We can get here in two different ways: 7492 // 1) We're performing value-initialization, and should zero-initialize 7493 // the object, or 7494 // 2) We're performing default-initialization of an object with a trivial 7495 // constexpr default constructor, in which case we should start the 7496 // lifetimes of all the base subobjects (there can be no data member 7497 // subobjects in this case) per [basic.life]p1. 7498 // Either way, ZeroInitialization is appropriate. 7499 return ZeroInitialization(E, T); 7500 } 7501 7502 const FunctionDecl *Definition = nullptr; 7503 auto Body = FD->getBody(Definition); 7504 7505 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 7506 return false; 7507 7508 // Avoid materializing a temporary for an elidable copy/move constructor. 7509 if (E->isElidable() && !ZeroInit) 7510 if (const MaterializeTemporaryExpr *ME 7511 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 7512 return Visit(ME->GetTemporaryExpr()); 7513 7514 if (ZeroInit && !ZeroInitialization(E, T)) 7515 return false; 7516 7517 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 7518 return HandleConstructorCall(E, This, Args, 7519 cast<CXXConstructorDecl>(Definition), Info, 7520 Result); 7521 } 7522 7523 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 7524 const CXXInheritedCtorInitExpr *E) { 7525 if (!Info.CurrentCall) { 7526 assert(Info.checkingPotentialConstantExpression()); 7527 return false; 7528 } 7529 7530 const CXXConstructorDecl *FD = E->getConstructor(); 7531 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 7532 return false; 7533 7534 const FunctionDecl *Definition = nullptr; 7535 auto Body = FD->getBody(Definition); 7536 7537 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 7538 return false; 7539 7540 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 7541 cast<CXXConstructorDecl>(Definition), Info, 7542 Result); 7543 } 7544 7545 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 7546 const CXXStdInitializerListExpr *E) { 7547 const ConstantArrayType *ArrayType = 7548 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 7549 7550 LValue Array; 7551 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 7552 return false; 7553 7554 // Get a pointer to the first element of the array. 7555 Array.addArray(Info, E, ArrayType); 7556 7557 // FIXME: Perform the checks on the field types in SemaInit. 7558 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 7559 RecordDecl::field_iterator Field = Record->field_begin(); 7560 if (Field == Record->field_end()) 7561 return Error(E); 7562 7563 // Start pointer. 7564 if (!Field->getType()->isPointerType() || 7565 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 7566 ArrayType->getElementType())) 7567 return Error(E); 7568 7569 // FIXME: What if the initializer_list type has base classes, etc? 7570 Result = APValue(APValue::UninitStruct(), 0, 2); 7571 Array.moveInto(Result.getStructField(0)); 7572 7573 if (++Field == Record->field_end()) 7574 return Error(E); 7575 7576 if (Field->getType()->isPointerType() && 7577 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 7578 ArrayType->getElementType())) { 7579 // End pointer. 7580 if (!HandleLValueArrayAdjustment(Info, E, Array, 7581 ArrayType->getElementType(), 7582 ArrayType->getSize().getZExtValue())) 7583 return false; 7584 Array.moveInto(Result.getStructField(1)); 7585 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 7586 // Length. 7587 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 7588 else 7589 return Error(E); 7590 7591 if (++Field != Record->field_end()) 7592 return Error(E); 7593 7594 return true; 7595 } 7596 7597 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 7598 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 7599 if (ClosureClass->isInvalidDecl()) return false; 7600 7601 if (Info.checkingPotentialConstantExpression()) return true; 7602 7603 const size_t NumFields = 7604 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 7605 7606 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 7607 E->capture_init_end()) && 7608 "The number of lambda capture initializers should equal the number of " 7609 "fields within the closure type"); 7610 7611 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 7612 // Iterate through all the lambda's closure object's fields and initialize 7613 // them. 7614 auto *CaptureInitIt = E->capture_init_begin(); 7615 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 7616 bool Success = true; 7617 for (const auto *Field : ClosureClass->fields()) { 7618 assert(CaptureInitIt != E->capture_init_end()); 7619 // Get the initializer for this field 7620 Expr *const CurFieldInit = *CaptureInitIt++; 7621 7622 // If there is no initializer, either this is a VLA or an error has 7623 // occurred. 7624 if (!CurFieldInit) 7625 return Error(E); 7626 7627 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 7628 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 7629 if (!Info.keepEvaluatingAfterFailure()) 7630 return false; 7631 Success = false; 7632 } 7633 ++CaptureIt; 7634 } 7635 return Success; 7636 } 7637 7638 static bool EvaluateRecord(const Expr *E, const LValue &This, 7639 APValue &Result, EvalInfo &Info) { 7640 assert(E->isRValue() && E->getType()->isRecordType() && 7641 "can't evaluate expression as a record rvalue"); 7642 return RecordExprEvaluator(Info, This, Result).Visit(E); 7643 } 7644 7645 //===----------------------------------------------------------------------===// 7646 // Temporary Evaluation 7647 // 7648 // Temporaries are represented in the AST as rvalues, but generally behave like 7649 // lvalues. The full-object of which the temporary is a subobject is implicitly 7650 // materialized so that a reference can bind to it. 7651 //===----------------------------------------------------------------------===// 7652 namespace { 7653 class TemporaryExprEvaluator 7654 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 7655 public: 7656 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 7657 LValueExprEvaluatorBaseTy(Info, Result, false) {} 7658 7659 /// Visit an expression which constructs the value of this temporary. 7660 bool VisitConstructExpr(const Expr *E) { 7661 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall); 7662 return EvaluateInPlace(Value, Info, Result, E); 7663 } 7664 7665 bool VisitCastExpr(const CastExpr *E) { 7666 switch (E->getCastKind()) { 7667 default: 7668 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7669 7670 case CK_ConstructorConversion: 7671 return VisitConstructExpr(E->getSubExpr()); 7672 } 7673 } 7674 bool VisitInitListExpr(const InitListExpr *E) { 7675 return VisitConstructExpr(E); 7676 } 7677 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 7678 return VisitConstructExpr(E); 7679 } 7680 bool VisitCallExpr(const CallExpr *E) { 7681 return VisitConstructExpr(E); 7682 } 7683 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 7684 return VisitConstructExpr(E); 7685 } 7686 bool VisitLambdaExpr(const LambdaExpr *E) { 7687 return VisitConstructExpr(E); 7688 } 7689 }; 7690 } // end anonymous namespace 7691 7692 /// Evaluate an expression of record type as a temporary. 7693 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 7694 assert(E->isRValue() && E->getType()->isRecordType()); 7695 return TemporaryExprEvaluator(Info, Result).Visit(E); 7696 } 7697 7698 //===----------------------------------------------------------------------===// 7699 // Vector Evaluation 7700 //===----------------------------------------------------------------------===// 7701 7702 namespace { 7703 class VectorExprEvaluator 7704 : public ExprEvaluatorBase<VectorExprEvaluator> { 7705 APValue &Result; 7706 public: 7707 7708 VectorExprEvaluator(EvalInfo &info, APValue &Result) 7709 : ExprEvaluatorBaseTy(info), Result(Result) {} 7710 7711 bool Success(ArrayRef<APValue> V, const Expr *E) { 7712 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 7713 // FIXME: remove this APValue copy. 7714 Result = APValue(V.data(), V.size()); 7715 return true; 7716 } 7717 bool Success(const APValue &V, const Expr *E) { 7718 assert(V.isVector()); 7719 Result = V; 7720 return true; 7721 } 7722 bool ZeroInitialization(const Expr *E); 7723 7724 bool VisitUnaryReal(const UnaryOperator *E) 7725 { return Visit(E->getSubExpr()); } 7726 bool VisitCastExpr(const CastExpr* E); 7727 bool VisitInitListExpr(const InitListExpr *E); 7728 bool VisitUnaryImag(const UnaryOperator *E); 7729 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 7730 // binary comparisons, binary and/or/xor, 7731 // shufflevector, ExtVectorElementExpr 7732 }; 7733 } // end anonymous namespace 7734 7735 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 7736 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 7737 return VectorExprEvaluator(Info, Result).Visit(E); 7738 } 7739 7740 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 7741 const VectorType *VTy = E->getType()->castAs<VectorType>(); 7742 unsigned NElts = VTy->getNumElements(); 7743 7744 const Expr *SE = E->getSubExpr(); 7745 QualType SETy = SE->getType(); 7746 7747 switch (E->getCastKind()) { 7748 case CK_VectorSplat: { 7749 APValue Val = APValue(); 7750 if (SETy->isIntegerType()) { 7751 APSInt IntResult; 7752 if (!EvaluateInteger(SE, IntResult, Info)) 7753 return false; 7754 Val = APValue(std::move(IntResult)); 7755 } else if (SETy->isRealFloatingType()) { 7756 APFloat FloatResult(0.0); 7757 if (!EvaluateFloat(SE, FloatResult, Info)) 7758 return false; 7759 Val = APValue(std::move(FloatResult)); 7760 } else { 7761 return Error(E); 7762 } 7763 7764 // Splat and create vector APValue. 7765 SmallVector<APValue, 4> Elts(NElts, Val); 7766 return Success(Elts, E); 7767 } 7768 case CK_BitCast: { 7769 // Evaluate the operand into an APInt we can extract from. 7770 llvm::APInt SValInt; 7771 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 7772 return false; 7773 // Extract the elements 7774 QualType EltTy = VTy->getElementType(); 7775 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 7776 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 7777 SmallVector<APValue, 4> Elts; 7778 if (EltTy->isRealFloatingType()) { 7779 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 7780 unsigned FloatEltSize = EltSize; 7781 if (&Sem == &APFloat::x87DoubleExtended()) 7782 FloatEltSize = 80; 7783 for (unsigned i = 0; i < NElts; i++) { 7784 llvm::APInt Elt; 7785 if (BigEndian) 7786 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 7787 else 7788 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 7789 Elts.push_back(APValue(APFloat(Sem, Elt))); 7790 } 7791 } else if (EltTy->isIntegerType()) { 7792 for (unsigned i = 0; i < NElts; i++) { 7793 llvm::APInt Elt; 7794 if (BigEndian) 7795 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 7796 else 7797 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 7798 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 7799 } 7800 } else { 7801 return Error(E); 7802 } 7803 return Success(Elts, E); 7804 } 7805 default: 7806 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7807 } 7808 } 7809 7810 bool 7811 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7812 const VectorType *VT = E->getType()->castAs<VectorType>(); 7813 unsigned NumInits = E->getNumInits(); 7814 unsigned NumElements = VT->getNumElements(); 7815 7816 QualType EltTy = VT->getElementType(); 7817 SmallVector<APValue, 4> Elements; 7818 7819 // The number of initializers can be less than the number of 7820 // vector elements. For OpenCL, this can be due to nested vector 7821 // initialization. For GCC compatibility, missing trailing elements 7822 // should be initialized with zeroes. 7823 unsigned CountInits = 0, CountElts = 0; 7824 while (CountElts < NumElements) { 7825 // Handle nested vector initialization. 7826 if (CountInits < NumInits 7827 && E->getInit(CountInits)->getType()->isVectorType()) { 7828 APValue v; 7829 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 7830 return Error(E); 7831 unsigned vlen = v.getVectorLength(); 7832 for (unsigned j = 0; j < vlen; j++) 7833 Elements.push_back(v.getVectorElt(j)); 7834 CountElts += vlen; 7835 } else if (EltTy->isIntegerType()) { 7836 llvm::APSInt sInt(32); 7837 if (CountInits < NumInits) { 7838 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 7839 return false; 7840 } else // trailing integer zero. 7841 sInt = Info.Ctx.MakeIntValue(0, EltTy); 7842 Elements.push_back(APValue(sInt)); 7843 CountElts++; 7844 } else { 7845 llvm::APFloat f(0.0); 7846 if (CountInits < NumInits) { 7847 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 7848 return false; 7849 } else // trailing float zero. 7850 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 7851 Elements.push_back(APValue(f)); 7852 CountElts++; 7853 } 7854 CountInits++; 7855 } 7856 return Success(Elements, E); 7857 } 7858 7859 bool 7860 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 7861 const VectorType *VT = E->getType()->getAs<VectorType>(); 7862 QualType EltTy = VT->getElementType(); 7863 APValue ZeroElement; 7864 if (EltTy->isIntegerType()) 7865 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 7866 else 7867 ZeroElement = 7868 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 7869 7870 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 7871 return Success(Elements, E); 7872 } 7873 7874 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 7875 VisitIgnoredValue(E->getSubExpr()); 7876 return ZeroInitialization(E); 7877 } 7878 7879 //===----------------------------------------------------------------------===// 7880 // Array Evaluation 7881 //===----------------------------------------------------------------------===// 7882 7883 namespace { 7884 class ArrayExprEvaluator 7885 : public ExprEvaluatorBase<ArrayExprEvaluator> { 7886 const LValue &This; 7887 APValue &Result; 7888 public: 7889 7890 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 7891 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 7892 7893 bool Success(const APValue &V, const Expr *E) { 7894 assert(V.isArray() && "expected array"); 7895 Result = V; 7896 return true; 7897 } 7898 7899 bool ZeroInitialization(const Expr *E) { 7900 const ConstantArrayType *CAT = 7901 Info.Ctx.getAsConstantArrayType(E->getType()); 7902 if (!CAT) 7903 return Error(E); 7904 7905 Result = APValue(APValue::UninitArray(), 0, 7906 CAT->getSize().getZExtValue()); 7907 if (!Result.hasArrayFiller()) return true; 7908 7909 // Zero-initialize all elements. 7910 LValue Subobject = This; 7911 Subobject.addArray(Info, E, CAT); 7912 ImplicitValueInitExpr VIE(CAT->getElementType()); 7913 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 7914 } 7915 7916 bool VisitCallExpr(const CallExpr *E) { 7917 return handleCallExpr(E, Result, &This); 7918 } 7919 bool VisitInitListExpr(const InitListExpr *E); 7920 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 7921 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 7922 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 7923 const LValue &Subobject, 7924 APValue *Value, QualType Type); 7925 bool VisitStringLiteral(const StringLiteral *E) { 7926 expandStringLiteral(Info, E, Result); 7927 return true; 7928 } 7929 }; 7930 } // end anonymous namespace 7931 7932 static bool EvaluateArray(const Expr *E, const LValue &This, 7933 APValue &Result, EvalInfo &Info) { 7934 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 7935 return ArrayExprEvaluator(Info, This, Result).Visit(E); 7936 } 7937 7938 // Return true iff the given array filler may depend on the element index. 7939 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 7940 // For now, just whitelist non-class value-initialization and initialization 7941 // lists comprised of them. 7942 if (isa<ImplicitValueInitExpr>(FillerExpr)) 7943 return false; 7944 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 7945 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 7946 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 7947 return true; 7948 } 7949 return false; 7950 } 7951 return true; 7952 } 7953 7954 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 7955 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType()); 7956 if (!CAT) 7957 return Error(E); 7958 7959 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 7960 // an appropriately-typed string literal enclosed in braces. 7961 if (E->isStringLiteralInit()) 7962 return Visit(E->getInit(0)); 7963 7964 bool Success = true; 7965 7966 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 7967 "zero-initialized array shouldn't have any initialized elts"); 7968 APValue Filler; 7969 if (Result.isArray() && Result.hasArrayFiller()) 7970 Filler = Result.getArrayFiller(); 7971 7972 unsigned NumEltsToInit = E->getNumInits(); 7973 unsigned NumElts = CAT->getSize().getZExtValue(); 7974 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 7975 7976 // If the initializer might depend on the array index, run it for each 7977 // array element. 7978 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 7979 NumEltsToInit = NumElts; 7980 7981 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 7982 << NumEltsToInit << ".\n"); 7983 7984 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 7985 7986 // If the array was previously zero-initialized, preserve the 7987 // zero-initialized values. 7988 if (Filler.hasValue()) { 7989 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 7990 Result.getArrayInitializedElt(I) = Filler; 7991 if (Result.hasArrayFiller()) 7992 Result.getArrayFiller() = Filler; 7993 } 7994 7995 LValue Subobject = This; 7996 Subobject.addArray(Info, E, CAT); 7997 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 7998 const Expr *Init = 7999 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 8000 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 8001 Info, Subobject, Init) || 8002 !HandleLValueArrayAdjustment(Info, Init, Subobject, 8003 CAT->getElementType(), 1)) { 8004 if (!Info.noteFailure()) 8005 return false; 8006 Success = false; 8007 } 8008 } 8009 8010 if (!Result.hasArrayFiller()) 8011 return Success; 8012 8013 // If we get here, we have a trivial filler, which we can just evaluate 8014 // once and splat over the rest of the array elements. 8015 assert(FillerExpr && "no array filler for incomplete init list"); 8016 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 8017 FillerExpr) && Success; 8018 } 8019 8020 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 8021 if (E->getCommonExpr() && 8022 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false), 8023 Info, E->getCommonExpr()->getSourceExpr())) 8024 return false; 8025 8026 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 8027 8028 uint64_t Elements = CAT->getSize().getZExtValue(); 8029 Result = APValue(APValue::UninitArray(), Elements, Elements); 8030 8031 LValue Subobject = This; 8032 Subobject.addArray(Info, E, CAT); 8033 8034 bool Success = true; 8035 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 8036 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 8037 Info, Subobject, E->getSubExpr()) || 8038 !HandleLValueArrayAdjustment(Info, E, Subobject, 8039 CAT->getElementType(), 1)) { 8040 if (!Info.noteFailure()) 8041 return false; 8042 Success = false; 8043 } 8044 } 8045 8046 return Success; 8047 } 8048 8049 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 8050 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 8051 } 8052 8053 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 8054 const LValue &Subobject, 8055 APValue *Value, 8056 QualType Type) { 8057 bool HadZeroInit = Value->hasValue(); 8058 8059 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 8060 unsigned N = CAT->getSize().getZExtValue(); 8061 8062 // Preserve the array filler if we had prior zero-initialization. 8063 APValue Filler = 8064 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 8065 : APValue(); 8066 8067 *Value = APValue(APValue::UninitArray(), N, N); 8068 8069 if (HadZeroInit) 8070 for (unsigned I = 0; I != N; ++I) 8071 Value->getArrayInitializedElt(I) = Filler; 8072 8073 // Initialize the elements. 8074 LValue ArrayElt = Subobject; 8075 ArrayElt.addArray(Info, E, CAT); 8076 for (unsigned I = 0; I != N; ++I) 8077 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 8078 CAT->getElementType()) || 8079 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 8080 CAT->getElementType(), 1)) 8081 return false; 8082 8083 return true; 8084 } 8085 8086 if (!Type->isRecordType()) 8087 return Error(E); 8088 8089 return RecordExprEvaluator(Info, Subobject, *Value) 8090 .VisitCXXConstructExpr(E, Type); 8091 } 8092 8093 //===----------------------------------------------------------------------===// 8094 // Integer Evaluation 8095 // 8096 // As a GNU extension, we support casting pointers to sufficiently-wide integer 8097 // types and back in constant folding. Integer values are thus represented 8098 // either as an integer-valued APValue, or as an lvalue-valued APValue. 8099 //===----------------------------------------------------------------------===// 8100 8101 namespace { 8102 class IntExprEvaluator 8103 : public ExprEvaluatorBase<IntExprEvaluator> { 8104 APValue &Result; 8105 public: 8106 IntExprEvaluator(EvalInfo &info, APValue &result) 8107 : ExprEvaluatorBaseTy(info), Result(result) {} 8108 8109 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 8110 assert(E->getType()->isIntegralOrEnumerationType() && 8111 "Invalid evaluation result."); 8112 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 8113 "Invalid evaluation result."); 8114 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 8115 "Invalid evaluation result."); 8116 Result = APValue(SI); 8117 return true; 8118 } 8119 bool Success(const llvm::APSInt &SI, const Expr *E) { 8120 return Success(SI, E, Result); 8121 } 8122 8123 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 8124 assert(E->getType()->isIntegralOrEnumerationType() && 8125 "Invalid evaluation result."); 8126 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 8127 "Invalid evaluation result."); 8128 Result = APValue(APSInt(I)); 8129 Result.getInt().setIsUnsigned( 8130 E->getType()->isUnsignedIntegerOrEnumerationType()); 8131 return true; 8132 } 8133 bool Success(const llvm::APInt &I, const Expr *E) { 8134 return Success(I, E, Result); 8135 } 8136 8137 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 8138 assert(E->getType()->isIntegralOrEnumerationType() && 8139 "Invalid evaluation result."); 8140 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 8141 return true; 8142 } 8143 bool Success(uint64_t Value, const Expr *E) { 8144 return Success(Value, E, Result); 8145 } 8146 8147 bool Success(CharUnits Size, const Expr *E) { 8148 return Success(Size.getQuantity(), E); 8149 } 8150 8151 bool Success(const APValue &V, const Expr *E) { 8152 if (V.isLValue() || V.isAddrLabelDiff()) { 8153 Result = V; 8154 return true; 8155 } 8156 return Success(V.getInt(), E); 8157 } 8158 8159 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 8160 8161 //===--------------------------------------------------------------------===// 8162 // Visitor Methods 8163 //===--------------------------------------------------------------------===// 8164 8165 bool VisitConstantExpr(const ConstantExpr *E); 8166 8167 bool VisitIntegerLiteral(const IntegerLiteral *E) { 8168 return Success(E->getValue(), E); 8169 } 8170 bool VisitCharacterLiteral(const CharacterLiteral *E) { 8171 return Success(E->getValue(), E); 8172 } 8173 8174 bool CheckReferencedDecl(const Expr *E, const Decl *D); 8175 bool VisitDeclRefExpr(const DeclRefExpr *E) { 8176 if (CheckReferencedDecl(E, E->getDecl())) 8177 return true; 8178 8179 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 8180 } 8181 bool VisitMemberExpr(const MemberExpr *E) { 8182 if (CheckReferencedDecl(E, E->getMemberDecl())) { 8183 VisitIgnoredBaseExpression(E->getBase()); 8184 return true; 8185 } 8186 8187 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 8188 } 8189 8190 bool VisitCallExpr(const CallExpr *E); 8191 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 8192 bool VisitBinaryOperator(const BinaryOperator *E); 8193 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 8194 bool VisitUnaryOperator(const UnaryOperator *E); 8195 8196 bool VisitCastExpr(const CastExpr* E); 8197 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 8198 8199 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 8200 return Success(E->getValue(), E); 8201 } 8202 8203 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 8204 return Success(E->getValue(), E); 8205 } 8206 8207 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 8208 if (Info.ArrayInitIndex == uint64_t(-1)) { 8209 // We were asked to evaluate this subexpression independent of the 8210 // enclosing ArrayInitLoopExpr. We can't do that. 8211 Info.FFDiag(E); 8212 return false; 8213 } 8214 return Success(Info.ArrayInitIndex, E); 8215 } 8216 8217 // Note, GNU defines __null as an integer, not a pointer. 8218 bool VisitGNUNullExpr(const GNUNullExpr *E) { 8219 return ZeroInitialization(E); 8220 } 8221 8222 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 8223 return Success(E->getValue(), E); 8224 } 8225 8226 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 8227 return Success(E->getValue(), E); 8228 } 8229 8230 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 8231 return Success(E->getValue(), E); 8232 } 8233 8234 bool VisitUnaryReal(const UnaryOperator *E); 8235 bool VisitUnaryImag(const UnaryOperator *E); 8236 8237 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 8238 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 8239 bool VisitSourceLocExpr(const SourceLocExpr *E); 8240 // FIXME: Missing: array subscript of vector, member of vector 8241 }; 8242 8243 class FixedPointExprEvaluator 8244 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 8245 APValue &Result; 8246 8247 public: 8248 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 8249 : ExprEvaluatorBaseTy(info), Result(result) {} 8250 8251 bool Success(const llvm::APInt &I, const Expr *E) { 8252 return Success( 8253 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 8254 } 8255 8256 bool Success(uint64_t Value, const Expr *E) { 8257 return Success( 8258 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 8259 } 8260 8261 bool Success(const APValue &V, const Expr *E) { 8262 return Success(V.getFixedPoint(), E); 8263 } 8264 8265 bool Success(const APFixedPoint &V, const Expr *E) { 8266 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 8267 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 8268 "Invalid evaluation result."); 8269 Result = APValue(V); 8270 return true; 8271 } 8272 8273 //===--------------------------------------------------------------------===// 8274 // Visitor Methods 8275 //===--------------------------------------------------------------------===// 8276 8277 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 8278 return Success(E->getValue(), E); 8279 } 8280 8281 bool VisitCastExpr(const CastExpr *E); 8282 bool VisitUnaryOperator(const UnaryOperator *E); 8283 bool VisitBinaryOperator(const BinaryOperator *E); 8284 }; 8285 } // end anonymous namespace 8286 8287 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 8288 /// produce either the integer value or a pointer. 8289 /// 8290 /// GCC has a heinous extension which folds casts between pointer types and 8291 /// pointer-sized integral types. We support this by allowing the evaluation of 8292 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 8293 /// Some simple arithmetic on such values is supported (they are treated much 8294 /// like char*). 8295 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 8296 EvalInfo &Info) { 8297 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 8298 return IntExprEvaluator(Info, Result).Visit(E); 8299 } 8300 8301 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 8302 APValue Val; 8303 if (!EvaluateIntegerOrLValue(E, Val, Info)) 8304 return false; 8305 if (!Val.isInt()) { 8306 // FIXME: It would be better to produce the diagnostic for casting 8307 // a pointer to an integer. 8308 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 8309 return false; 8310 } 8311 Result = Val.getInt(); 8312 return true; 8313 } 8314 8315 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 8316 APValue Evaluated = E->EvaluateInContext( 8317 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 8318 return Success(Evaluated, E); 8319 } 8320 8321 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 8322 EvalInfo &Info) { 8323 if (E->getType()->isFixedPointType()) { 8324 APValue Val; 8325 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 8326 return false; 8327 if (!Val.isFixedPoint()) 8328 return false; 8329 8330 Result = Val.getFixedPoint(); 8331 return true; 8332 } 8333 return false; 8334 } 8335 8336 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 8337 EvalInfo &Info) { 8338 if (E->getType()->isIntegerType()) { 8339 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 8340 APSInt Val; 8341 if (!EvaluateInteger(E, Val, Info)) 8342 return false; 8343 Result = APFixedPoint(Val, FXSema); 8344 return true; 8345 } else if (E->getType()->isFixedPointType()) { 8346 return EvaluateFixedPoint(E, Result, Info); 8347 } 8348 return false; 8349 } 8350 8351 /// Check whether the given declaration can be directly converted to an integral 8352 /// rvalue. If not, no diagnostic is produced; there are other things we can 8353 /// try. 8354 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 8355 // Enums are integer constant exprs. 8356 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 8357 // Check for signedness/width mismatches between E type and ECD value. 8358 bool SameSign = (ECD->getInitVal().isSigned() 8359 == E->getType()->isSignedIntegerOrEnumerationType()); 8360 bool SameWidth = (ECD->getInitVal().getBitWidth() 8361 == Info.Ctx.getIntWidth(E->getType())); 8362 if (SameSign && SameWidth) 8363 return Success(ECD->getInitVal(), E); 8364 else { 8365 // Get rid of mismatch (otherwise Success assertions will fail) 8366 // by computing a new value matching the type of E. 8367 llvm::APSInt Val = ECD->getInitVal(); 8368 if (!SameSign) 8369 Val.setIsSigned(!ECD->getInitVal().isSigned()); 8370 if (!SameWidth) 8371 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 8372 return Success(Val, E); 8373 } 8374 } 8375 return false; 8376 } 8377 8378 /// Values returned by __builtin_classify_type, chosen to match the values 8379 /// produced by GCC's builtin. 8380 enum class GCCTypeClass { 8381 None = -1, 8382 Void = 0, 8383 Integer = 1, 8384 // GCC reserves 2 for character types, but instead classifies them as 8385 // integers. 8386 Enum = 3, 8387 Bool = 4, 8388 Pointer = 5, 8389 // GCC reserves 6 for references, but appears to never use it (because 8390 // expressions never have reference type, presumably). 8391 PointerToDataMember = 7, 8392 RealFloat = 8, 8393 Complex = 9, 8394 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 8395 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 8396 // GCC claims to reserve 11 for pointers to member functions, but *actually* 8397 // uses 12 for that purpose, same as for a class or struct. Maybe it 8398 // internally implements a pointer to member as a struct? Who knows. 8399 PointerToMemberFunction = 12, // Not a bug, see above. 8400 ClassOrStruct = 12, 8401 Union = 13, 8402 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 8403 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 8404 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 8405 // literals. 8406 }; 8407 8408 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 8409 /// as GCC. 8410 static GCCTypeClass 8411 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 8412 assert(!T->isDependentType() && "unexpected dependent type"); 8413 8414 QualType CanTy = T.getCanonicalType(); 8415 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 8416 8417 switch (CanTy->getTypeClass()) { 8418 #define TYPE(ID, BASE) 8419 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 8420 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 8421 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 8422 #include "clang/AST/TypeNodes.def" 8423 case Type::Auto: 8424 case Type::DeducedTemplateSpecialization: 8425 llvm_unreachable("unexpected non-canonical or dependent type"); 8426 8427 case Type::Builtin: 8428 switch (BT->getKind()) { 8429 #define BUILTIN_TYPE(ID, SINGLETON_ID) 8430 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 8431 case BuiltinType::ID: return GCCTypeClass::Integer; 8432 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 8433 case BuiltinType::ID: return GCCTypeClass::RealFloat; 8434 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 8435 case BuiltinType::ID: break; 8436 #include "clang/AST/BuiltinTypes.def" 8437 case BuiltinType::Void: 8438 return GCCTypeClass::Void; 8439 8440 case BuiltinType::Bool: 8441 return GCCTypeClass::Bool; 8442 8443 case BuiltinType::Char_U: 8444 case BuiltinType::UChar: 8445 case BuiltinType::WChar_U: 8446 case BuiltinType::Char8: 8447 case BuiltinType::Char16: 8448 case BuiltinType::Char32: 8449 case BuiltinType::UShort: 8450 case BuiltinType::UInt: 8451 case BuiltinType::ULong: 8452 case BuiltinType::ULongLong: 8453 case BuiltinType::UInt128: 8454 return GCCTypeClass::Integer; 8455 8456 case BuiltinType::UShortAccum: 8457 case BuiltinType::UAccum: 8458 case BuiltinType::ULongAccum: 8459 case BuiltinType::UShortFract: 8460 case BuiltinType::UFract: 8461 case BuiltinType::ULongFract: 8462 case BuiltinType::SatUShortAccum: 8463 case BuiltinType::SatUAccum: 8464 case BuiltinType::SatULongAccum: 8465 case BuiltinType::SatUShortFract: 8466 case BuiltinType::SatUFract: 8467 case BuiltinType::SatULongFract: 8468 return GCCTypeClass::None; 8469 8470 case BuiltinType::NullPtr: 8471 8472 case BuiltinType::ObjCId: 8473 case BuiltinType::ObjCClass: 8474 case BuiltinType::ObjCSel: 8475 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 8476 case BuiltinType::Id: 8477 #include "clang/Basic/OpenCLImageTypes.def" 8478 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 8479 case BuiltinType::Id: 8480 #include "clang/Basic/OpenCLExtensionTypes.def" 8481 case BuiltinType::OCLSampler: 8482 case BuiltinType::OCLEvent: 8483 case BuiltinType::OCLClkEvent: 8484 case BuiltinType::OCLQueue: 8485 case BuiltinType::OCLReserveID: 8486 return GCCTypeClass::None; 8487 8488 case BuiltinType::Dependent: 8489 llvm_unreachable("unexpected dependent type"); 8490 }; 8491 llvm_unreachable("unexpected placeholder type"); 8492 8493 case Type::Enum: 8494 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 8495 8496 case Type::Pointer: 8497 case Type::ConstantArray: 8498 case Type::VariableArray: 8499 case Type::IncompleteArray: 8500 case Type::FunctionNoProto: 8501 case Type::FunctionProto: 8502 return GCCTypeClass::Pointer; 8503 8504 case Type::MemberPointer: 8505 return CanTy->isMemberDataPointerType() 8506 ? GCCTypeClass::PointerToDataMember 8507 : GCCTypeClass::PointerToMemberFunction; 8508 8509 case Type::Complex: 8510 return GCCTypeClass::Complex; 8511 8512 case Type::Record: 8513 return CanTy->isUnionType() ? GCCTypeClass::Union 8514 : GCCTypeClass::ClassOrStruct; 8515 8516 case Type::Atomic: 8517 // GCC classifies _Atomic T the same as T. 8518 return EvaluateBuiltinClassifyType( 8519 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 8520 8521 case Type::BlockPointer: 8522 case Type::Vector: 8523 case Type::ExtVector: 8524 case Type::ObjCObject: 8525 case Type::ObjCInterface: 8526 case Type::ObjCObjectPointer: 8527 case Type::Pipe: 8528 // GCC classifies vectors as None. We follow its lead and classify all 8529 // other types that don't fit into the regular classification the same way. 8530 return GCCTypeClass::None; 8531 8532 case Type::LValueReference: 8533 case Type::RValueReference: 8534 llvm_unreachable("invalid type for expression"); 8535 } 8536 8537 llvm_unreachable("unexpected type class"); 8538 } 8539 8540 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 8541 /// as GCC. 8542 static GCCTypeClass 8543 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 8544 // If no argument was supplied, default to None. This isn't 8545 // ideal, however it is what gcc does. 8546 if (E->getNumArgs() == 0) 8547 return GCCTypeClass::None; 8548 8549 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 8550 // being an ICE, but still folds it to a constant using the type of the first 8551 // argument. 8552 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 8553 } 8554 8555 /// EvaluateBuiltinConstantPForLValue - Determine the result of 8556 /// __builtin_constant_p when applied to the given pointer. 8557 /// 8558 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 8559 /// or it points to the first character of a string literal. 8560 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 8561 APValue::LValueBase Base = LV.getLValueBase(); 8562 if (Base.isNull()) { 8563 // A null base is acceptable. 8564 return true; 8565 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 8566 if (!isa<StringLiteral>(E)) 8567 return false; 8568 return LV.getLValueOffset().isZero(); 8569 } else if (Base.is<TypeInfoLValue>()) { 8570 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 8571 // evaluate to true. 8572 return true; 8573 } else { 8574 // Any other base is not constant enough for GCC. 8575 return false; 8576 } 8577 } 8578 8579 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 8580 /// GCC as we can manage. 8581 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 8582 // This evaluation is not permitted to have side-effects, so evaluate it in 8583 // a speculative evaluation context. 8584 SpeculativeEvaluationRAII SpeculativeEval(Info); 8585 8586 // Constant-folding is always enabled for the operand of __builtin_constant_p 8587 // (even when the enclosing evaluation context otherwise requires a strict 8588 // language-specific constant expression). 8589 FoldConstant Fold(Info, true); 8590 8591 QualType ArgType = Arg->getType(); 8592 8593 // __builtin_constant_p always has one operand. The rules which gcc follows 8594 // are not precisely documented, but are as follows: 8595 // 8596 // - If the operand is of integral, floating, complex or enumeration type, 8597 // and can be folded to a known value of that type, it returns 1. 8598 // - If the operand can be folded to a pointer to the first character 8599 // of a string literal (or such a pointer cast to an integral type) 8600 // or to a null pointer or an integer cast to a pointer, it returns 1. 8601 // 8602 // Otherwise, it returns 0. 8603 // 8604 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 8605 // its support for this did not work prior to GCC 9 and is not yet well 8606 // understood. 8607 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 8608 ArgType->isAnyComplexType() || ArgType->isPointerType() || 8609 ArgType->isNullPtrType()) { 8610 APValue V; 8611 if (!::EvaluateAsRValue(Info, Arg, V)) { 8612 Fold.keepDiagnostics(); 8613 return false; 8614 } 8615 8616 // For a pointer (possibly cast to integer), there are special rules. 8617 if (V.getKind() == APValue::LValue) 8618 return EvaluateBuiltinConstantPForLValue(V); 8619 8620 // Otherwise, any constant value is good enough. 8621 return V.hasValue(); 8622 } 8623 8624 // Anything else isn't considered to be sufficiently constant. 8625 return false; 8626 } 8627 8628 /// Retrieves the "underlying object type" of the given expression, 8629 /// as used by __builtin_object_size. 8630 static QualType getObjectType(APValue::LValueBase B) { 8631 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 8632 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 8633 return VD->getType(); 8634 } else if (const Expr *E = B.get<const Expr*>()) { 8635 if (isa<CompoundLiteralExpr>(E)) 8636 return E->getType(); 8637 } else if (B.is<TypeInfoLValue>()) { 8638 return B.getTypeInfoType(); 8639 } 8640 8641 return QualType(); 8642 } 8643 8644 /// A more selective version of E->IgnoreParenCasts for 8645 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 8646 /// to change the type of E. 8647 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 8648 /// 8649 /// Always returns an RValue with a pointer representation. 8650 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 8651 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 8652 8653 auto *NoParens = E->IgnoreParens(); 8654 auto *Cast = dyn_cast<CastExpr>(NoParens); 8655 if (Cast == nullptr) 8656 return NoParens; 8657 8658 // We only conservatively allow a few kinds of casts, because this code is 8659 // inherently a simple solution that seeks to support the common case. 8660 auto CastKind = Cast->getCastKind(); 8661 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 8662 CastKind != CK_AddressSpaceConversion) 8663 return NoParens; 8664 8665 auto *SubExpr = Cast->getSubExpr(); 8666 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 8667 return NoParens; 8668 return ignorePointerCastsAndParens(SubExpr); 8669 } 8670 8671 /// Checks to see if the given LValue's Designator is at the end of the LValue's 8672 /// record layout. e.g. 8673 /// struct { struct { int a, b; } fst, snd; } obj; 8674 /// obj.fst // no 8675 /// obj.snd // yes 8676 /// obj.fst.a // no 8677 /// obj.fst.b // no 8678 /// obj.snd.a // no 8679 /// obj.snd.b // yes 8680 /// 8681 /// Please note: this function is specialized for how __builtin_object_size 8682 /// views "objects". 8683 /// 8684 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 8685 /// correct result, it will always return true. 8686 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 8687 assert(!LVal.Designator.Invalid); 8688 8689 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 8690 const RecordDecl *Parent = FD->getParent(); 8691 Invalid = Parent->isInvalidDecl(); 8692 if (Invalid || Parent->isUnion()) 8693 return true; 8694 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 8695 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 8696 }; 8697 8698 auto &Base = LVal.getLValueBase(); 8699 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 8700 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 8701 bool Invalid; 8702 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 8703 return Invalid; 8704 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 8705 for (auto *FD : IFD->chain()) { 8706 bool Invalid; 8707 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 8708 return Invalid; 8709 } 8710 } 8711 } 8712 8713 unsigned I = 0; 8714 QualType BaseType = getType(Base); 8715 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 8716 // If we don't know the array bound, conservatively assume we're looking at 8717 // the final array element. 8718 ++I; 8719 if (BaseType->isIncompleteArrayType()) 8720 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 8721 else 8722 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 8723 } 8724 8725 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 8726 const auto &Entry = LVal.Designator.Entries[I]; 8727 if (BaseType->isArrayType()) { 8728 // Because __builtin_object_size treats arrays as objects, we can ignore 8729 // the index iff this is the last array in the Designator. 8730 if (I + 1 == E) 8731 return true; 8732 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 8733 uint64_t Index = Entry.getAsArrayIndex(); 8734 if (Index + 1 != CAT->getSize()) 8735 return false; 8736 BaseType = CAT->getElementType(); 8737 } else if (BaseType->isAnyComplexType()) { 8738 const auto *CT = BaseType->castAs<ComplexType>(); 8739 uint64_t Index = Entry.getAsArrayIndex(); 8740 if (Index != 1) 8741 return false; 8742 BaseType = CT->getElementType(); 8743 } else if (auto *FD = getAsField(Entry)) { 8744 bool Invalid; 8745 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 8746 return Invalid; 8747 BaseType = FD->getType(); 8748 } else { 8749 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 8750 return false; 8751 } 8752 } 8753 return true; 8754 } 8755 8756 /// Tests to see if the LValue has a user-specified designator (that isn't 8757 /// necessarily valid). Note that this always returns 'true' if the LValue has 8758 /// an unsized array as its first designator entry, because there's currently no 8759 /// way to tell if the user typed *foo or foo[0]. 8760 static bool refersToCompleteObject(const LValue &LVal) { 8761 if (LVal.Designator.Invalid) 8762 return false; 8763 8764 if (!LVal.Designator.Entries.empty()) 8765 return LVal.Designator.isMostDerivedAnUnsizedArray(); 8766 8767 if (!LVal.InvalidBase) 8768 return true; 8769 8770 // If `E` is a MemberExpr, then the first part of the designator is hiding in 8771 // the LValueBase. 8772 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 8773 return !E || !isa<MemberExpr>(E); 8774 } 8775 8776 /// Attempts to detect a user writing into a piece of memory that's impossible 8777 /// to figure out the size of by just using types. 8778 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 8779 const SubobjectDesignator &Designator = LVal.Designator; 8780 // Notes: 8781 // - Users can only write off of the end when we have an invalid base. Invalid 8782 // bases imply we don't know where the memory came from. 8783 // - We used to be a bit more aggressive here; we'd only be conservative if 8784 // the array at the end was flexible, or if it had 0 or 1 elements. This 8785 // broke some common standard library extensions (PR30346), but was 8786 // otherwise seemingly fine. It may be useful to reintroduce this behavior 8787 // with some sort of whitelist. OTOH, it seems that GCC is always 8788 // conservative with the last element in structs (if it's an array), so our 8789 // current behavior is more compatible than a whitelisting approach would 8790 // be. 8791 return LVal.InvalidBase && 8792 Designator.Entries.size() == Designator.MostDerivedPathLength && 8793 Designator.MostDerivedIsArrayElement && 8794 isDesignatorAtObjectEnd(Ctx, LVal); 8795 } 8796 8797 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 8798 /// Fails if the conversion would cause loss of precision. 8799 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 8800 CharUnits &Result) { 8801 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 8802 if (Int.ugt(CharUnitsMax)) 8803 return false; 8804 Result = CharUnits::fromQuantity(Int.getZExtValue()); 8805 return true; 8806 } 8807 8808 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 8809 /// determine how many bytes exist from the beginning of the object to either 8810 /// the end of the current subobject, or the end of the object itself, depending 8811 /// on what the LValue looks like + the value of Type. 8812 /// 8813 /// If this returns false, the value of Result is undefined. 8814 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 8815 unsigned Type, const LValue &LVal, 8816 CharUnits &EndOffset) { 8817 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 8818 8819 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 8820 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 8821 return false; 8822 return HandleSizeof(Info, ExprLoc, Ty, Result); 8823 }; 8824 8825 // We want to evaluate the size of the entire object. This is a valid fallback 8826 // for when Type=1 and the designator is invalid, because we're asked for an 8827 // upper-bound. 8828 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 8829 // Type=3 wants a lower bound, so we can't fall back to this. 8830 if (Type == 3 && !DetermineForCompleteObject) 8831 return false; 8832 8833 llvm::APInt APEndOffset; 8834 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8835 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 8836 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 8837 8838 if (LVal.InvalidBase) 8839 return false; 8840 8841 QualType BaseTy = getObjectType(LVal.getLValueBase()); 8842 return CheckedHandleSizeof(BaseTy, EndOffset); 8843 } 8844 8845 // We want to evaluate the size of a subobject. 8846 const SubobjectDesignator &Designator = LVal.Designator; 8847 8848 // The following is a moderately common idiom in C: 8849 // 8850 // struct Foo { int a; char c[1]; }; 8851 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 8852 // strcpy(&F->c[0], Bar); 8853 // 8854 // In order to not break too much legacy code, we need to support it. 8855 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 8856 // If we can resolve this to an alloc_size call, we can hand that back, 8857 // because we know for certain how many bytes there are to write to. 8858 llvm::APInt APEndOffset; 8859 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 8860 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 8861 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 8862 8863 // If we cannot determine the size of the initial allocation, then we can't 8864 // given an accurate upper-bound. However, we are still able to give 8865 // conservative lower-bounds for Type=3. 8866 if (Type == 1) 8867 return false; 8868 } 8869 8870 CharUnits BytesPerElem; 8871 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 8872 return false; 8873 8874 // According to the GCC documentation, we want the size of the subobject 8875 // denoted by the pointer. But that's not quite right -- what we actually 8876 // want is the size of the immediately-enclosing array, if there is one. 8877 int64_t ElemsRemaining; 8878 if (Designator.MostDerivedIsArrayElement && 8879 Designator.Entries.size() == Designator.MostDerivedPathLength) { 8880 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 8881 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 8882 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 8883 } else { 8884 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 8885 } 8886 8887 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 8888 return true; 8889 } 8890 8891 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 8892 /// returns true and stores the result in @p Size. 8893 /// 8894 /// If @p WasError is non-null, this will report whether the failure to evaluate 8895 /// is to be treated as an Error in IntExprEvaluator. 8896 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 8897 EvalInfo &Info, uint64_t &Size) { 8898 // Determine the denoted object. 8899 LValue LVal; 8900 { 8901 // The operand of __builtin_object_size is never evaluated for side-effects. 8902 // If there are any, but we can determine the pointed-to object anyway, then 8903 // ignore the side-effects. 8904 SpeculativeEvaluationRAII SpeculativeEval(Info); 8905 IgnoreSideEffectsRAII Fold(Info); 8906 8907 if (E->isGLValue()) { 8908 // It's possible for us to be given GLValues if we're called via 8909 // Expr::tryEvaluateObjectSize. 8910 APValue RVal; 8911 if (!EvaluateAsRValue(Info, E, RVal)) 8912 return false; 8913 LVal.setFrom(Info.Ctx, RVal); 8914 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 8915 /*InvalidBaseOK=*/true)) 8916 return false; 8917 } 8918 8919 // If we point to before the start of the object, there are no accessible 8920 // bytes. 8921 if (LVal.getLValueOffset().isNegative()) { 8922 Size = 0; 8923 return true; 8924 } 8925 8926 CharUnits EndOffset; 8927 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 8928 return false; 8929 8930 // If we've fallen outside of the end offset, just pretend there's nothing to 8931 // write to/read from. 8932 if (EndOffset <= LVal.getLValueOffset()) 8933 Size = 0; 8934 else 8935 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 8936 return true; 8937 } 8938 8939 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) { 8940 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true); 8941 return ExprEvaluatorBaseTy::VisitConstantExpr(E); 8942 } 8943 8944 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 8945 if (unsigned BuiltinOp = E->getBuiltinCallee()) 8946 return VisitBuiltinCallExpr(E, BuiltinOp); 8947 8948 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8949 } 8950 8951 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 8952 unsigned BuiltinOp) { 8953 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 8954 default: 8955 return ExprEvaluatorBaseTy::VisitCallExpr(E); 8956 8957 case Builtin::BI__builtin_dynamic_object_size: 8958 case Builtin::BI__builtin_object_size: { 8959 // The type was checked when we built the expression. 8960 unsigned Type = 8961 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 8962 assert(Type <= 3 && "unexpected type"); 8963 8964 uint64_t Size; 8965 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 8966 return Success(Size, E); 8967 8968 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 8969 return Success((Type & 2) ? 0 : -1, E); 8970 8971 // Expression had no side effects, but we couldn't statically determine the 8972 // size of the referenced object. 8973 switch (Info.EvalMode) { 8974 case EvalInfo::EM_ConstantExpression: 8975 case EvalInfo::EM_PotentialConstantExpression: 8976 case EvalInfo::EM_ConstantFold: 8977 case EvalInfo::EM_EvaluateForOverflow: 8978 case EvalInfo::EM_IgnoreSideEffects: 8979 // Leave it to IR generation. 8980 return Error(E); 8981 case EvalInfo::EM_ConstantExpressionUnevaluated: 8982 case EvalInfo::EM_PotentialConstantExpressionUnevaluated: 8983 // Reduce it to a constant now. 8984 return Success((Type & 2) ? 0 : -1, E); 8985 } 8986 8987 llvm_unreachable("unexpected EvalMode"); 8988 } 8989 8990 case Builtin::BI__builtin_os_log_format_buffer_size: { 8991 analyze_os_log::OSLogBufferLayout Layout; 8992 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 8993 return Success(Layout.size().getQuantity(), E); 8994 } 8995 8996 case Builtin::BI__builtin_bswap16: 8997 case Builtin::BI__builtin_bswap32: 8998 case Builtin::BI__builtin_bswap64: { 8999 APSInt Val; 9000 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9001 return false; 9002 9003 return Success(Val.byteSwap(), E); 9004 } 9005 9006 case Builtin::BI__builtin_classify_type: 9007 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 9008 9009 case Builtin::BI__builtin_clrsb: 9010 case Builtin::BI__builtin_clrsbl: 9011 case Builtin::BI__builtin_clrsbll: { 9012 APSInt Val; 9013 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9014 return false; 9015 9016 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 9017 } 9018 9019 case Builtin::BI__builtin_clz: 9020 case Builtin::BI__builtin_clzl: 9021 case Builtin::BI__builtin_clzll: 9022 case Builtin::BI__builtin_clzs: { 9023 APSInt Val; 9024 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9025 return false; 9026 if (!Val) 9027 return Error(E); 9028 9029 return Success(Val.countLeadingZeros(), E); 9030 } 9031 9032 case Builtin::BI__builtin_constant_p: { 9033 const Expr *Arg = E->getArg(0); 9034 if (EvaluateBuiltinConstantP(Info, Arg)) 9035 return Success(true, E); 9036 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 9037 // Outside a constant context, eagerly evaluate to false in the presence 9038 // of side-effects in order to avoid -Wunsequenced false-positives in 9039 // a branch on __builtin_constant_p(expr). 9040 return Success(false, E); 9041 } 9042 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 9043 return false; 9044 } 9045 9046 case Builtin::BI__builtin_is_constant_evaluated: 9047 return Success(Info.InConstantContext, E); 9048 9049 case Builtin::BI__builtin_ctz: 9050 case Builtin::BI__builtin_ctzl: 9051 case Builtin::BI__builtin_ctzll: 9052 case Builtin::BI__builtin_ctzs: { 9053 APSInt Val; 9054 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9055 return false; 9056 if (!Val) 9057 return Error(E); 9058 9059 return Success(Val.countTrailingZeros(), E); 9060 } 9061 9062 case Builtin::BI__builtin_eh_return_data_regno: { 9063 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 9064 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 9065 return Success(Operand, E); 9066 } 9067 9068 case Builtin::BI__builtin_expect: 9069 return Visit(E->getArg(0)); 9070 9071 case Builtin::BI__builtin_ffs: 9072 case Builtin::BI__builtin_ffsl: 9073 case Builtin::BI__builtin_ffsll: { 9074 APSInt Val; 9075 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9076 return false; 9077 9078 unsigned N = Val.countTrailingZeros(); 9079 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 9080 } 9081 9082 case Builtin::BI__builtin_fpclassify: { 9083 APFloat Val(0.0); 9084 if (!EvaluateFloat(E->getArg(5), Val, Info)) 9085 return false; 9086 unsigned Arg; 9087 switch (Val.getCategory()) { 9088 case APFloat::fcNaN: Arg = 0; break; 9089 case APFloat::fcInfinity: Arg = 1; break; 9090 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 9091 case APFloat::fcZero: Arg = 4; break; 9092 } 9093 return Visit(E->getArg(Arg)); 9094 } 9095 9096 case Builtin::BI__builtin_isinf_sign: { 9097 APFloat Val(0.0); 9098 return EvaluateFloat(E->getArg(0), Val, Info) && 9099 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 9100 } 9101 9102 case Builtin::BI__builtin_isinf: { 9103 APFloat Val(0.0); 9104 return EvaluateFloat(E->getArg(0), Val, Info) && 9105 Success(Val.isInfinity() ? 1 : 0, E); 9106 } 9107 9108 case Builtin::BI__builtin_isfinite: { 9109 APFloat Val(0.0); 9110 return EvaluateFloat(E->getArg(0), Val, Info) && 9111 Success(Val.isFinite() ? 1 : 0, E); 9112 } 9113 9114 case Builtin::BI__builtin_isnan: { 9115 APFloat Val(0.0); 9116 return EvaluateFloat(E->getArg(0), Val, Info) && 9117 Success(Val.isNaN() ? 1 : 0, E); 9118 } 9119 9120 case Builtin::BI__builtin_isnormal: { 9121 APFloat Val(0.0); 9122 return EvaluateFloat(E->getArg(0), Val, Info) && 9123 Success(Val.isNormal() ? 1 : 0, E); 9124 } 9125 9126 case Builtin::BI__builtin_parity: 9127 case Builtin::BI__builtin_parityl: 9128 case Builtin::BI__builtin_parityll: { 9129 APSInt Val; 9130 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9131 return false; 9132 9133 return Success(Val.countPopulation() % 2, E); 9134 } 9135 9136 case Builtin::BI__builtin_popcount: 9137 case Builtin::BI__builtin_popcountl: 9138 case Builtin::BI__builtin_popcountll: { 9139 APSInt Val; 9140 if (!EvaluateInteger(E->getArg(0), Val, Info)) 9141 return false; 9142 9143 return Success(Val.countPopulation(), E); 9144 } 9145 9146 case Builtin::BIstrlen: 9147 case Builtin::BIwcslen: 9148 // A call to strlen is not a constant expression. 9149 if (Info.getLangOpts().CPlusPlus11) 9150 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9151 << /*isConstexpr*/0 << /*isConstructor*/0 9152 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9153 else 9154 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9155 LLVM_FALLTHROUGH; 9156 case Builtin::BI__builtin_strlen: 9157 case Builtin::BI__builtin_wcslen: { 9158 // As an extension, we support __builtin_strlen() as a constant expression, 9159 // and support folding strlen() to a constant. 9160 LValue String; 9161 if (!EvaluatePointer(E->getArg(0), String, Info)) 9162 return false; 9163 9164 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 9165 9166 // Fast path: if it's a string literal, search the string value. 9167 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 9168 String.getLValueBase().dyn_cast<const Expr *>())) { 9169 // The string literal may have embedded null characters. Find the first 9170 // one and truncate there. 9171 StringRef Str = S->getBytes(); 9172 int64_t Off = String.Offset.getQuantity(); 9173 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 9174 S->getCharByteWidth() == 1 && 9175 // FIXME: Add fast-path for wchar_t too. 9176 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 9177 Str = Str.substr(Off); 9178 9179 StringRef::size_type Pos = Str.find(0); 9180 if (Pos != StringRef::npos) 9181 Str = Str.substr(0, Pos); 9182 9183 return Success(Str.size(), E); 9184 } 9185 9186 // Fall through to slow path to issue appropriate diagnostic. 9187 } 9188 9189 // Slow path: scan the bytes of the string looking for the terminating 0. 9190 for (uint64_t Strlen = 0; /**/; ++Strlen) { 9191 APValue Char; 9192 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 9193 !Char.isInt()) 9194 return false; 9195 if (!Char.getInt()) 9196 return Success(Strlen, E); 9197 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 9198 return false; 9199 } 9200 } 9201 9202 case Builtin::BIstrcmp: 9203 case Builtin::BIwcscmp: 9204 case Builtin::BIstrncmp: 9205 case Builtin::BIwcsncmp: 9206 case Builtin::BImemcmp: 9207 case Builtin::BIbcmp: 9208 case Builtin::BIwmemcmp: 9209 // A call to strlen is not a constant expression. 9210 if (Info.getLangOpts().CPlusPlus11) 9211 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 9212 << /*isConstexpr*/0 << /*isConstructor*/0 9213 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 9214 else 9215 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 9216 LLVM_FALLTHROUGH; 9217 case Builtin::BI__builtin_strcmp: 9218 case Builtin::BI__builtin_wcscmp: 9219 case Builtin::BI__builtin_strncmp: 9220 case Builtin::BI__builtin_wcsncmp: 9221 case Builtin::BI__builtin_memcmp: 9222 case Builtin::BI__builtin_bcmp: 9223 case Builtin::BI__builtin_wmemcmp: { 9224 LValue String1, String2; 9225 if (!EvaluatePointer(E->getArg(0), String1, Info) || 9226 !EvaluatePointer(E->getArg(1), String2, Info)) 9227 return false; 9228 9229 uint64_t MaxLength = uint64_t(-1); 9230 if (BuiltinOp != Builtin::BIstrcmp && 9231 BuiltinOp != Builtin::BIwcscmp && 9232 BuiltinOp != Builtin::BI__builtin_strcmp && 9233 BuiltinOp != Builtin::BI__builtin_wcscmp) { 9234 APSInt N; 9235 if (!EvaluateInteger(E->getArg(2), N, Info)) 9236 return false; 9237 MaxLength = N.getExtValue(); 9238 } 9239 9240 // Empty substrings compare equal by definition. 9241 if (MaxLength == 0u) 9242 return Success(0, E); 9243 9244 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9245 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 9246 String1.Designator.Invalid || String2.Designator.Invalid) 9247 return false; 9248 9249 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 9250 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 9251 9252 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 9253 BuiltinOp == Builtin::BIbcmp || 9254 BuiltinOp == Builtin::BI__builtin_memcmp || 9255 BuiltinOp == Builtin::BI__builtin_bcmp; 9256 9257 assert(IsRawByte || 9258 (Info.Ctx.hasSameUnqualifiedType( 9259 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 9260 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 9261 9262 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 9263 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 9264 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 9265 Char1.isInt() && Char2.isInt(); 9266 }; 9267 const auto &AdvanceElems = [&] { 9268 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 9269 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 9270 }; 9271 9272 if (IsRawByte) { 9273 uint64_t BytesRemaining = MaxLength; 9274 // Pointers to const void may point to objects of incomplete type. 9275 if (CharTy1->isIncompleteType()) { 9276 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1; 9277 return false; 9278 } 9279 if (CharTy2->isIncompleteType()) { 9280 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2; 9281 return false; 9282 } 9283 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)}; 9284 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width); 9285 // Give up on comparing between elements with disparate widths. 9286 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2)) 9287 return false; 9288 uint64_t BytesPerElement = CharTy1Size.getQuantity(); 9289 assert(BytesRemaining && "BytesRemaining should not be zero: the " 9290 "following loop considers at least one element"); 9291 while (true) { 9292 APValue Char1, Char2; 9293 if (!ReadCurElems(Char1, Char2)) 9294 return false; 9295 // We have compatible in-memory widths, but a possible type and 9296 // (for `bool`) internal representation mismatch. 9297 // Assuming two's complement representation, including 0 for `false` and 9298 // 1 for `true`, we can check an appropriate number of elements for 9299 // equality even if they are not byte-sized. 9300 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width); 9301 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width); 9302 if (Char1InMem.ne(Char2InMem)) { 9303 // If the elements are byte-sized, then we can produce a three-way 9304 // comparison result in a straightforward manner. 9305 if (BytesPerElement == 1u) { 9306 // memcmp always compares unsigned chars. 9307 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E); 9308 } 9309 // The result is byte-order sensitive, and we have multibyte elements. 9310 // FIXME: We can compare the remaining bytes in the correct order. 9311 return false; 9312 } 9313 if (!AdvanceElems()) 9314 return false; 9315 if (BytesRemaining <= BytesPerElement) 9316 break; 9317 BytesRemaining -= BytesPerElement; 9318 } 9319 // Enough elements are equal to account for the memcmp limit. 9320 return Success(0, E); 9321 } 9322 9323 bool StopAtNull = 9324 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 9325 BuiltinOp != Builtin::BIwmemcmp && 9326 BuiltinOp != Builtin::BI__builtin_memcmp && 9327 BuiltinOp != Builtin::BI__builtin_bcmp && 9328 BuiltinOp != Builtin::BI__builtin_wmemcmp); 9329 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 9330 BuiltinOp == Builtin::BIwcsncmp || 9331 BuiltinOp == Builtin::BIwmemcmp || 9332 BuiltinOp == Builtin::BI__builtin_wcscmp || 9333 BuiltinOp == Builtin::BI__builtin_wcsncmp || 9334 BuiltinOp == Builtin::BI__builtin_wmemcmp; 9335 9336 for (; MaxLength; --MaxLength) { 9337 APValue Char1, Char2; 9338 if (!ReadCurElems(Char1, Char2)) 9339 return false; 9340 if (Char1.getInt() != Char2.getInt()) { 9341 if (IsWide) // wmemcmp compares with wchar_t signedness. 9342 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 9343 // memcmp always compares unsigned chars. 9344 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 9345 } 9346 if (StopAtNull && !Char1.getInt()) 9347 return Success(0, E); 9348 assert(!(StopAtNull && !Char2.getInt())); 9349 if (!AdvanceElems()) 9350 return false; 9351 } 9352 // We hit the strncmp / memcmp limit. 9353 return Success(0, E); 9354 } 9355 9356 case Builtin::BI__atomic_always_lock_free: 9357 case Builtin::BI__atomic_is_lock_free: 9358 case Builtin::BI__c11_atomic_is_lock_free: { 9359 APSInt SizeVal; 9360 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 9361 return false; 9362 9363 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 9364 // of two less than the maximum inline atomic width, we know it is 9365 // lock-free. If the size isn't a power of two, or greater than the 9366 // maximum alignment where we promote atomics, we know it is not lock-free 9367 // (at least not in the sense of atomic_is_lock_free). Otherwise, 9368 // the answer can only be determined at runtime; for example, 16-byte 9369 // atomics have lock-free implementations on some, but not all, 9370 // x86-64 processors. 9371 9372 // Check power-of-two. 9373 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 9374 if (Size.isPowerOfTwo()) { 9375 // Check against inlining width. 9376 unsigned InlineWidthBits = 9377 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 9378 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 9379 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 9380 Size == CharUnits::One() || 9381 E->getArg(1)->isNullPointerConstant(Info.Ctx, 9382 Expr::NPC_NeverValueDependent)) 9383 // OK, we will inline appropriately-aligned operations of this size, 9384 // and _Atomic(T) is appropriately-aligned. 9385 return Success(1, E); 9386 9387 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 9388 castAs<PointerType>()->getPointeeType(); 9389 if (!PointeeType->isIncompleteType() && 9390 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 9391 // OK, we will inline operations on this object. 9392 return Success(1, E); 9393 } 9394 } 9395 } 9396 9397 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 9398 Success(0, E) : Error(E); 9399 } 9400 case Builtin::BIomp_is_initial_device: 9401 // We can decide statically which value the runtime would return if called. 9402 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 9403 case Builtin::BI__builtin_add_overflow: 9404 case Builtin::BI__builtin_sub_overflow: 9405 case Builtin::BI__builtin_mul_overflow: 9406 case Builtin::BI__builtin_sadd_overflow: 9407 case Builtin::BI__builtin_uadd_overflow: 9408 case Builtin::BI__builtin_uaddl_overflow: 9409 case Builtin::BI__builtin_uaddll_overflow: 9410 case Builtin::BI__builtin_usub_overflow: 9411 case Builtin::BI__builtin_usubl_overflow: 9412 case Builtin::BI__builtin_usubll_overflow: 9413 case Builtin::BI__builtin_umul_overflow: 9414 case Builtin::BI__builtin_umull_overflow: 9415 case Builtin::BI__builtin_umulll_overflow: 9416 case Builtin::BI__builtin_saddl_overflow: 9417 case Builtin::BI__builtin_saddll_overflow: 9418 case Builtin::BI__builtin_ssub_overflow: 9419 case Builtin::BI__builtin_ssubl_overflow: 9420 case Builtin::BI__builtin_ssubll_overflow: 9421 case Builtin::BI__builtin_smul_overflow: 9422 case Builtin::BI__builtin_smull_overflow: 9423 case Builtin::BI__builtin_smulll_overflow: { 9424 LValue ResultLValue; 9425 APSInt LHS, RHS; 9426 9427 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 9428 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 9429 !EvaluateInteger(E->getArg(1), RHS, Info) || 9430 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 9431 return false; 9432 9433 APSInt Result; 9434 bool DidOverflow = false; 9435 9436 // If the types don't have to match, enlarge all 3 to the largest of them. 9437 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 9438 BuiltinOp == Builtin::BI__builtin_sub_overflow || 9439 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 9440 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 9441 ResultType->isSignedIntegerOrEnumerationType(); 9442 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 9443 ResultType->isSignedIntegerOrEnumerationType(); 9444 uint64_t LHSSize = LHS.getBitWidth(); 9445 uint64_t RHSSize = RHS.getBitWidth(); 9446 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 9447 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 9448 9449 // Add an additional bit if the signedness isn't uniformly agreed to. We 9450 // could do this ONLY if there is a signed and an unsigned that both have 9451 // MaxBits, but the code to check that is pretty nasty. The issue will be 9452 // caught in the shrink-to-result later anyway. 9453 if (IsSigned && !AllSigned) 9454 ++MaxBits; 9455 9456 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits), 9457 !IsSigned); 9458 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits), 9459 !IsSigned); 9460 Result = APSInt(MaxBits, !IsSigned); 9461 } 9462 9463 // Find largest int. 9464 switch (BuiltinOp) { 9465 default: 9466 llvm_unreachable("Invalid value for BuiltinOp"); 9467 case Builtin::BI__builtin_add_overflow: 9468 case Builtin::BI__builtin_sadd_overflow: 9469 case Builtin::BI__builtin_saddl_overflow: 9470 case Builtin::BI__builtin_saddll_overflow: 9471 case Builtin::BI__builtin_uadd_overflow: 9472 case Builtin::BI__builtin_uaddl_overflow: 9473 case Builtin::BI__builtin_uaddll_overflow: 9474 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 9475 : LHS.uadd_ov(RHS, DidOverflow); 9476 break; 9477 case Builtin::BI__builtin_sub_overflow: 9478 case Builtin::BI__builtin_ssub_overflow: 9479 case Builtin::BI__builtin_ssubl_overflow: 9480 case Builtin::BI__builtin_ssubll_overflow: 9481 case Builtin::BI__builtin_usub_overflow: 9482 case Builtin::BI__builtin_usubl_overflow: 9483 case Builtin::BI__builtin_usubll_overflow: 9484 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 9485 : LHS.usub_ov(RHS, DidOverflow); 9486 break; 9487 case Builtin::BI__builtin_mul_overflow: 9488 case Builtin::BI__builtin_smul_overflow: 9489 case Builtin::BI__builtin_smull_overflow: 9490 case Builtin::BI__builtin_smulll_overflow: 9491 case Builtin::BI__builtin_umul_overflow: 9492 case Builtin::BI__builtin_umull_overflow: 9493 case Builtin::BI__builtin_umulll_overflow: 9494 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 9495 : LHS.umul_ov(RHS, DidOverflow); 9496 break; 9497 } 9498 9499 // In the case where multiple sizes are allowed, truncate and see if 9500 // the values are the same. 9501 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 9502 BuiltinOp == Builtin::BI__builtin_sub_overflow || 9503 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 9504 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 9505 // since it will give us the behavior of a TruncOrSelf in the case where 9506 // its parameter <= its size. We previously set Result to be at least the 9507 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 9508 // will work exactly like TruncOrSelf. 9509 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 9510 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 9511 9512 if (!APSInt::isSameValue(Temp, Result)) 9513 DidOverflow = true; 9514 Result = Temp; 9515 } 9516 9517 APValue APV{Result}; 9518 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 9519 return false; 9520 return Success(DidOverflow, E); 9521 } 9522 } 9523 } 9524 9525 /// Determine whether this is a pointer past the end of the complete 9526 /// object referred to by the lvalue. 9527 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 9528 const LValue &LV) { 9529 // A null pointer can be viewed as being "past the end" but we don't 9530 // choose to look at it that way here. 9531 if (!LV.getLValueBase()) 9532 return false; 9533 9534 // If the designator is valid and refers to a subobject, we're not pointing 9535 // past the end. 9536 if (!LV.getLValueDesignator().Invalid && 9537 !LV.getLValueDesignator().isOnePastTheEnd()) 9538 return false; 9539 9540 // A pointer to an incomplete type might be past-the-end if the type's size is 9541 // zero. We cannot tell because the type is incomplete. 9542 QualType Ty = getType(LV.getLValueBase()); 9543 if (Ty->isIncompleteType()) 9544 return true; 9545 9546 // We're a past-the-end pointer if we point to the byte after the object, 9547 // no matter what our type or path is. 9548 auto Size = Ctx.getTypeSizeInChars(Ty); 9549 return LV.getLValueOffset() == Size; 9550 } 9551 9552 namespace { 9553 9554 /// Data recursive integer evaluator of certain binary operators. 9555 /// 9556 /// We use a data recursive algorithm for binary operators so that we are able 9557 /// to handle extreme cases of chained binary operators without causing stack 9558 /// overflow. 9559 class DataRecursiveIntBinOpEvaluator { 9560 struct EvalResult { 9561 APValue Val; 9562 bool Failed; 9563 9564 EvalResult() : Failed(false) { } 9565 9566 void swap(EvalResult &RHS) { 9567 Val.swap(RHS.Val); 9568 Failed = RHS.Failed; 9569 RHS.Failed = false; 9570 } 9571 }; 9572 9573 struct Job { 9574 const Expr *E; 9575 EvalResult LHSResult; // meaningful only for binary operator expression. 9576 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 9577 9578 Job() = default; 9579 Job(Job &&) = default; 9580 9581 void startSpeculativeEval(EvalInfo &Info) { 9582 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 9583 } 9584 9585 private: 9586 SpeculativeEvaluationRAII SpecEvalRAII; 9587 }; 9588 9589 SmallVector<Job, 16> Queue; 9590 9591 IntExprEvaluator &IntEval; 9592 EvalInfo &Info; 9593 APValue &FinalResult; 9594 9595 public: 9596 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 9597 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 9598 9599 /// True if \param E is a binary operator that we are going to handle 9600 /// data recursively. 9601 /// We handle binary operators that are comma, logical, or that have operands 9602 /// with integral or enumeration type. 9603 static bool shouldEnqueue(const BinaryOperator *E) { 9604 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 9605 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 9606 E->getLHS()->getType()->isIntegralOrEnumerationType() && 9607 E->getRHS()->getType()->isIntegralOrEnumerationType()); 9608 } 9609 9610 bool Traverse(const BinaryOperator *E) { 9611 enqueue(E); 9612 EvalResult PrevResult; 9613 while (!Queue.empty()) 9614 process(PrevResult); 9615 9616 if (PrevResult.Failed) return false; 9617 9618 FinalResult.swap(PrevResult.Val); 9619 return true; 9620 } 9621 9622 private: 9623 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 9624 return IntEval.Success(Value, E, Result); 9625 } 9626 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 9627 return IntEval.Success(Value, E, Result); 9628 } 9629 bool Error(const Expr *E) { 9630 return IntEval.Error(E); 9631 } 9632 bool Error(const Expr *E, diag::kind D) { 9633 return IntEval.Error(E, D); 9634 } 9635 9636 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 9637 return Info.CCEDiag(E, D); 9638 } 9639 9640 // Returns true if visiting the RHS is necessary, false otherwise. 9641 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 9642 bool &SuppressRHSDiags); 9643 9644 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 9645 const BinaryOperator *E, APValue &Result); 9646 9647 void EvaluateExpr(const Expr *E, EvalResult &Result) { 9648 Result.Failed = !Evaluate(Result.Val, Info, E); 9649 if (Result.Failed) 9650 Result.Val = APValue(); 9651 } 9652 9653 void process(EvalResult &Result); 9654 9655 void enqueue(const Expr *E) { 9656 E = E->IgnoreParens(); 9657 Queue.resize(Queue.size()+1); 9658 Queue.back().E = E; 9659 Queue.back().Kind = Job::AnyExprKind; 9660 } 9661 }; 9662 9663 } 9664 9665 bool DataRecursiveIntBinOpEvaluator:: 9666 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 9667 bool &SuppressRHSDiags) { 9668 if (E->getOpcode() == BO_Comma) { 9669 // Ignore LHS but note if we could not evaluate it. 9670 if (LHSResult.Failed) 9671 return Info.noteSideEffect(); 9672 return true; 9673 } 9674 9675 if (E->isLogicalOp()) { 9676 bool LHSAsBool; 9677 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 9678 // We were able to evaluate the LHS, see if we can get away with not 9679 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 9680 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 9681 Success(LHSAsBool, E, LHSResult.Val); 9682 return false; // Ignore RHS 9683 } 9684 } else { 9685 LHSResult.Failed = true; 9686 9687 // Since we weren't able to evaluate the left hand side, it 9688 // might have had side effects. 9689 if (!Info.noteSideEffect()) 9690 return false; 9691 9692 // We can't evaluate the LHS; however, sometimes the result 9693 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 9694 // Don't ignore RHS and suppress diagnostics from this arm. 9695 SuppressRHSDiags = true; 9696 } 9697 9698 return true; 9699 } 9700 9701 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 9702 E->getRHS()->getType()->isIntegralOrEnumerationType()); 9703 9704 if (LHSResult.Failed && !Info.noteFailure()) 9705 return false; // Ignore RHS; 9706 9707 return true; 9708 } 9709 9710 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 9711 bool IsSub) { 9712 // Compute the new offset in the appropriate width, wrapping at 64 bits. 9713 // FIXME: When compiling for a 32-bit target, we should use 32-bit 9714 // offsets. 9715 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 9716 CharUnits &Offset = LVal.getLValueOffset(); 9717 uint64_t Offset64 = Offset.getQuantity(); 9718 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 9719 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 9720 : Offset64 + Index64); 9721 } 9722 9723 bool DataRecursiveIntBinOpEvaluator:: 9724 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 9725 const BinaryOperator *E, APValue &Result) { 9726 if (E->getOpcode() == BO_Comma) { 9727 if (RHSResult.Failed) 9728 return false; 9729 Result = RHSResult.Val; 9730 return true; 9731 } 9732 9733 if (E->isLogicalOp()) { 9734 bool lhsResult, rhsResult; 9735 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 9736 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 9737 9738 if (LHSIsOK) { 9739 if (RHSIsOK) { 9740 if (E->getOpcode() == BO_LOr) 9741 return Success(lhsResult || rhsResult, E, Result); 9742 else 9743 return Success(lhsResult && rhsResult, E, Result); 9744 } 9745 } else { 9746 if (RHSIsOK) { 9747 // We can't evaluate the LHS; however, sometimes the result 9748 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 9749 if (rhsResult == (E->getOpcode() == BO_LOr)) 9750 return Success(rhsResult, E, Result); 9751 } 9752 } 9753 9754 return false; 9755 } 9756 9757 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 9758 E->getRHS()->getType()->isIntegralOrEnumerationType()); 9759 9760 if (LHSResult.Failed || RHSResult.Failed) 9761 return false; 9762 9763 const APValue &LHSVal = LHSResult.Val; 9764 const APValue &RHSVal = RHSResult.Val; 9765 9766 // Handle cases like (unsigned long)&a + 4. 9767 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 9768 Result = LHSVal; 9769 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 9770 return true; 9771 } 9772 9773 // Handle cases like 4 + (unsigned long)&a 9774 if (E->getOpcode() == BO_Add && 9775 RHSVal.isLValue() && LHSVal.isInt()) { 9776 Result = RHSVal; 9777 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 9778 return true; 9779 } 9780 9781 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 9782 // Handle (intptr_t)&&A - (intptr_t)&&B. 9783 if (!LHSVal.getLValueOffset().isZero() || 9784 !RHSVal.getLValueOffset().isZero()) 9785 return false; 9786 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 9787 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 9788 if (!LHSExpr || !RHSExpr) 9789 return false; 9790 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 9791 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 9792 if (!LHSAddrExpr || !RHSAddrExpr) 9793 return false; 9794 // Make sure both labels come from the same function. 9795 if (LHSAddrExpr->getLabel()->getDeclContext() != 9796 RHSAddrExpr->getLabel()->getDeclContext()) 9797 return false; 9798 Result = APValue(LHSAddrExpr, RHSAddrExpr); 9799 return true; 9800 } 9801 9802 // All the remaining cases expect both operands to be an integer 9803 if (!LHSVal.isInt() || !RHSVal.isInt()) 9804 return Error(E); 9805 9806 // Set up the width and signedness manually, in case it can't be deduced 9807 // from the operation we're performing. 9808 // FIXME: Don't do this in the cases where we can deduce it. 9809 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 9810 E->getType()->isUnsignedIntegerOrEnumerationType()); 9811 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 9812 RHSVal.getInt(), Value)) 9813 return false; 9814 return Success(Value, E, Result); 9815 } 9816 9817 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 9818 Job &job = Queue.back(); 9819 9820 switch (job.Kind) { 9821 case Job::AnyExprKind: { 9822 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 9823 if (shouldEnqueue(Bop)) { 9824 job.Kind = Job::BinOpKind; 9825 enqueue(Bop->getLHS()); 9826 return; 9827 } 9828 } 9829 9830 EvaluateExpr(job.E, Result); 9831 Queue.pop_back(); 9832 return; 9833 } 9834 9835 case Job::BinOpKind: { 9836 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 9837 bool SuppressRHSDiags = false; 9838 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 9839 Queue.pop_back(); 9840 return; 9841 } 9842 if (SuppressRHSDiags) 9843 job.startSpeculativeEval(Info); 9844 job.LHSResult.swap(Result); 9845 job.Kind = Job::BinOpVisitedLHSKind; 9846 enqueue(Bop->getRHS()); 9847 return; 9848 } 9849 9850 case Job::BinOpVisitedLHSKind: { 9851 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 9852 EvalResult RHS; 9853 RHS.swap(Result); 9854 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 9855 Queue.pop_back(); 9856 return; 9857 } 9858 } 9859 9860 llvm_unreachable("Invalid Job::Kind!"); 9861 } 9862 9863 namespace { 9864 /// Used when we determine that we should fail, but can keep evaluating prior to 9865 /// noting that we had a failure. 9866 class DelayedNoteFailureRAII { 9867 EvalInfo &Info; 9868 bool NoteFailure; 9869 9870 public: 9871 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 9872 : Info(Info), NoteFailure(NoteFailure) {} 9873 ~DelayedNoteFailureRAII() { 9874 if (NoteFailure) { 9875 bool ContinueAfterFailure = Info.noteFailure(); 9876 (void)ContinueAfterFailure; 9877 assert(ContinueAfterFailure && 9878 "Shouldn't have kept evaluating on failure."); 9879 } 9880 } 9881 }; 9882 } 9883 9884 template <class SuccessCB, class AfterCB> 9885 static bool 9886 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 9887 SuccessCB &&Success, AfterCB &&DoAfter) { 9888 assert(E->isComparisonOp() && "expected comparison operator"); 9889 assert((E->getOpcode() == BO_Cmp || 9890 E->getType()->isIntegralOrEnumerationType()) && 9891 "unsupported binary expression evaluation"); 9892 auto Error = [&](const Expr *E) { 9893 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 9894 return false; 9895 }; 9896 9897 using CCR = ComparisonCategoryResult; 9898 bool IsRelational = E->isRelationalOp(); 9899 bool IsEquality = E->isEqualityOp(); 9900 if (E->getOpcode() == BO_Cmp) { 9901 const ComparisonCategoryInfo &CmpInfo = 9902 Info.Ctx.CompCategories.getInfoForType(E->getType()); 9903 IsRelational = CmpInfo.isOrdered(); 9904 IsEquality = CmpInfo.isEquality(); 9905 } 9906 9907 QualType LHSTy = E->getLHS()->getType(); 9908 QualType RHSTy = E->getRHS()->getType(); 9909 9910 if (LHSTy->isIntegralOrEnumerationType() && 9911 RHSTy->isIntegralOrEnumerationType()) { 9912 APSInt LHS, RHS; 9913 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 9914 if (!LHSOK && !Info.noteFailure()) 9915 return false; 9916 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 9917 return false; 9918 if (LHS < RHS) 9919 return Success(CCR::Less, E); 9920 if (LHS > RHS) 9921 return Success(CCR::Greater, E); 9922 return Success(CCR::Equal, E); 9923 } 9924 9925 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 9926 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 9927 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 9928 9929 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 9930 if (!LHSOK && !Info.noteFailure()) 9931 return false; 9932 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 9933 return false; 9934 if (LHSFX < RHSFX) 9935 return Success(CCR::Less, E); 9936 if (LHSFX > RHSFX) 9937 return Success(CCR::Greater, E); 9938 return Success(CCR::Equal, E); 9939 } 9940 9941 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 9942 ComplexValue LHS, RHS; 9943 bool LHSOK; 9944 if (E->isAssignmentOp()) { 9945 LValue LV; 9946 EvaluateLValue(E->getLHS(), LV, Info); 9947 LHSOK = false; 9948 } else if (LHSTy->isRealFloatingType()) { 9949 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 9950 if (LHSOK) { 9951 LHS.makeComplexFloat(); 9952 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 9953 } 9954 } else { 9955 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 9956 } 9957 if (!LHSOK && !Info.noteFailure()) 9958 return false; 9959 9960 if (E->getRHS()->getType()->isRealFloatingType()) { 9961 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 9962 return false; 9963 RHS.makeComplexFloat(); 9964 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 9965 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 9966 return false; 9967 9968 if (LHS.isComplexFloat()) { 9969 APFloat::cmpResult CR_r = 9970 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 9971 APFloat::cmpResult CR_i = 9972 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 9973 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 9974 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 9975 } else { 9976 assert(IsEquality && "invalid complex comparison"); 9977 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 9978 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 9979 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 9980 } 9981 } 9982 9983 if (LHSTy->isRealFloatingType() && 9984 RHSTy->isRealFloatingType()) { 9985 APFloat RHS(0.0), LHS(0.0); 9986 9987 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 9988 if (!LHSOK && !Info.noteFailure()) 9989 return false; 9990 9991 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 9992 return false; 9993 9994 assert(E->isComparisonOp() && "Invalid binary operator!"); 9995 auto GetCmpRes = [&]() { 9996 switch (LHS.compare(RHS)) { 9997 case APFloat::cmpEqual: 9998 return CCR::Equal; 9999 case APFloat::cmpLessThan: 10000 return CCR::Less; 10001 case APFloat::cmpGreaterThan: 10002 return CCR::Greater; 10003 case APFloat::cmpUnordered: 10004 return CCR::Unordered; 10005 } 10006 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 10007 }; 10008 return Success(GetCmpRes(), E); 10009 } 10010 10011 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 10012 LValue LHSValue, RHSValue; 10013 10014 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 10015 if (!LHSOK && !Info.noteFailure()) 10016 return false; 10017 10018 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10019 return false; 10020 10021 // Reject differing bases from the normal codepath; we special-case 10022 // comparisons to null. 10023 if (!HasSameBase(LHSValue, RHSValue)) { 10024 // Inequalities and subtractions between unrelated pointers have 10025 // unspecified or undefined behavior. 10026 if (!IsEquality) 10027 return Error(E); 10028 // A constant address may compare equal to the address of a symbol. 10029 // The one exception is that address of an object cannot compare equal 10030 // to a null pointer constant. 10031 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 10032 (!RHSValue.Base && !RHSValue.Offset.isZero())) 10033 return Error(E); 10034 // It's implementation-defined whether distinct literals will have 10035 // distinct addresses. In clang, the result of such a comparison is 10036 // unspecified, so it is not a constant expression. However, we do know 10037 // that the address of a literal will be non-null. 10038 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 10039 LHSValue.Base && RHSValue.Base) 10040 return Error(E); 10041 // We can't tell whether weak symbols will end up pointing to the same 10042 // object. 10043 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 10044 return Error(E); 10045 // We can't compare the address of the start of one object with the 10046 // past-the-end address of another object, per C++ DR1652. 10047 if ((LHSValue.Base && LHSValue.Offset.isZero() && 10048 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 10049 (RHSValue.Base && RHSValue.Offset.isZero() && 10050 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 10051 return Error(E); 10052 // We can't tell whether an object is at the same address as another 10053 // zero sized object. 10054 if ((RHSValue.Base && isZeroSized(LHSValue)) || 10055 (LHSValue.Base && isZeroSized(RHSValue))) 10056 return Error(E); 10057 return Success(CCR::Nonequal, E); 10058 } 10059 10060 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 10061 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 10062 10063 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 10064 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 10065 10066 // C++11 [expr.rel]p3: 10067 // Pointers to void (after pointer conversions) can be compared, with a 10068 // result defined as follows: If both pointers represent the same 10069 // address or are both the null pointer value, the result is true if the 10070 // operator is <= or >= and false otherwise; otherwise the result is 10071 // unspecified. 10072 // We interpret this as applying to pointers to *cv* void. 10073 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 10074 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 10075 10076 // C++11 [expr.rel]p2: 10077 // - If two pointers point to non-static data members of the same object, 10078 // or to subobjects or array elements fo such members, recursively, the 10079 // pointer to the later declared member compares greater provided the 10080 // two members have the same access control and provided their class is 10081 // not a union. 10082 // [...] 10083 // - Otherwise pointer comparisons are unspecified. 10084 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 10085 bool WasArrayIndex; 10086 unsigned Mismatch = FindDesignatorMismatch( 10087 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 10088 // At the point where the designators diverge, the comparison has a 10089 // specified value if: 10090 // - we are comparing array indices 10091 // - we are comparing fields of a union, or fields with the same access 10092 // Otherwise, the result is unspecified and thus the comparison is not a 10093 // constant expression. 10094 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 10095 Mismatch < RHSDesignator.Entries.size()) { 10096 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 10097 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 10098 if (!LF && !RF) 10099 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 10100 else if (!LF) 10101 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 10102 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 10103 << RF->getParent() << RF; 10104 else if (!RF) 10105 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 10106 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 10107 << LF->getParent() << LF; 10108 else if (!LF->getParent()->isUnion() && 10109 LF->getAccess() != RF->getAccess()) 10110 Info.CCEDiag(E, 10111 diag::note_constexpr_pointer_comparison_differing_access) 10112 << LF << LF->getAccess() << RF << RF->getAccess() 10113 << LF->getParent(); 10114 } 10115 } 10116 10117 // The comparison here must be unsigned, and performed with the same 10118 // width as the pointer. 10119 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 10120 uint64_t CompareLHS = LHSOffset.getQuantity(); 10121 uint64_t CompareRHS = RHSOffset.getQuantity(); 10122 assert(PtrSize <= 64 && "Unexpected pointer width"); 10123 uint64_t Mask = ~0ULL >> (64 - PtrSize); 10124 CompareLHS &= Mask; 10125 CompareRHS &= Mask; 10126 10127 // If there is a base and this is a relational operator, we can only 10128 // compare pointers within the object in question; otherwise, the result 10129 // depends on where the object is located in memory. 10130 if (!LHSValue.Base.isNull() && IsRelational) { 10131 QualType BaseTy = getType(LHSValue.Base); 10132 if (BaseTy->isIncompleteType()) 10133 return Error(E); 10134 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 10135 uint64_t OffsetLimit = Size.getQuantity(); 10136 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 10137 return Error(E); 10138 } 10139 10140 if (CompareLHS < CompareRHS) 10141 return Success(CCR::Less, E); 10142 if (CompareLHS > CompareRHS) 10143 return Success(CCR::Greater, E); 10144 return Success(CCR::Equal, E); 10145 } 10146 10147 if (LHSTy->isMemberPointerType()) { 10148 assert(IsEquality && "unexpected member pointer operation"); 10149 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 10150 10151 MemberPtr LHSValue, RHSValue; 10152 10153 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 10154 if (!LHSOK && !Info.noteFailure()) 10155 return false; 10156 10157 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10158 return false; 10159 10160 // C++11 [expr.eq]p2: 10161 // If both operands are null, they compare equal. Otherwise if only one is 10162 // null, they compare unequal. 10163 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 10164 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 10165 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 10166 } 10167 10168 // Otherwise if either is a pointer to a virtual member function, the 10169 // result is unspecified. 10170 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 10171 if (MD->isVirtual()) 10172 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 10173 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 10174 if (MD->isVirtual()) 10175 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 10176 10177 // Otherwise they compare equal if and only if they would refer to the 10178 // same member of the same most derived object or the same subobject if 10179 // they were dereferenced with a hypothetical object of the associated 10180 // class type. 10181 bool Equal = LHSValue == RHSValue; 10182 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 10183 } 10184 10185 if (LHSTy->isNullPtrType()) { 10186 assert(E->isComparisonOp() && "unexpected nullptr operation"); 10187 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 10188 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 10189 // are compared, the result is true of the operator is <=, >= or ==, and 10190 // false otherwise. 10191 return Success(CCR::Equal, E); 10192 } 10193 10194 return DoAfter(); 10195 } 10196 10197 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 10198 if (!CheckLiteralType(Info, E)) 10199 return false; 10200 10201 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 10202 const BinaryOperator *E) { 10203 // Evaluation succeeded. Lookup the information for the comparison category 10204 // type and fetch the VarDecl for the result. 10205 const ComparisonCategoryInfo &CmpInfo = 10206 Info.Ctx.CompCategories.getInfoForType(E->getType()); 10207 const VarDecl *VD = 10208 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; 10209 // Check and evaluate the result as a constant expression. 10210 LValue LV; 10211 LV.set(VD); 10212 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 10213 return false; 10214 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 10215 }; 10216 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 10217 return ExprEvaluatorBaseTy::VisitBinCmp(E); 10218 }); 10219 } 10220 10221 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10222 // We don't call noteFailure immediately because the assignment happens after 10223 // we evaluate LHS and RHS. 10224 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 10225 return Error(E); 10226 10227 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 10228 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 10229 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 10230 10231 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 10232 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 10233 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 10234 10235 if (E->isComparisonOp()) { 10236 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way 10237 // comparisons and then translating the result. 10238 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 10239 const BinaryOperator *E) { 10240 using CCR = ComparisonCategoryResult; 10241 bool IsEqual = ResKind == CCR::Equal, 10242 IsLess = ResKind == CCR::Less, 10243 IsGreater = ResKind == CCR::Greater; 10244 auto Op = E->getOpcode(); 10245 switch (Op) { 10246 default: 10247 llvm_unreachable("unsupported binary operator"); 10248 case BO_EQ: 10249 case BO_NE: 10250 return Success(IsEqual == (Op == BO_EQ), E); 10251 case BO_LT: return Success(IsLess, E); 10252 case BO_GT: return Success(IsGreater, E); 10253 case BO_LE: return Success(IsEqual || IsLess, E); 10254 case BO_GE: return Success(IsEqual || IsGreater, E); 10255 } 10256 }; 10257 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 10258 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10259 }); 10260 } 10261 10262 QualType LHSTy = E->getLHS()->getType(); 10263 QualType RHSTy = E->getRHS()->getType(); 10264 10265 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 10266 E->getOpcode() == BO_Sub) { 10267 LValue LHSValue, RHSValue; 10268 10269 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 10270 if (!LHSOK && !Info.noteFailure()) 10271 return false; 10272 10273 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 10274 return false; 10275 10276 // Reject differing bases from the normal codepath; we special-case 10277 // comparisons to null. 10278 if (!HasSameBase(LHSValue, RHSValue)) { 10279 // Handle &&A - &&B. 10280 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 10281 return Error(E); 10282 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 10283 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 10284 if (!LHSExpr || !RHSExpr) 10285 return Error(E); 10286 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 10287 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 10288 if (!LHSAddrExpr || !RHSAddrExpr) 10289 return Error(E); 10290 // Make sure both labels come from the same function. 10291 if (LHSAddrExpr->getLabel()->getDeclContext() != 10292 RHSAddrExpr->getLabel()->getDeclContext()) 10293 return Error(E); 10294 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 10295 } 10296 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 10297 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 10298 10299 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 10300 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 10301 10302 // C++11 [expr.add]p6: 10303 // Unless both pointers point to elements of the same array object, or 10304 // one past the last element of the array object, the behavior is 10305 // undefined. 10306 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 10307 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 10308 RHSDesignator)) 10309 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 10310 10311 QualType Type = E->getLHS()->getType(); 10312 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 10313 10314 CharUnits ElementSize; 10315 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 10316 return false; 10317 10318 // As an extension, a type may have zero size (empty struct or union in 10319 // C, array of zero length). Pointer subtraction in such cases has 10320 // undefined behavior, so is not constant. 10321 if (ElementSize.isZero()) { 10322 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 10323 << ElementType; 10324 return false; 10325 } 10326 10327 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 10328 // and produce incorrect results when it overflows. Such behavior 10329 // appears to be non-conforming, but is common, so perhaps we should 10330 // assume the standard intended for such cases to be undefined behavior 10331 // and check for them. 10332 10333 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 10334 // overflow in the final conversion to ptrdiff_t. 10335 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 10336 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 10337 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 10338 false); 10339 APSInt TrueResult = (LHS - RHS) / ElemSize; 10340 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 10341 10342 if (Result.extend(65) != TrueResult && 10343 !HandleOverflow(Info, E, TrueResult, E->getType())) 10344 return false; 10345 return Success(Result, E); 10346 } 10347 10348 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 10349 } 10350 10351 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 10352 /// a result as the expression's type. 10353 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 10354 const UnaryExprOrTypeTraitExpr *E) { 10355 switch(E->getKind()) { 10356 case UETT_PreferredAlignOf: 10357 case UETT_AlignOf: { 10358 if (E->isArgumentType()) 10359 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 10360 E); 10361 else 10362 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 10363 E); 10364 } 10365 10366 case UETT_VecStep: { 10367 QualType Ty = E->getTypeOfArgument(); 10368 10369 if (Ty->isVectorType()) { 10370 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 10371 10372 // The vec_step built-in functions that take a 3-component 10373 // vector return 4. (OpenCL 1.1 spec 6.11.12) 10374 if (n == 3) 10375 n = 4; 10376 10377 return Success(n, E); 10378 } else 10379 return Success(1, E); 10380 } 10381 10382 case UETT_SizeOf: { 10383 QualType SrcTy = E->getTypeOfArgument(); 10384 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 10385 // the result is the size of the referenced type." 10386 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 10387 SrcTy = Ref->getPointeeType(); 10388 10389 CharUnits Sizeof; 10390 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 10391 return false; 10392 return Success(Sizeof, E); 10393 } 10394 case UETT_OpenMPRequiredSimdAlign: 10395 assert(E->isArgumentType()); 10396 return Success( 10397 Info.Ctx.toCharUnitsFromBits( 10398 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 10399 .getQuantity(), 10400 E); 10401 } 10402 10403 llvm_unreachable("unknown expr/type trait"); 10404 } 10405 10406 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 10407 CharUnits Result; 10408 unsigned n = OOE->getNumComponents(); 10409 if (n == 0) 10410 return Error(OOE); 10411 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 10412 for (unsigned i = 0; i != n; ++i) { 10413 OffsetOfNode ON = OOE->getComponent(i); 10414 switch (ON.getKind()) { 10415 case OffsetOfNode::Array: { 10416 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 10417 APSInt IdxResult; 10418 if (!EvaluateInteger(Idx, IdxResult, Info)) 10419 return false; 10420 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 10421 if (!AT) 10422 return Error(OOE); 10423 CurrentType = AT->getElementType(); 10424 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 10425 Result += IdxResult.getSExtValue() * ElementSize; 10426 break; 10427 } 10428 10429 case OffsetOfNode::Field: { 10430 FieldDecl *MemberDecl = ON.getField(); 10431 const RecordType *RT = CurrentType->getAs<RecordType>(); 10432 if (!RT) 10433 return Error(OOE); 10434 RecordDecl *RD = RT->getDecl(); 10435 if (RD->isInvalidDecl()) return false; 10436 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 10437 unsigned i = MemberDecl->getFieldIndex(); 10438 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 10439 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 10440 CurrentType = MemberDecl->getType().getNonReferenceType(); 10441 break; 10442 } 10443 10444 case OffsetOfNode::Identifier: 10445 llvm_unreachable("dependent __builtin_offsetof"); 10446 10447 case OffsetOfNode::Base: { 10448 CXXBaseSpecifier *BaseSpec = ON.getBase(); 10449 if (BaseSpec->isVirtual()) 10450 return Error(OOE); 10451 10452 // Find the layout of the class whose base we are looking into. 10453 const RecordType *RT = CurrentType->getAs<RecordType>(); 10454 if (!RT) 10455 return Error(OOE); 10456 RecordDecl *RD = RT->getDecl(); 10457 if (RD->isInvalidDecl()) return false; 10458 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 10459 10460 // Find the base class itself. 10461 CurrentType = BaseSpec->getType(); 10462 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 10463 if (!BaseRT) 10464 return Error(OOE); 10465 10466 // Add the offset to the base. 10467 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 10468 break; 10469 } 10470 } 10471 } 10472 return Success(Result, OOE); 10473 } 10474 10475 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10476 switch (E->getOpcode()) { 10477 default: 10478 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 10479 // See C99 6.6p3. 10480 return Error(E); 10481 case UO_Extension: 10482 // FIXME: Should extension allow i-c-e extension expressions in its scope? 10483 // If so, we could clear the diagnostic ID. 10484 return Visit(E->getSubExpr()); 10485 case UO_Plus: 10486 // The result is just the value. 10487 return Visit(E->getSubExpr()); 10488 case UO_Minus: { 10489 if (!Visit(E->getSubExpr())) 10490 return false; 10491 if (!Result.isInt()) return Error(E); 10492 const APSInt &Value = Result.getInt(); 10493 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 10494 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 10495 E->getType())) 10496 return false; 10497 return Success(-Value, E); 10498 } 10499 case UO_Not: { 10500 if (!Visit(E->getSubExpr())) 10501 return false; 10502 if (!Result.isInt()) return Error(E); 10503 return Success(~Result.getInt(), E); 10504 } 10505 case UO_LNot: { 10506 bool bres; 10507 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 10508 return false; 10509 return Success(!bres, E); 10510 } 10511 } 10512 } 10513 10514 /// HandleCast - This is used to evaluate implicit or explicit casts where the 10515 /// result type is integer. 10516 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 10517 const Expr *SubExpr = E->getSubExpr(); 10518 QualType DestType = E->getType(); 10519 QualType SrcType = SubExpr->getType(); 10520 10521 switch (E->getCastKind()) { 10522 case CK_BaseToDerived: 10523 case CK_DerivedToBase: 10524 case CK_UncheckedDerivedToBase: 10525 case CK_Dynamic: 10526 case CK_ToUnion: 10527 case CK_ArrayToPointerDecay: 10528 case CK_FunctionToPointerDecay: 10529 case CK_NullToPointer: 10530 case CK_NullToMemberPointer: 10531 case CK_BaseToDerivedMemberPointer: 10532 case CK_DerivedToBaseMemberPointer: 10533 case CK_ReinterpretMemberPointer: 10534 case CK_ConstructorConversion: 10535 case CK_IntegralToPointer: 10536 case CK_ToVoid: 10537 case CK_VectorSplat: 10538 case CK_IntegralToFloating: 10539 case CK_FloatingCast: 10540 case CK_CPointerToObjCPointerCast: 10541 case CK_BlockPointerToObjCPointerCast: 10542 case CK_AnyPointerToBlockPointerCast: 10543 case CK_ObjCObjectLValueCast: 10544 case CK_FloatingRealToComplex: 10545 case CK_FloatingComplexToReal: 10546 case CK_FloatingComplexCast: 10547 case CK_FloatingComplexToIntegralComplex: 10548 case CK_IntegralRealToComplex: 10549 case CK_IntegralComplexCast: 10550 case CK_IntegralComplexToFloatingComplex: 10551 case CK_BuiltinFnToFnPtr: 10552 case CK_ZeroToOCLOpaqueType: 10553 case CK_NonAtomicToAtomic: 10554 case CK_AddressSpaceConversion: 10555 case CK_IntToOCLSampler: 10556 case CK_FixedPointCast: 10557 case CK_IntegralToFixedPoint: 10558 llvm_unreachable("invalid cast kind for integral value"); 10559 10560 case CK_BitCast: 10561 case CK_Dependent: 10562 case CK_LValueBitCast: 10563 case CK_ARCProduceObject: 10564 case CK_ARCConsumeObject: 10565 case CK_ARCReclaimReturnedObject: 10566 case CK_ARCExtendBlockObject: 10567 case CK_CopyAndAutoreleaseBlockObject: 10568 return Error(E); 10569 10570 case CK_UserDefinedConversion: 10571 case CK_LValueToRValue: 10572 case CK_AtomicToNonAtomic: 10573 case CK_NoOp: 10574 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10575 10576 case CK_MemberPointerToBoolean: 10577 case CK_PointerToBoolean: 10578 case CK_IntegralToBoolean: 10579 case CK_FloatingToBoolean: 10580 case CK_BooleanToSignedIntegral: 10581 case CK_FloatingComplexToBoolean: 10582 case CK_IntegralComplexToBoolean: { 10583 bool BoolResult; 10584 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 10585 return false; 10586 uint64_t IntResult = BoolResult; 10587 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 10588 IntResult = (uint64_t)-1; 10589 return Success(IntResult, E); 10590 } 10591 10592 case CK_FixedPointToIntegral: { 10593 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 10594 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 10595 return false; 10596 bool Overflowed; 10597 llvm::APSInt Result = Src.convertToInt( 10598 Info.Ctx.getIntWidth(DestType), 10599 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 10600 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 10601 return false; 10602 return Success(Result, E); 10603 } 10604 10605 case CK_FixedPointToBoolean: { 10606 // Unsigned padding does not affect this. 10607 APValue Val; 10608 if (!Evaluate(Val, Info, SubExpr)) 10609 return false; 10610 return Success(Val.getFixedPoint().getBoolValue(), E); 10611 } 10612 10613 case CK_IntegralCast: { 10614 if (!Visit(SubExpr)) 10615 return false; 10616 10617 if (!Result.isInt()) { 10618 // Allow casts of address-of-label differences if they are no-ops 10619 // or narrowing. (The narrowing case isn't actually guaranteed to 10620 // be constant-evaluatable except in some narrow cases which are hard 10621 // to detect here. We let it through on the assumption the user knows 10622 // what they are doing.) 10623 if (Result.isAddrLabelDiff()) 10624 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 10625 // Only allow casts of lvalues if they are lossless. 10626 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 10627 } 10628 10629 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 10630 Result.getInt()), E); 10631 } 10632 10633 case CK_PointerToIntegral: { 10634 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 10635 10636 LValue LV; 10637 if (!EvaluatePointer(SubExpr, LV, Info)) 10638 return false; 10639 10640 if (LV.getLValueBase()) { 10641 // Only allow based lvalue casts if they are lossless. 10642 // FIXME: Allow a larger integer size than the pointer size, and allow 10643 // narrowing back down to pointer width in subsequent integral casts. 10644 // FIXME: Check integer type's active bits, not its type size. 10645 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 10646 return Error(E); 10647 10648 LV.Designator.setInvalid(); 10649 LV.moveInto(Result); 10650 return true; 10651 } 10652 10653 APSInt AsInt; 10654 APValue V; 10655 LV.moveInto(V); 10656 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 10657 llvm_unreachable("Can't cast this!"); 10658 10659 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 10660 } 10661 10662 case CK_IntegralComplexToReal: { 10663 ComplexValue C; 10664 if (!EvaluateComplex(SubExpr, C, Info)) 10665 return false; 10666 return Success(C.getComplexIntReal(), E); 10667 } 10668 10669 case CK_FloatingToIntegral: { 10670 APFloat F(0.0); 10671 if (!EvaluateFloat(SubExpr, F, Info)) 10672 return false; 10673 10674 APSInt Value; 10675 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 10676 return false; 10677 return Success(Value, E); 10678 } 10679 } 10680 10681 llvm_unreachable("unknown cast resulting in integral value"); 10682 } 10683 10684 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 10685 if (E->getSubExpr()->getType()->isAnyComplexType()) { 10686 ComplexValue LV; 10687 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 10688 return false; 10689 if (!LV.isComplexInt()) 10690 return Error(E); 10691 return Success(LV.getComplexIntReal(), E); 10692 } 10693 10694 return Visit(E->getSubExpr()); 10695 } 10696 10697 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10698 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 10699 ComplexValue LV; 10700 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 10701 return false; 10702 if (!LV.isComplexInt()) 10703 return Error(E); 10704 return Success(LV.getComplexIntImag(), E); 10705 } 10706 10707 VisitIgnoredValue(E->getSubExpr()); 10708 return Success(0, E); 10709 } 10710 10711 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 10712 return Success(E->getPackLength(), E); 10713 } 10714 10715 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 10716 return Success(E->getValue(), E); 10717 } 10718 10719 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10720 switch (E->getOpcode()) { 10721 default: 10722 // Invalid unary operators 10723 return Error(E); 10724 case UO_Plus: 10725 // The result is just the value. 10726 return Visit(E->getSubExpr()); 10727 case UO_Minus: { 10728 if (!Visit(E->getSubExpr())) return false; 10729 if (!Result.isFixedPoint()) 10730 return Error(E); 10731 bool Overflowed; 10732 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 10733 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 10734 return false; 10735 return Success(Negated, E); 10736 } 10737 case UO_LNot: { 10738 bool bres; 10739 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 10740 return false; 10741 return Success(!bres, E); 10742 } 10743 } 10744 } 10745 10746 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 10747 const Expr *SubExpr = E->getSubExpr(); 10748 QualType DestType = E->getType(); 10749 assert(DestType->isFixedPointType() && 10750 "Expected destination type to be a fixed point type"); 10751 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 10752 10753 switch (E->getCastKind()) { 10754 case CK_FixedPointCast: { 10755 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 10756 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 10757 return false; 10758 bool Overflowed; 10759 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 10760 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 10761 return false; 10762 return Success(Result, E); 10763 } 10764 case CK_IntegralToFixedPoint: { 10765 APSInt Src; 10766 if (!EvaluateInteger(SubExpr, Src, Info)) 10767 return false; 10768 10769 bool Overflowed; 10770 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 10771 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 10772 10773 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType)) 10774 return false; 10775 10776 return Success(IntResult, E); 10777 } 10778 case CK_NoOp: 10779 case CK_LValueToRValue: 10780 return ExprEvaluatorBaseTy::VisitCastExpr(E); 10781 default: 10782 return Error(E); 10783 } 10784 } 10785 10786 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 10787 const Expr *LHS = E->getLHS(); 10788 const Expr *RHS = E->getRHS(); 10789 FixedPointSemantics ResultFXSema = 10790 Info.Ctx.getFixedPointSemantics(E->getType()); 10791 10792 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 10793 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 10794 return false; 10795 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 10796 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 10797 return false; 10798 10799 switch (E->getOpcode()) { 10800 case BO_Add: { 10801 bool AddOverflow, ConversionOverflow; 10802 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow) 10803 .convert(ResultFXSema, &ConversionOverflow); 10804 if ((AddOverflow || ConversionOverflow) && 10805 !HandleOverflow(Info, E, Result, E->getType())) 10806 return false; 10807 return Success(Result, E); 10808 } 10809 default: 10810 return false; 10811 } 10812 llvm_unreachable("Should've exited before this"); 10813 } 10814 10815 //===----------------------------------------------------------------------===// 10816 // Float Evaluation 10817 //===----------------------------------------------------------------------===// 10818 10819 namespace { 10820 class FloatExprEvaluator 10821 : public ExprEvaluatorBase<FloatExprEvaluator> { 10822 APFloat &Result; 10823 public: 10824 FloatExprEvaluator(EvalInfo &info, APFloat &result) 10825 : ExprEvaluatorBaseTy(info), Result(result) {} 10826 10827 bool Success(const APValue &V, const Expr *e) { 10828 Result = V.getFloat(); 10829 return true; 10830 } 10831 10832 bool ZeroInitialization(const Expr *E) { 10833 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 10834 return true; 10835 } 10836 10837 bool VisitCallExpr(const CallExpr *E); 10838 10839 bool VisitUnaryOperator(const UnaryOperator *E); 10840 bool VisitBinaryOperator(const BinaryOperator *E); 10841 bool VisitFloatingLiteral(const FloatingLiteral *E); 10842 bool VisitCastExpr(const CastExpr *E); 10843 10844 bool VisitUnaryReal(const UnaryOperator *E); 10845 bool VisitUnaryImag(const UnaryOperator *E); 10846 10847 // FIXME: Missing: array subscript of vector, member of vector 10848 }; 10849 } // end anonymous namespace 10850 10851 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 10852 assert(E->isRValue() && E->getType()->isRealFloatingType()); 10853 return FloatExprEvaluator(Info, Result).Visit(E); 10854 } 10855 10856 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 10857 QualType ResultTy, 10858 const Expr *Arg, 10859 bool SNaN, 10860 llvm::APFloat &Result) { 10861 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 10862 if (!S) return false; 10863 10864 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 10865 10866 llvm::APInt fill; 10867 10868 // Treat empty strings as if they were zero. 10869 if (S->getString().empty()) 10870 fill = llvm::APInt(32, 0); 10871 else if (S->getString().getAsInteger(0, fill)) 10872 return false; 10873 10874 if (Context.getTargetInfo().isNan2008()) { 10875 if (SNaN) 10876 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 10877 else 10878 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 10879 } else { 10880 // Prior to IEEE 754-2008, architectures were allowed to choose whether 10881 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 10882 // a different encoding to what became a standard in 2008, and for pre- 10883 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 10884 // sNaN. This is now known as "legacy NaN" encoding. 10885 if (SNaN) 10886 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 10887 else 10888 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 10889 } 10890 10891 return true; 10892 } 10893 10894 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 10895 switch (E->getBuiltinCallee()) { 10896 default: 10897 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10898 10899 case Builtin::BI__builtin_huge_val: 10900 case Builtin::BI__builtin_huge_valf: 10901 case Builtin::BI__builtin_huge_vall: 10902 case Builtin::BI__builtin_huge_valf128: 10903 case Builtin::BI__builtin_inf: 10904 case Builtin::BI__builtin_inff: 10905 case Builtin::BI__builtin_infl: 10906 case Builtin::BI__builtin_inff128: { 10907 const llvm::fltSemantics &Sem = 10908 Info.Ctx.getFloatTypeSemantics(E->getType()); 10909 Result = llvm::APFloat::getInf(Sem); 10910 return true; 10911 } 10912 10913 case Builtin::BI__builtin_nans: 10914 case Builtin::BI__builtin_nansf: 10915 case Builtin::BI__builtin_nansl: 10916 case Builtin::BI__builtin_nansf128: 10917 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 10918 true, Result)) 10919 return Error(E); 10920 return true; 10921 10922 case Builtin::BI__builtin_nan: 10923 case Builtin::BI__builtin_nanf: 10924 case Builtin::BI__builtin_nanl: 10925 case Builtin::BI__builtin_nanf128: 10926 // If this is __builtin_nan() turn this into a nan, otherwise we 10927 // can't constant fold it. 10928 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 10929 false, Result)) 10930 return Error(E); 10931 return true; 10932 10933 case Builtin::BI__builtin_fabs: 10934 case Builtin::BI__builtin_fabsf: 10935 case Builtin::BI__builtin_fabsl: 10936 case Builtin::BI__builtin_fabsf128: 10937 if (!EvaluateFloat(E->getArg(0), Result, Info)) 10938 return false; 10939 10940 if (Result.isNegative()) 10941 Result.changeSign(); 10942 return true; 10943 10944 // FIXME: Builtin::BI__builtin_powi 10945 // FIXME: Builtin::BI__builtin_powif 10946 // FIXME: Builtin::BI__builtin_powil 10947 10948 case Builtin::BI__builtin_copysign: 10949 case Builtin::BI__builtin_copysignf: 10950 case Builtin::BI__builtin_copysignl: 10951 case Builtin::BI__builtin_copysignf128: { 10952 APFloat RHS(0.); 10953 if (!EvaluateFloat(E->getArg(0), Result, Info) || 10954 !EvaluateFloat(E->getArg(1), RHS, Info)) 10955 return false; 10956 Result.copySign(RHS); 10957 return true; 10958 } 10959 } 10960 } 10961 10962 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 10963 if (E->getSubExpr()->getType()->isAnyComplexType()) { 10964 ComplexValue CV; 10965 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 10966 return false; 10967 Result = CV.FloatReal; 10968 return true; 10969 } 10970 10971 return Visit(E->getSubExpr()); 10972 } 10973 10974 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 10975 if (E->getSubExpr()->getType()->isAnyComplexType()) { 10976 ComplexValue CV; 10977 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 10978 return false; 10979 Result = CV.FloatImag; 10980 return true; 10981 } 10982 10983 VisitIgnoredValue(E->getSubExpr()); 10984 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 10985 Result = llvm::APFloat::getZero(Sem); 10986 return true; 10987 } 10988 10989 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 10990 switch (E->getOpcode()) { 10991 default: return Error(E); 10992 case UO_Plus: 10993 return EvaluateFloat(E->getSubExpr(), Result, Info); 10994 case UO_Minus: 10995 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 10996 return false; 10997 Result.changeSign(); 10998 return true; 10999 } 11000 } 11001 11002 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11003 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 11004 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11005 11006 APFloat RHS(0.0); 11007 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 11008 if (!LHSOK && !Info.noteFailure()) 11009 return false; 11010 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 11011 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 11012 } 11013 11014 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 11015 Result = E->getValue(); 11016 return true; 11017 } 11018 11019 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 11020 const Expr* SubExpr = E->getSubExpr(); 11021 11022 switch (E->getCastKind()) { 11023 default: 11024 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11025 11026 case CK_IntegralToFloating: { 11027 APSInt IntResult; 11028 return EvaluateInteger(SubExpr, IntResult, Info) && 11029 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 11030 E->getType(), Result); 11031 } 11032 11033 case CK_FloatingCast: { 11034 if (!Visit(SubExpr)) 11035 return false; 11036 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 11037 Result); 11038 } 11039 11040 case CK_FloatingComplexToReal: { 11041 ComplexValue V; 11042 if (!EvaluateComplex(SubExpr, V, Info)) 11043 return false; 11044 Result = V.getComplexFloatReal(); 11045 return true; 11046 } 11047 } 11048 } 11049 11050 //===----------------------------------------------------------------------===// 11051 // Complex Evaluation (for float and integer) 11052 //===----------------------------------------------------------------------===// 11053 11054 namespace { 11055 class ComplexExprEvaluator 11056 : public ExprEvaluatorBase<ComplexExprEvaluator> { 11057 ComplexValue &Result; 11058 11059 public: 11060 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 11061 : ExprEvaluatorBaseTy(info), Result(Result) {} 11062 11063 bool Success(const APValue &V, const Expr *e) { 11064 Result.setFrom(V); 11065 return true; 11066 } 11067 11068 bool ZeroInitialization(const Expr *E); 11069 11070 //===--------------------------------------------------------------------===// 11071 // Visitor Methods 11072 //===--------------------------------------------------------------------===// 11073 11074 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 11075 bool VisitCastExpr(const CastExpr *E); 11076 bool VisitBinaryOperator(const BinaryOperator *E); 11077 bool VisitUnaryOperator(const UnaryOperator *E); 11078 bool VisitInitListExpr(const InitListExpr *E); 11079 }; 11080 } // end anonymous namespace 11081 11082 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 11083 EvalInfo &Info) { 11084 assert(E->isRValue() && E->getType()->isAnyComplexType()); 11085 return ComplexExprEvaluator(Info, Result).Visit(E); 11086 } 11087 11088 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 11089 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 11090 if (ElemTy->isRealFloatingType()) { 11091 Result.makeComplexFloat(); 11092 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 11093 Result.FloatReal = Zero; 11094 Result.FloatImag = Zero; 11095 } else { 11096 Result.makeComplexInt(); 11097 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 11098 Result.IntReal = Zero; 11099 Result.IntImag = Zero; 11100 } 11101 return true; 11102 } 11103 11104 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 11105 const Expr* SubExpr = E->getSubExpr(); 11106 11107 if (SubExpr->getType()->isRealFloatingType()) { 11108 Result.makeComplexFloat(); 11109 APFloat &Imag = Result.FloatImag; 11110 if (!EvaluateFloat(SubExpr, Imag, Info)) 11111 return false; 11112 11113 Result.FloatReal = APFloat(Imag.getSemantics()); 11114 return true; 11115 } else { 11116 assert(SubExpr->getType()->isIntegerType() && 11117 "Unexpected imaginary literal."); 11118 11119 Result.makeComplexInt(); 11120 APSInt &Imag = Result.IntImag; 11121 if (!EvaluateInteger(SubExpr, Imag, Info)) 11122 return false; 11123 11124 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 11125 return true; 11126 } 11127 } 11128 11129 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 11130 11131 switch (E->getCastKind()) { 11132 case CK_BitCast: 11133 case CK_BaseToDerived: 11134 case CK_DerivedToBase: 11135 case CK_UncheckedDerivedToBase: 11136 case CK_Dynamic: 11137 case CK_ToUnion: 11138 case CK_ArrayToPointerDecay: 11139 case CK_FunctionToPointerDecay: 11140 case CK_NullToPointer: 11141 case CK_NullToMemberPointer: 11142 case CK_BaseToDerivedMemberPointer: 11143 case CK_DerivedToBaseMemberPointer: 11144 case CK_MemberPointerToBoolean: 11145 case CK_ReinterpretMemberPointer: 11146 case CK_ConstructorConversion: 11147 case CK_IntegralToPointer: 11148 case CK_PointerToIntegral: 11149 case CK_PointerToBoolean: 11150 case CK_ToVoid: 11151 case CK_VectorSplat: 11152 case CK_IntegralCast: 11153 case CK_BooleanToSignedIntegral: 11154 case CK_IntegralToBoolean: 11155 case CK_IntegralToFloating: 11156 case CK_FloatingToIntegral: 11157 case CK_FloatingToBoolean: 11158 case CK_FloatingCast: 11159 case CK_CPointerToObjCPointerCast: 11160 case CK_BlockPointerToObjCPointerCast: 11161 case CK_AnyPointerToBlockPointerCast: 11162 case CK_ObjCObjectLValueCast: 11163 case CK_FloatingComplexToReal: 11164 case CK_FloatingComplexToBoolean: 11165 case CK_IntegralComplexToReal: 11166 case CK_IntegralComplexToBoolean: 11167 case CK_ARCProduceObject: 11168 case CK_ARCConsumeObject: 11169 case CK_ARCReclaimReturnedObject: 11170 case CK_ARCExtendBlockObject: 11171 case CK_CopyAndAutoreleaseBlockObject: 11172 case CK_BuiltinFnToFnPtr: 11173 case CK_ZeroToOCLOpaqueType: 11174 case CK_NonAtomicToAtomic: 11175 case CK_AddressSpaceConversion: 11176 case CK_IntToOCLSampler: 11177 case CK_FixedPointCast: 11178 case CK_FixedPointToBoolean: 11179 case CK_FixedPointToIntegral: 11180 case CK_IntegralToFixedPoint: 11181 llvm_unreachable("invalid cast kind for complex value"); 11182 11183 case CK_LValueToRValue: 11184 case CK_AtomicToNonAtomic: 11185 case CK_NoOp: 11186 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11187 11188 case CK_Dependent: 11189 case CK_LValueBitCast: 11190 case CK_UserDefinedConversion: 11191 return Error(E); 11192 11193 case CK_FloatingRealToComplex: { 11194 APFloat &Real = Result.FloatReal; 11195 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 11196 return false; 11197 11198 Result.makeComplexFloat(); 11199 Result.FloatImag = APFloat(Real.getSemantics()); 11200 return true; 11201 } 11202 11203 case CK_FloatingComplexCast: { 11204 if (!Visit(E->getSubExpr())) 11205 return false; 11206 11207 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11208 QualType From 11209 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11210 11211 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 11212 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 11213 } 11214 11215 case CK_FloatingComplexToIntegralComplex: { 11216 if (!Visit(E->getSubExpr())) 11217 return false; 11218 11219 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11220 QualType From 11221 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11222 Result.makeComplexInt(); 11223 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 11224 To, Result.IntReal) && 11225 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 11226 To, Result.IntImag); 11227 } 11228 11229 case CK_IntegralRealToComplex: { 11230 APSInt &Real = Result.IntReal; 11231 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 11232 return false; 11233 11234 Result.makeComplexInt(); 11235 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 11236 return true; 11237 } 11238 11239 case CK_IntegralComplexCast: { 11240 if (!Visit(E->getSubExpr())) 11241 return false; 11242 11243 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 11244 QualType From 11245 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 11246 11247 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 11248 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 11249 return true; 11250 } 11251 11252 case CK_IntegralComplexToFloatingComplex: { 11253 if (!Visit(E->getSubExpr())) 11254 return false; 11255 11256 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 11257 QualType From 11258 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 11259 Result.makeComplexFloat(); 11260 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 11261 To, Result.FloatReal) && 11262 HandleIntToFloatCast(Info, E, From, Result.IntImag, 11263 To, Result.FloatImag); 11264 } 11265 } 11266 11267 llvm_unreachable("unknown cast resulting in complex value"); 11268 } 11269 11270 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11271 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 11272 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11273 11274 // Track whether the LHS or RHS is real at the type system level. When this is 11275 // the case we can simplify our evaluation strategy. 11276 bool LHSReal = false, RHSReal = false; 11277 11278 bool LHSOK; 11279 if (E->getLHS()->getType()->isRealFloatingType()) { 11280 LHSReal = true; 11281 APFloat &Real = Result.FloatReal; 11282 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 11283 if (LHSOK) { 11284 Result.makeComplexFloat(); 11285 Result.FloatImag = APFloat(Real.getSemantics()); 11286 } 11287 } else { 11288 LHSOK = Visit(E->getLHS()); 11289 } 11290 if (!LHSOK && !Info.noteFailure()) 11291 return false; 11292 11293 ComplexValue RHS; 11294 if (E->getRHS()->getType()->isRealFloatingType()) { 11295 RHSReal = true; 11296 APFloat &Real = RHS.FloatReal; 11297 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 11298 return false; 11299 RHS.makeComplexFloat(); 11300 RHS.FloatImag = APFloat(Real.getSemantics()); 11301 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 11302 return false; 11303 11304 assert(!(LHSReal && RHSReal) && 11305 "Cannot have both operands of a complex operation be real."); 11306 switch (E->getOpcode()) { 11307 default: return Error(E); 11308 case BO_Add: 11309 if (Result.isComplexFloat()) { 11310 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 11311 APFloat::rmNearestTiesToEven); 11312 if (LHSReal) 11313 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 11314 else if (!RHSReal) 11315 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 11316 APFloat::rmNearestTiesToEven); 11317 } else { 11318 Result.getComplexIntReal() += RHS.getComplexIntReal(); 11319 Result.getComplexIntImag() += RHS.getComplexIntImag(); 11320 } 11321 break; 11322 case BO_Sub: 11323 if (Result.isComplexFloat()) { 11324 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 11325 APFloat::rmNearestTiesToEven); 11326 if (LHSReal) { 11327 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 11328 Result.getComplexFloatImag().changeSign(); 11329 } else if (!RHSReal) { 11330 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 11331 APFloat::rmNearestTiesToEven); 11332 } 11333 } else { 11334 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 11335 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 11336 } 11337 break; 11338 case BO_Mul: 11339 if (Result.isComplexFloat()) { 11340 // This is an implementation of complex multiplication according to the 11341 // constraints laid out in C11 Annex G. The implementation uses the 11342 // following naming scheme: 11343 // (a + ib) * (c + id) 11344 ComplexValue LHS = Result; 11345 APFloat &A = LHS.getComplexFloatReal(); 11346 APFloat &B = LHS.getComplexFloatImag(); 11347 APFloat &C = RHS.getComplexFloatReal(); 11348 APFloat &D = RHS.getComplexFloatImag(); 11349 APFloat &ResR = Result.getComplexFloatReal(); 11350 APFloat &ResI = Result.getComplexFloatImag(); 11351 if (LHSReal) { 11352 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 11353 ResR = A * C; 11354 ResI = A * D; 11355 } else if (RHSReal) { 11356 ResR = C * A; 11357 ResI = C * B; 11358 } else { 11359 // In the fully general case, we need to handle NaNs and infinities 11360 // robustly. 11361 APFloat AC = A * C; 11362 APFloat BD = B * D; 11363 APFloat AD = A * D; 11364 APFloat BC = B * C; 11365 ResR = AC - BD; 11366 ResI = AD + BC; 11367 if (ResR.isNaN() && ResI.isNaN()) { 11368 bool Recalc = false; 11369 if (A.isInfinity() || B.isInfinity()) { 11370 A = APFloat::copySign( 11371 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 11372 B = APFloat::copySign( 11373 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 11374 if (C.isNaN()) 11375 C = APFloat::copySign(APFloat(C.getSemantics()), C); 11376 if (D.isNaN()) 11377 D = APFloat::copySign(APFloat(D.getSemantics()), D); 11378 Recalc = true; 11379 } 11380 if (C.isInfinity() || D.isInfinity()) { 11381 C = APFloat::copySign( 11382 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 11383 D = APFloat::copySign( 11384 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 11385 if (A.isNaN()) 11386 A = APFloat::copySign(APFloat(A.getSemantics()), A); 11387 if (B.isNaN()) 11388 B = APFloat::copySign(APFloat(B.getSemantics()), B); 11389 Recalc = true; 11390 } 11391 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 11392 AD.isInfinity() || BC.isInfinity())) { 11393 if (A.isNaN()) 11394 A = APFloat::copySign(APFloat(A.getSemantics()), A); 11395 if (B.isNaN()) 11396 B = APFloat::copySign(APFloat(B.getSemantics()), B); 11397 if (C.isNaN()) 11398 C = APFloat::copySign(APFloat(C.getSemantics()), C); 11399 if (D.isNaN()) 11400 D = APFloat::copySign(APFloat(D.getSemantics()), D); 11401 Recalc = true; 11402 } 11403 if (Recalc) { 11404 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 11405 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 11406 } 11407 } 11408 } 11409 } else { 11410 ComplexValue LHS = Result; 11411 Result.getComplexIntReal() = 11412 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 11413 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 11414 Result.getComplexIntImag() = 11415 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 11416 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 11417 } 11418 break; 11419 case BO_Div: 11420 if (Result.isComplexFloat()) { 11421 // This is an implementation of complex division according to the 11422 // constraints laid out in C11 Annex G. The implementation uses the 11423 // following naming scheme: 11424 // (a + ib) / (c + id) 11425 ComplexValue LHS = Result; 11426 APFloat &A = LHS.getComplexFloatReal(); 11427 APFloat &B = LHS.getComplexFloatImag(); 11428 APFloat &C = RHS.getComplexFloatReal(); 11429 APFloat &D = RHS.getComplexFloatImag(); 11430 APFloat &ResR = Result.getComplexFloatReal(); 11431 APFloat &ResI = Result.getComplexFloatImag(); 11432 if (RHSReal) { 11433 ResR = A / C; 11434 ResI = B / C; 11435 } else { 11436 if (LHSReal) { 11437 // No real optimizations we can do here, stub out with zero. 11438 B = APFloat::getZero(A.getSemantics()); 11439 } 11440 int DenomLogB = 0; 11441 APFloat MaxCD = maxnum(abs(C), abs(D)); 11442 if (MaxCD.isFinite()) { 11443 DenomLogB = ilogb(MaxCD); 11444 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 11445 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 11446 } 11447 APFloat Denom = C * C + D * D; 11448 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 11449 APFloat::rmNearestTiesToEven); 11450 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 11451 APFloat::rmNearestTiesToEven); 11452 if (ResR.isNaN() && ResI.isNaN()) { 11453 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 11454 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 11455 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 11456 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 11457 D.isFinite()) { 11458 A = APFloat::copySign( 11459 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 11460 B = APFloat::copySign( 11461 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 11462 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 11463 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 11464 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 11465 C = APFloat::copySign( 11466 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 11467 D = APFloat::copySign( 11468 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 11469 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 11470 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 11471 } 11472 } 11473 } 11474 } else { 11475 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 11476 return Error(E, diag::note_expr_divide_by_zero); 11477 11478 ComplexValue LHS = Result; 11479 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 11480 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 11481 Result.getComplexIntReal() = 11482 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 11483 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 11484 Result.getComplexIntImag() = 11485 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 11486 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 11487 } 11488 break; 11489 } 11490 11491 return true; 11492 } 11493 11494 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 11495 // Get the operand value into 'Result'. 11496 if (!Visit(E->getSubExpr())) 11497 return false; 11498 11499 switch (E->getOpcode()) { 11500 default: 11501 return Error(E); 11502 case UO_Extension: 11503 return true; 11504 case UO_Plus: 11505 // The result is always just the subexpr. 11506 return true; 11507 case UO_Minus: 11508 if (Result.isComplexFloat()) { 11509 Result.getComplexFloatReal().changeSign(); 11510 Result.getComplexFloatImag().changeSign(); 11511 } 11512 else { 11513 Result.getComplexIntReal() = -Result.getComplexIntReal(); 11514 Result.getComplexIntImag() = -Result.getComplexIntImag(); 11515 } 11516 return true; 11517 case UO_Not: 11518 if (Result.isComplexFloat()) 11519 Result.getComplexFloatImag().changeSign(); 11520 else 11521 Result.getComplexIntImag() = -Result.getComplexIntImag(); 11522 return true; 11523 } 11524 } 11525 11526 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 11527 if (E->getNumInits() == 2) { 11528 if (E->getType()->isComplexType()) { 11529 Result.makeComplexFloat(); 11530 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 11531 return false; 11532 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 11533 return false; 11534 } else { 11535 Result.makeComplexInt(); 11536 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 11537 return false; 11538 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 11539 return false; 11540 } 11541 return true; 11542 } 11543 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 11544 } 11545 11546 //===----------------------------------------------------------------------===// 11547 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 11548 // implicit conversion. 11549 //===----------------------------------------------------------------------===// 11550 11551 namespace { 11552 class AtomicExprEvaluator : 11553 public ExprEvaluatorBase<AtomicExprEvaluator> { 11554 const LValue *This; 11555 APValue &Result; 11556 public: 11557 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 11558 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 11559 11560 bool Success(const APValue &V, const Expr *E) { 11561 Result = V; 11562 return true; 11563 } 11564 11565 bool ZeroInitialization(const Expr *E) { 11566 ImplicitValueInitExpr VIE( 11567 E->getType()->castAs<AtomicType>()->getValueType()); 11568 // For atomic-qualified class (and array) types in C++, initialize the 11569 // _Atomic-wrapped subobject directly, in-place. 11570 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 11571 : Evaluate(Result, Info, &VIE); 11572 } 11573 11574 bool VisitCastExpr(const CastExpr *E) { 11575 switch (E->getCastKind()) { 11576 default: 11577 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11578 case CK_NonAtomicToAtomic: 11579 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 11580 : Evaluate(Result, Info, E->getSubExpr()); 11581 } 11582 } 11583 }; 11584 } // end anonymous namespace 11585 11586 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 11587 EvalInfo &Info) { 11588 assert(E->isRValue() && E->getType()->isAtomicType()); 11589 return AtomicExprEvaluator(Info, This, Result).Visit(E); 11590 } 11591 11592 //===----------------------------------------------------------------------===// 11593 // Void expression evaluation, primarily for a cast to void on the LHS of a 11594 // comma operator 11595 //===----------------------------------------------------------------------===// 11596 11597 namespace { 11598 class VoidExprEvaluator 11599 : public ExprEvaluatorBase<VoidExprEvaluator> { 11600 public: 11601 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 11602 11603 bool Success(const APValue &V, const Expr *e) { return true; } 11604 11605 bool ZeroInitialization(const Expr *E) { return true; } 11606 11607 bool VisitCastExpr(const CastExpr *E) { 11608 switch (E->getCastKind()) { 11609 default: 11610 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11611 case CK_ToVoid: 11612 VisitIgnoredValue(E->getSubExpr()); 11613 return true; 11614 } 11615 } 11616 11617 bool VisitCallExpr(const CallExpr *E) { 11618 switch (E->getBuiltinCallee()) { 11619 default: 11620 return ExprEvaluatorBaseTy::VisitCallExpr(E); 11621 case Builtin::BI__assume: 11622 case Builtin::BI__builtin_assume: 11623 // The argument is not evaluated! 11624 return true; 11625 } 11626 } 11627 }; 11628 } // end anonymous namespace 11629 11630 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 11631 assert(E->isRValue() && E->getType()->isVoidType()); 11632 return VoidExprEvaluator(Info).Visit(E); 11633 } 11634 11635 //===----------------------------------------------------------------------===// 11636 // Top level Expr::EvaluateAsRValue method. 11637 //===----------------------------------------------------------------------===// 11638 11639 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 11640 // In C, function designators are not lvalues, but we evaluate them as if they 11641 // are. 11642 QualType T = E->getType(); 11643 if (E->isGLValue() || T->isFunctionType()) { 11644 LValue LV; 11645 if (!EvaluateLValue(E, LV, Info)) 11646 return false; 11647 LV.moveInto(Result); 11648 } else if (T->isVectorType()) { 11649 if (!EvaluateVector(E, Result, Info)) 11650 return false; 11651 } else if (T->isIntegralOrEnumerationType()) { 11652 if (!IntExprEvaluator(Info, Result).Visit(E)) 11653 return false; 11654 } else if (T->hasPointerRepresentation()) { 11655 LValue LV; 11656 if (!EvaluatePointer(E, LV, Info)) 11657 return false; 11658 LV.moveInto(Result); 11659 } else if (T->isRealFloatingType()) { 11660 llvm::APFloat F(0.0); 11661 if (!EvaluateFloat(E, F, Info)) 11662 return false; 11663 Result = APValue(F); 11664 } else if (T->isAnyComplexType()) { 11665 ComplexValue C; 11666 if (!EvaluateComplex(E, C, Info)) 11667 return false; 11668 C.moveInto(Result); 11669 } else if (T->isFixedPointType()) { 11670 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 11671 } else if (T->isMemberPointerType()) { 11672 MemberPtr P; 11673 if (!EvaluateMemberPointer(E, P, Info)) 11674 return false; 11675 P.moveInto(Result); 11676 return true; 11677 } else if (T->isArrayType()) { 11678 LValue LV; 11679 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 11680 if (!EvaluateArray(E, LV, Value, Info)) 11681 return false; 11682 Result = Value; 11683 } else if (T->isRecordType()) { 11684 LValue LV; 11685 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 11686 if (!EvaluateRecord(E, LV, Value, Info)) 11687 return false; 11688 Result = Value; 11689 } else if (T->isVoidType()) { 11690 if (!Info.getLangOpts().CPlusPlus11) 11691 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 11692 << E->getType(); 11693 if (!EvaluateVoid(E, Info)) 11694 return false; 11695 } else if (T->isAtomicType()) { 11696 QualType Unqual = T.getAtomicUnqualifiedType(); 11697 if (Unqual->isArrayType() || Unqual->isRecordType()) { 11698 LValue LV; 11699 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall); 11700 if (!EvaluateAtomic(E, &LV, Value, Info)) 11701 return false; 11702 } else { 11703 if (!EvaluateAtomic(E, nullptr, Result, Info)) 11704 return false; 11705 } 11706 } else if (Info.getLangOpts().CPlusPlus11) { 11707 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 11708 return false; 11709 } else { 11710 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11711 return false; 11712 } 11713 11714 return true; 11715 } 11716 11717 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 11718 /// cases, the in-place evaluation is essential, since later initializers for 11719 /// an object can indirectly refer to subobjects which were initialized earlier. 11720 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 11721 const Expr *E, bool AllowNonLiteralTypes) { 11722 assert(!E->isValueDependent()); 11723 11724 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 11725 return false; 11726 11727 if (E->isRValue()) { 11728 // Evaluate arrays and record types in-place, so that later initializers can 11729 // refer to earlier-initialized members of the object. 11730 QualType T = E->getType(); 11731 if (T->isArrayType()) 11732 return EvaluateArray(E, This, Result, Info); 11733 else if (T->isRecordType()) 11734 return EvaluateRecord(E, This, Result, Info); 11735 else if (T->isAtomicType()) { 11736 QualType Unqual = T.getAtomicUnqualifiedType(); 11737 if (Unqual->isArrayType() || Unqual->isRecordType()) 11738 return EvaluateAtomic(E, &This, Result, Info); 11739 } 11740 } 11741 11742 // For any other type, in-place evaluation is unimportant. 11743 return Evaluate(Result, Info, E); 11744 } 11745 11746 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 11747 /// lvalue-to-rvalue cast if it is an lvalue. 11748 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 11749 if (E->getType().isNull()) 11750 return false; 11751 11752 if (!CheckLiteralType(Info, E)) 11753 return false; 11754 11755 if (!::Evaluate(Result, Info, E)) 11756 return false; 11757 11758 if (E->isGLValue()) { 11759 LValue LV; 11760 LV.setFrom(Info.Ctx, Result); 11761 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 11762 return false; 11763 } 11764 11765 // Check this core constant expression is a constant expression. 11766 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 11767 } 11768 11769 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 11770 const ASTContext &Ctx, bool &IsConst) { 11771 // Fast-path evaluations of integer literals, since we sometimes see files 11772 // containing vast quantities of these. 11773 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 11774 Result.Val = APValue(APSInt(L->getValue(), 11775 L->getType()->isUnsignedIntegerType())); 11776 IsConst = true; 11777 return true; 11778 } 11779 11780 // This case should be rare, but we need to check it before we check on 11781 // the type below. 11782 if (Exp->getType().isNull()) { 11783 IsConst = false; 11784 return true; 11785 } 11786 11787 // FIXME: Evaluating values of large array and record types can cause 11788 // performance problems. Only do so in C++11 for now. 11789 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 11790 Exp->getType()->isRecordType()) && 11791 !Ctx.getLangOpts().CPlusPlus11) { 11792 IsConst = false; 11793 return true; 11794 } 11795 return false; 11796 } 11797 11798 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 11799 Expr::SideEffectsKind SEK) { 11800 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 11801 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 11802 } 11803 11804 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 11805 const ASTContext &Ctx, EvalInfo &Info) { 11806 bool IsConst; 11807 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 11808 return IsConst; 11809 11810 return EvaluateAsRValue(Info, E, Result.Val); 11811 } 11812 11813 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 11814 const ASTContext &Ctx, 11815 Expr::SideEffectsKind AllowSideEffects, 11816 EvalInfo &Info) { 11817 if (!E->getType()->isIntegralOrEnumerationType()) 11818 return false; 11819 11820 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 11821 !ExprResult.Val.isInt() || 11822 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 11823 return false; 11824 11825 return true; 11826 } 11827 11828 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 11829 const ASTContext &Ctx, 11830 Expr::SideEffectsKind AllowSideEffects, 11831 EvalInfo &Info) { 11832 if (!E->getType()->isFixedPointType()) 11833 return false; 11834 11835 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 11836 return false; 11837 11838 if (!ExprResult.Val.isFixedPoint() || 11839 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 11840 return false; 11841 11842 return true; 11843 } 11844 11845 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 11846 /// any crazy technique (that has nothing to do with language standards) that 11847 /// we want to. If this function returns true, it returns the folded constant 11848 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 11849 /// will be applied to the result. 11850 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 11851 bool InConstantContext) const { 11852 assert(!isValueDependent() && 11853 "Expression evaluator can't be called on a dependent expression."); 11854 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 11855 Info.InConstantContext = InConstantContext; 11856 return ::EvaluateAsRValue(this, Result, Ctx, Info); 11857 } 11858 11859 bool Expr::EvaluateAsBooleanCondition(bool &Result, 11860 const ASTContext &Ctx) const { 11861 assert(!isValueDependent() && 11862 "Expression evaluator can't be called on a dependent expression."); 11863 EvalResult Scratch; 11864 return EvaluateAsRValue(Scratch, Ctx) && 11865 HandleConversionToBool(Scratch.Val, Result); 11866 } 11867 11868 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 11869 SideEffectsKind AllowSideEffects) const { 11870 assert(!isValueDependent() && 11871 "Expression evaluator can't be called on a dependent expression."); 11872 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 11873 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 11874 } 11875 11876 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 11877 SideEffectsKind AllowSideEffects) const { 11878 assert(!isValueDependent() && 11879 "Expression evaluator can't be called on a dependent expression."); 11880 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 11881 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 11882 } 11883 11884 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 11885 SideEffectsKind AllowSideEffects) const { 11886 assert(!isValueDependent() && 11887 "Expression evaluator can't be called on a dependent expression."); 11888 11889 if (!getType()->isRealFloatingType()) 11890 return false; 11891 11892 EvalResult ExprResult; 11893 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() || 11894 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 11895 return false; 11896 11897 Result = ExprResult.Val.getFloat(); 11898 return true; 11899 } 11900 11901 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const { 11902 assert(!isValueDependent() && 11903 "Expression evaluator can't be called on a dependent expression."); 11904 11905 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 11906 11907 LValue LV; 11908 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects || 11909 !CheckLValueConstantExpression(Info, getExprLoc(), 11910 Ctx.getLValueReferenceType(getType()), LV, 11911 Expr::EvaluateForCodeGen)) 11912 return false; 11913 11914 LV.moveInto(Result.Val); 11915 return true; 11916 } 11917 11918 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 11919 const ASTContext &Ctx) const { 11920 assert(!isValueDependent() && 11921 "Expression evaluator can't be called on a dependent expression."); 11922 11923 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 11924 EvalInfo Info(Ctx, Result, EM); 11925 Info.InConstantContext = true; 11926 11927 if (!::Evaluate(Result.Val, Info, this)) 11928 return false; 11929 11930 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val, 11931 Usage); 11932 } 11933 11934 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 11935 const VarDecl *VD, 11936 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 11937 assert(!isValueDependent() && 11938 "Expression evaluator can't be called on a dependent expression."); 11939 11940 // FIXME: Evaluating initializers for large array and record types can cause 11941 // performance problems. Only do so in C++11 for now. 11942 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 11943 !Ctx.getLangOpts().CPlusPlus11) 11944 return false; 11945 11946 Expr::EvalStatus EStatus; 11947 EStatus.Diag = &Notes; 11948 11949 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr() 11950 ? EvalInfo::EM_ConstantExpression 11951 : EvalInfo::EM_ConstantFold); 11952 InitInfo.setEvaluatingDecl(VD, Value); 11953 InitInfo.InConstantContext = true; 11954 11955 LValue LVal; 11956 LVal.set(VD); 11957 11958 // C++11 [basic.start.init]p2: 11959 // Variables with static storage duration or thread storage duration shall be 11960 // zero-initialized before any other initialization takes place. 11961 // This behavior is not present in C. 11962 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 11963 !VD->getType()->isReferenceType()) { 11964 ImplicitValueInitExpr VIE(VD->getType()); 11965 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, 11966 /*AllowNonLiteralTypes=*/true)) 11967 return false; 11968 } 11969 11970 if (!EvaluateInPlace(Value, InitInfo, LVal, this, 11971 /*AllowNonLiteralTypes=*/true) || 11972 EStatus.HasSideEffects) 11973 return false; 11974 11975 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(), 11976 Value); 11977 } 11978 11979 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 11980 /// constant folded, but discard the result. 11981 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 11982 assert(!isValueDependent() && 11983 "Expression evaluator can't be called on a dependent expression."); 11984 11985 EvalResult Result; 11986 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 11987 !hasUnacceptableSideEffect(Result, SEK); 11988 } 11989 11990 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 11991 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 11992 assert(!isValueDependent() && 11993 "Expression evaluator can't be called on a dependent expression."); 11994 11995 EvalResult EVResult; 11996 EVResult.Diag = Diag; 11997 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 11998 Info.InConstantContext = true; 11999 12000 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 12001 (void)Result; 12002 assert(Result && "Could not evaluate expression"); 12003 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 12004 12005 return EVResult.Val.getInt(); 12006 } 12007 12008 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 12009 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 12010 assert(!isValueDependent() && 12011 "Expression evaluator can't be called on a dependent expression."); 12012 12013 EvalResult EVResult; 12014 EVResult.Diag = Diag; 12015 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow); 12016 Info.InConstantContext = true; 12017 12018 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 12019 (void)Result; 12020 assert(Result && "Could not evaluate expression"); 12021 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 12022 12023 return EVResult.Val.getInt(); 12024 } 12025 12026 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 12027 assert(!isValueDependent() && 12028 "Expression evaluator can't be called on a dependent expression."); 12029 12030 bool IsConst; 12031 EvalResult EVResult; 12032 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 12033 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow); 12034 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 12035 } 12036 } 12037 12038 bool Expr::EvalResult::isGlobalLValue() const { 12039 assert(Val.isLValue()); 12040 return IsGlobalLValue(Val.getLValueBase()); 12041 } 12042 12043 12044 /// isIntegerConstantExpr - this recursive routine will test if an expression is 12045 /// an integer constant expression. 12046 12047 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 12048 /// comma, etc 12049 12050 // CheckICE - This function does the fundamental ICE checking: the returned 12051 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 12052 // and a (possibly null) SourceLocation indicating the location of the problem. 12053 // 12054 // Note that to reduce code duplication, this helper does no evaluation 12055 // itself; the caller checks whether the expression is evaluatable, and 12056 // in the rare cases where CheckICE actually cares about the evaluated 12057 // value, it calls into Evaluate. 12058 12059 namespace { 12060 12061 enum ICEKind { 12062 /// This expression is an ICE. 12063 IK_ICE, 12064 /// This expression is not an ICE, but if it isn't evaluated, it's 12065 /// a legal subexpression for an ICE. This return value is used to handle 12066 /// the comma operator in C99 mode, and non-constant subexpressions. 12067 IK_ICEIfUnevaluated, 12068 /// This expression is not an ICE, and is not a legal subexpression for one. 12069 IK_NotICE 12070 }; 12071 12072 struct ICEDiag { 12073 ICEKind Kind; 12074 SourceLocation Loc; 12075 12076 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 12077 }; 12078 12079 } 12080 12081 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 12082 12083 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 12084 12085 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 12086 Expr::EvalResult EVResult; 12087 Expr::EvalStatus Status; 12088 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 12089 12090 Info.InConstantContext = true; 12091 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 12092 !EVResult.Val.isInt()) 12093 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12094 12095 return NoDiag(); 12096 } 12097 12098 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 12099 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 12100 if (!E->getType()->isIntegralOrEnumerationType()) 12101 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12102 12103 switch (E->getStmtClass()) { 12104 #define ABSTRACT_STMT(Node) 12105 #define STMT(Node, Base) case Expr::Node##Class: 12106 #define EXPR(Node, Base) 12107 #include "clang/AST/StmtNodes.inc" 12108 case Expr::PredefinedExprClass: 12109 case Expr::FloatingLiteralClass: 12110 case Expr::ImaginaryLiteralClass: 12111 case Expr::StringLiteralClass: 12112 case Expr::ArraySubscriptExprClass: 12113 case Expr::OMPArraySectionExprClass: 12114 case Expr::MemberExprClass: 12115 case Expr::CompoundAssignOperatorClass: 12116 case Expr::CompoundLiteralExprClass: 12117 case Expr::ExtVectorElementExprClass: 12118 case Expr::DesignatedInitExprClass: 12119 case Expr::ArrayInitLoopExprClass: 12120 case Expr::ArrayInitIndexExprClass: 12121 case Expr::NoInitExprClass: 12122 case Expr::DesignatedInitUpdateExprClass: 12123 case Expr::ImplicitValueInitExprClass: 12124 case Expr::ParenListExprClass: 12125 case Expr::VAArgExprClass: 12126 case Expr::AddrLabelExprClass: 12127 case Expr::StmtExprClass: 12128 case Expr::CXXMemberCallExprClass: 12129 case Expr::CUDAKernelCallExprClass: 12130 case Expr::CXXDynamicCastExprClass: 12131 case Expr::CXXTypeidExprClass: 12132 case Expr::CXXUuidofExprClass: 12133 case Expr::MSPropertyRefExprClass: 12134 case Expr::MSPropertySubscriptExprClass: 12135 case Expr::CXXNullPtrLiteralExprClass: 12136 case Expr::UserDefinedLiteralClass: 12137 case Expr::CXXThisExprClass: 12138 case Expr::CXXThrowExprClass: 12139 case Expr::CXXNewExprClass: 12140 case Expr::CXXDeleteExprClass: 12141 case Expr::CXXPseudoDestructorExprClass: 12142 case Expr::UnresolvedLookupExprClass: 12143 case Expr::TypoExprClass: 12144 case Expr::DependentScopeDeclRefExprClass: 12145 case Expr::CXXConstructExprClass: 12146 case Expr::CXXInheritedCtorInitExprClass: 12147 case Expr::CXXStdInitializerListExprClass: 12148 case Expr::CXXBindTemporaryExprClass: 12149 case Expr::ExprWithCleanupsClass: 12150 case Expr::CXXTemporaryObjectExprClass: 12151 case Expr::CXXUnresolvedConstructExprClass: 12152 case Expr::CXXDependentScopeMemberExprClass: 12153 case Expr::UnresolvedMemberExprClass: 12154 case Expr::ObjCStringLiteralClass: 12155 case Expr::ObjCBoxedExprClass: 12156 case Expr::ObjCArrayLiteralClass: 12157 case Expr::ObjCDictionaryLiteralClass: 12158 case Expr::ObjCEncodeExprClass: 12159 case Expr::ObjCMessageExprClass: 12160 case Expr::ObjCSelectorExprClass: 12161 case Expr::ObjCProtocolExprClass: 12162 case Expr::ObjCIvarRefExprClass: 12163 case Expr::ObjCPropertyRefExprClass: 12164 case Expr::ObjCSubscriptRefExprClass: 12165 case Expr::ObjCIsaExprClass: 12166 case Expr::ObjCAvailabilityCheckExprClass: 12167 case Expr::ShuffleVectorExprClass: 12168 case Expr::ConvertVectorExprClass: 12169 case Expr::BlockExprClass: 12170 case Expr::NoStmtClass: 12171 case Expr::OpaqueValueExprClass: 12172 case Expr::PackExpansionExprClass: 12173 case Expr::SubstNonTypeTemplateParmPackExprClass: 12174 case Expr::FunctionParmPackExprClass: 12175 case Expr::AsTypeExprClass: 12176 case Expr::ObjCIndirectCopyRestoreExprClass: 12177 case Expr::MaterializeTemporaryExprClass: 12178 case Expr::PseudoObjectExprClass: 12179 case Expr::AtomicExprClass: 12180 case Expr::LambdaExprClass: 12181 case Expr::CXXFoldExprClass: 12182 case Expr::CoawaitExprClass: 12183 case Expr::DependentCoawaitExprClass: 12184 case Expr::CoyieldExprClass: 12185 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12186 12187 case Expr::InitListExprClass: { 12188 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 12189 // form "T x = { a };" is equivalent to "T x = a;". 12190 // Unless we're initializing a reference, T is a scalar as it is known to be 12191 // of integral or enumeration type. 12192 if (E->isRValue()) 12193 if (cast<InitListExpr>(E)->getNumInits() == 1) 12194 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 12195 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12196 } 12197 12198 case Expr::SizeOfPackExprClass: 12199 case Expr::GNUNullExprClass: 12200 case Expr::SourceLocExprClass: 12201 return NoDiag(); 12202 12203 case Expr::SubstNonTypeTemplateParmExprClass: 12204 return 12205 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 12206 12207 case Expr::ConstantExprClass: 12208 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 12209 12210 case Expr::ParenExprClass: 12211 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 12212 case Expr::GenericSelectionExprClass: 12213 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 12214 case Expr::IntegerLiteralClass: 12215 case Expr::FixedPointLiteralClass: 12216 case Expr::CharacterLiteralClass: 12217 case Expr::ObjCBoolLiteralExprClass: 12218 case Expr::CXXBoolLiteralExprClass: 12219 case Expr::CXXScalarValueInitExprClass: 12220 case Expr::TypeTraitExprClass: 12221 case Expr::ArrayTypeTraitExprClass: 12222 case Expr::ExpressionTraitExprClass: 12223 case Expr::CXXNoexceptExprClass: 12224 return NoDiag(); 12225 case Expr::CallExprClass: 12226 case Expr::CXXOperatorCallExprClass: { 12227 // C99 6.6/3 allows function calls within unevaluated subexpressions of 12228 // constant expressions, but they can never be ICEs because an ICE cannot 12229 // contain an operand of (pointer to) function type. 12230 const CallExpr *CE = cast<CallExpr>(E); 12231 if (CE->getBuiltinCallee()) 12232 return CheckEvalInICE(E, Ctx); 12233 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12234 } 12235 case Expr::DeclRefExprClass: { 12236 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 12237 return NoDiag(); 12238 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 12239 if (Ctx.getLangOpts().CPlusPlus && 12240 D && IsConstNonVolatile(D->getType())) { 12241 // Parameter variables are never constants. Without this check, 12242 // getAnyInitializer() can find a default argument, which leads 12243 // to chaos. 12244 if (isa<ParmVarDecl>(D)) 12245 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12246 12247 // C++ 7.1.5.1p2 12248 // A variable of non-volatile const-qualified integral or enumeration 12249 // type initialized by an ICE can be used in ICEs. 12250 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 12251 if (!Dcl->getType()->isIntegralOrEnumerationType()) 12252 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12253 12254 const VarDecl *VD; 12255 // Look for a declaration of this variable that has an initializer, and 12256 // check whether it is an ICE. 12257 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 12258 return NoDiag(); 12259 else 12260 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 12261 } 12262 } 12263 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12264 } 12265 case Expr::UnaryOperatorClass: { 12266 const UnaryOperator *Exp = cast<UnaryOperator>(E); 12267 switch (Exp->getOpcode()) { 12268 case UO_PostInc: 12269 case UO_PostDec: 12270 case UO_PreInc: 12271 case UO_PreDec: 12272 case UO_AddrOf: 12273 case UO_Deref: 12274 case UO_Coawait: 12275 // C99 6.6/3 allows increment and decrement within unevaluated 12276 // subexpressions of constant expressions, but they can never be ICEs 12277 // because an ICE cannot contain an lvalue operand. 12278 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12279 case UO_Extension: 12280 case UO_LNot: 12281 case UO_Plus: 12282 case UO_Minus: 12283 case UO_Not: 12284 case UO_Real: 12285 case UO_Imag: 12286 return CheckICE(Exp->getSubExpr(), Ctx); 12287 } 12288 llvm_unreachable("invalid unary operator class"); 12289 } 12290 case Expr::OffsetOfExprClass: { 12291 // Note that per C99, offsetof must be an ICE. And AFAIK, using 12292 // EvaluateAsRValue matches the proposed gcc behavior for cases like 12293 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 12294 // compliance: we should warn earlier for offsetof expressions with 12295 // array subscripts that aren't ICEs, and if the array subscripts 12296 // are ICEs, the value of the offsetof must be an integer constant. 12297 return CheckEvalInICE(E, Ctx); 12298 } 12299 case Expr::UnaryExprOrTypeTraitExprClass: { 12300 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 12301 if ((Exp->getKind() == UETT_SizeOf) && 12302 Exp->getTypeOfArgument()->isVariableArrayType()) 12303 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12304 return NoDiag(); 12305 } 12306 case Expr::BinaryOperatorClass: { 12307 const BinaryOperator *Exp = cast<BinaryOperator>(E); 12308 switch (Exp->getOpcode()) { 12309 case BO_PtrMemD: 12310 case BO_PtrMemI: 12311 case BO_Assign: 12312 case BO_MulAssign: 12313 case BO_DivAssign: 12314 case BO_RemAssign: 12315 case BO_AddAssign: 12316 case BO_SubAssign: 12317 case BO_ShlAssign: 12318 case BO_ShrAssign: 12319 case BO_AndAssign: 12320 case BO_XorAssign: 12321 case BO_OrAssign: 12322 // C99 6.6/3 allows assignments within unevaluated subexpressions of 12323 // constant expressions, but they can never be ICEs because an ICE cannot 12324 // contain an lvalue operand. 12325 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12326 12327 case BO_Mul: 12328 case BO_Div: 12329 case BO_Rem: 12330 case BO_Add: 12331 case BO_Sub: 12332 case BO_Shl: 12333 case BO_Shr: 12334 case BO_LT: 12335 case BO_GT: 12336 case BO_LE: 12337 case BO_GE: 12338 case BO_EQ: 12339 case BO_NE: 12340 case BO_And: 12341 case BO_Xor: 12342 case BO_Or: 12343 case BO_Comma: 12344 case BO_Cmp: { 12345 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 12346 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 12347 if (Exp->getOpcode() == BO_Div || 12348 Exp->getOpcode() == BO_Rem) { 12349 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 12350 // we don't evaluate one. 12351 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 12352 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 12353 if (REval == 0) 12354 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12355 if (REval.isSigned() && REval.isAllOnesValue()) { 12356 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 12357 if (LEval.isMinSignedValue()) 12358 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12359 } 12360 } 12361 } 12362 if (Exp->getOpcode() == BO_Comma) { 12363 if (Ctx.getLangOpts().C99) { 12364 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 12365 // if it isn't evaluated. 12366 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 12367 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 12368 } else { 12369 // In both C89 and C++, commas in ICEs are illegal. 12370 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12371 } 12372 } 12373 return Worst(LHSResult, RHSResult); 12374 } 12375 case BO_LAnd: 12376 case BO_LOr: { 12377 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 12378 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 12379 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 12380 // Rare case where the RHS has a comma "side-effect"; we need 12381 // to actually check the condition to see whether the side 12382 // with the comma is evaluated. 12383 if ((Exp->getOpcode() == BO_LAnd) != 12384 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 12385 return RHSResult; 12386 return NoDiag(); 12387 } 12388 12389 return Worst(LHSResult, RHSResult); 12390 } 12391 } 12392 llvm_unreachable("invalid binary operator kind"); 12393 } 12394 case Expr::ImplicitCastExprClass: 12395 case Expr::CStyleCastExprClass: 12396 case Expr::CXXFunctionalCastExprClass: 12397 case Expr::CXXStaticCastExprClass: 12398 case Expr::CXXReinterpretCastExprClass: 12399 case Expr::CXXConstCastExprClass: 12400 case Expr::ObjCBridgedCastExprClass: { 12401 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 12402 if (isa<ExplicitCastExpr>(E)) { 12403 if (const FloatingLiteral *FL 12404 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 12405 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 12406 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 12407 APSInt IgnoredVal(DestWidth, !DestSigned); 12408 bool Ignored; 12409 // If the value does not fit in the destination type, the behavior is 12410 // undefined, so we are not required to treat it as a constant 12411 // expression. 12412 if (FL->getValue().convertToInteger(IgnoredVal, 12413 llvm::APFloat::rmTowardZero, 12414 &Ignored) & APFloat::opInvalidOp) 12415 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12416 return NoDiag(); 12417 } 12418 } 12419 switch (cast<CastExpr>(E)->getCastKind()) { 12420 case CK_LValueToRValue: 12421 case CK_AtomicToNonAtomic: 12422 case CK_NonAtomicToAtomic: 12423 case CK_NoOp: 12424 case CK_IntegralToBoolean: 12425 case CK_IntegralCast: 12426 return CheckICE(SubExpr, Ctx); 12427 default: 12428 return ICEDiag(IK_NotICE, E->getBeginLoc()); 12429 } 12430 } 12431 case Expr::BinaryConditionalOperatorClass: { 12432 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 12433 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 12434 if (CommonResult.Kind == IK_NotICE) return CommonResult; 12435 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 12436 if (FalseResult.Kind == IK_NotICE) return FalseResult; 12437 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 12438 if (FalseResult.Kind == IK_ICEIfUnevaluated && 12439 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 12440 return FalseResult; 12441 } 12442 case Expr::ConditionalOperatorClass: { 12443 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 12444 // If the condition (ignoring parens) is a __builtin_constant_p call, 12445 // then only the true side is actually considered in an integer constant 12446 // expression, and it is fully evaluated. This is an important GNU 12447 // extension. See GCC PR38377 for discussion. 12448 if (const CallExpr *CallCE 12449 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 12450 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 12451 return CheckEvalInICE(E, Ctx); 12452 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 12453 if (CondResult.Kind == IK_NotICE) 12454 return CondResult; 12455 12456 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 12457 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 12458 12459 if (TrueResult.Kind == IK_NotICE) 12460 return TrueResult; 12461 if (FalseResult.Kind == IK_NotICE) 12462 return FalseResult; 12463 if (CondResult.Kind == IK_ICEIfUnevaluated) 12464 return CondResult; 12465 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 12466 return NoDiag(); 12467 // Rare case where the diagnostics depend on which side is evaluated 12468 // Note that if we get here, CondResult is 0, and at least one of 12469 // TrueResult and FalseResult is non-zero. 12470 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 12471 return FalseResult; 12472 return TrueResult; 12473 } 12474 case Expr::CXXDefaultArgExprClass: 12475 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 12476 case Expr::CXXDefaultInitExprClass: 12477 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 12478 case Expr::ChooseExprClass: { 12479 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 12480 } 12481 } 12482 12483 llvm_unreachable("Invalid StmtClass!"); 12484 } 12485 12486 /// Evaluate an expression as a C++11 integral constant expression. 12487 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 12488 const Expr *E, 12489 llvm::APSInt *Value, 12490 SourceLocation *Loc) { 12491 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12492 if (Loc) *Loc = E->getExprLoc(); 12493 return false; 12494 } 12495 12496 APValue Result; 12497 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 12498 return false; 12499 12500 if (!Result.isInt()) { 12501 if (Loc) *Loc = E->getExprLoc(); 12502 return false; 12503 } 12504 12505 if (Value) *Value = Result.getInt(); 12506 return true; 12507 } 12508 12509 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 12510 SourceLocation *Loc) const { 12511 assert(!isValueDependent() && 12512 "Expression evaluator can't be called on a dependent expression."); 12513 12514 if (Ctx.getLangOpts().CPlusPlus11) 12515 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 12516 12517 ICEDiag D = CheckICE(this, Ctx); 12518 if (D.Kind != IK_ICE) { 12519 if (Loc) *Loc = D.Loc; 12520 return false; 12521 } 12522 return true; 12523 } 12524 12525 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 12526 SourceLocation *Loc, bool isEvaluated) const { 12527 assert(!isValueDependent() && 12528 "Expression evaluator can't be called on a dependent expression."); 12529 12530 if (Ctx.getLangOpts().CPlusPlus11) 12531 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 12532 12533 if (!isIntegerConstantExpr(Ctx, Loc)) 12534 return false; 12535 12536 // The only possible side-effects here are due to UB discovered in the 12537 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 12538 // required to treat the expression as an ICE, so we produce the folded 12539 // value. 12540 EvalResult ExprResult; 12541 Expr::EvalStatus Status; 12542 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 12543 Info.InConstantContext = true; 12544 12545 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 12546 llvm_unreachable("ICE cannot be evaluated!"); 12547 12548 Value = ExprResult.Val.getInt(); 12549 return true; 12550 } 12551 12552 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 12553 assert(!isValueDependent() && 12554 "Expression evaluator can't be called on a dependent expression."); 12555 12556 return CheckICE(this, Ctx).Kind == IK_ICE; 12557 } 12558 12559 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 12560 SourceLocation *Loc) const { 12561 assert(!isValueDependent() && 12562 "Expression evaluator can't be called on a dependent expression."); 12563 12564 // We support this checking in C++98 mode in order to diagnose compatibility 12565 // issues. 12566 assert(Ctx.getLangOpts().CPlusPlus); 12567 12568 // Build evaluation settings. 12569 Expr::EvalStatus Status; 12570 SmallVector<PartialDiagnosticAt, 8> Diags; 12571 Status.Diag = &Diags; 12572 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 12573 12574 APValue Scratch; 12575 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch); 12576 12577 if (!Diags.empty()) { 12578 IsConstExpr = false; 12579 if (Loc) *Loc = Diags[0].first; 12580 } else if (!IsConstExpr) { 12581 // FIXME: This shouldn't happen. 12582 if (Loc) *Loc = getExprLoc(); 12583 } 12584 12585 return IsConstExpr; 12586 } 12587 12588 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 12589 const FunctionDecl *Callee, 12590 ArrayRef<const Expr*> Args, 12591 const Expr *This) const { 12592 assert(!isValueDependent() && 12593 "Expression evaluator can't be called on a dependent expression."); 12594 12595 Expr::EvalStatus Status; 12596 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 12597 Info.InConstantContext = true; 12598 12599 LValue ThisVal; 12600 const LValue *ThisPtr = nullptr; 12601 if (This) { 12602 #ifndef NDEBUG 12603 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 12604 assert(MD && "Don't provide `this` for non-methods."); 12605 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 12606 #endif 12607 if (EvaluateObjectArgument(Info, This, ThisVal)) 12608 ThisPtr = &ThisVal; 12609 if (Info.EvalStatus.HasSideEffects) 12610 return false; 12611 } 12612 12613 ArgVector ArgValues(Args.size()); 12614 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 12615 I != E; ++I) { 12616 if ((*I)->isValueDependent() || 12617 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 12618 // If evaluation fails, throw away the argument entirely. 12619 ArgValues[I - Args.begin()] = APValue(); 12620 if (Info.EvalStatus.HasSideEffects) 12621 return false; 12622 } 12623 12624 // Build fake call to Callee. 12625 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 12626 ArgValues.data()); 12627 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects; 12628 } 12629 12630 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 12631 SmallVectorImpl< 12632 PartialDiagnosticAt> &Diags) { 12633 // FIXME: It would be useful to check constexpr function templates, but at the 12634 // moment the constant expression evaluator cannot cope with the non-rigorous 12635 // ASTs which we build for dependent expressions. 12636 if (FD->isDependentContext()) 12637 return true; 12638 12639 Expr::EvalStatus Status; 12640 Status.Diag = &Diags; 12641 12642 EvalInfo Info(FD->getASTContext(), Status, 12643 EvalInfo::EM_PotentialConstantExpression); 12644 Info.InConstantContext = true; 12645 12646 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 12647 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 12648 12649 // Fabricate an arbitrary expression on the stack and pretend that it 12650 // is a temporary being used as the 'this' pointer. 12651 LValue This; 12652 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 12653 This.set({&VIE, Info.CurrentCall->Index}); 12654 12655 ArrayRef<const Expr*> Args; 12656 12657 APValue Scratch; 12658 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 12659 // Evaluate the call as a constant initializer, to allow the construction 12660 // of objects of non-literal types. 12661 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 12662 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 12663 } else { 12664 SourceLocation Loc = FD->getLocation(); 12665 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 12666 Args, FD->getBody(), Info, Scratch, nullptr); 12667 } 12668 12669 return Diags.empty(); 12670 } 12671 12672 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 12673 const FunctionDecl *FD, 12674 SmallVectorImpl< 12675 PartialDiagnosticAt> &Diags) { 12676 assert(!E->isValueDependent() && 12677 "Expression evaluator can't be called on a dependent expression."); 12678 12679 Expr::EvalStatus Status; 12680 Status.Diag = &Diags; 12681 12682 EvalInfo Info(FD->getASTContext(), Status, 12683 EvalInfo::EM_PotentialConstantExpressionUnevaluated); 12684 Info.InConstantContext = true; 12685 12686 // Fabricate a call stack frame to give the arguments a plausible cover story. 12687 ArrayRef<const Expr*> Args; 12688 ArgVector ArgValues(0); 12689 bool Success = EvaluateArgs(Args, ArgValues, Info); 12690 (void)Success; 12691 assert(Success && 12692 "Failed to set up arguments for potential constant evaluation"); 12693 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 12694 12695 APValue ResultScratch; 12696 Evaluate(ResultScratch, Info, E); 12697 return Diags.empty(); 12698 } 12699 12700 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 12701 unsigned Type) const { 12702 if (!getType()->isPointerType()) 12703 return false; 12704 12705 Expr::EvalStatus Status; 12706 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 12707 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 12708 } 12709