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 <cstring> 36 #include <functional> 37 #include "Interp/Context.h" 38 #include "Interp/Frame.h" 39 #include "Interp/State.h" 40 #include "clang/AST/APValue.h" 41 #include "clang/AST/ASTContext.h" 42 #include "clang/AST/ASTDiagnostic.h" 43 #include "clang/AST/ASTLambda.h" 44 #include "clang/AST/CXXInheritance.h" 45 #include "clang/AST/CharUnits.h" 46 #include "clang/AST/CurrentSourceLocExprScope.h" 47 #include "clang/AST/Expr.h" 48 #include "clang/AST/OSLog.h" 49 #include "clang/AST/OptionalDiagnostic.h" 50 #include "clang/AST/RecordLayout.h" 51 #include "clang/AST/StmtVisitor.h" 52 #include "clang/AST/TypeLoc.h" 53 #include "clang/Basic/Builtins.h" 54 #include "clang/Basic/FixedPoint.h" 55 #include "clang/Basic/TargetInfo.h" 56 #include "llvm/ADT/Optional.h" 57 #include "llvm/ADT/SmallBitVector.h" 58 #include "llvm/Support/SaveAndRestore.h" 59 #include "llvm/Support/raw_ostream.h" 60 61 #define DEBUG_TYPE "exprconstant" 62 63 using namespace clang; 64 using llvm::APInt; 65 using llvm::APSInt; 66 using llvm::APFloat; 67 using llvm::Optional; 68 69 namespace { 70 struct LValue; 71 class CallStackFrame; 72 class EvalInfo; 73 74 using SourceLocExprScopeGuard = 75 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 76 77 static QualType getType(APValue::LValueBase B) { 78 if (!B) return QualType(); 79 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 80 // FIXME: It's unclear where we're supposed to take the type from, and 81 // this actually matters for arrays of unknown bound. Eg: 82 // 83 // extern int arr[]; void f() { extern int arr[3]; }; 84 // constexpr int *p = &arr[1]; // valid? 85 // 86 // For now, we take the array bound from the most recent declaration. 87 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl; 88 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) { 89 QualType T = Redecl->getType(); 90 if (!T->isIncompleteArrayType()) 91 return T; 92 } 93 return D->getType(); 94 } 95 96 if (B.is<TypeInfoLValue>()) 97 return B.getTypeInfoType(); 98 99 if (B.is<DynamicAllocLValue>()) 100 return B.getDynamicAllocType(); 101 102 const Expr *Base = B.get<const Expr*>(); 103 104 // For a materialized temporary, the type of the temporary we materialized 105 // may not be the type of the expression. 106 if (const MaterializeTemporaryExpr *MTE = 107 dyn_cast<MaterializeTemporaryExpr>(Base)) { 108 SmallVector<const Expr *, 2> CommaLHSs; 109 SmallVector<SubobjectAdjustment, 2> Adjustments; 110 const Expr *Temp = MTE->GetTemporaryExpr(); 111 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, 112 Adjustments); 113 // Keep any cv-qualifiers from the reference if we generated a temporary 114 // for it directly. Otherwise use the type after adjustment. 115 if (!Adjustments.empty()) 116 return Inner->getType(); 117 } 118 119 return Base->getType(); 120 } 121 122 /// Get an LValue path entry, which is known to not be an array index, as a 123 /// field declaration. 124 static const FieldDecl *getAsField(APValue::LValuePathEntry E) { 125 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer()); 126 } 127 /// Get an LValue path entry, which is known to not be an array index, as a 128 /// base class declaration. 129 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { 130 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()); 131 } 132 /// Determine whether this LValue path entry for a base class names a virtual 133 /// base class. 134 static bool isVirtualBaseClass(APValue::LValuePathEntry E) { 135 return E.getAsBaseOrMember().getInt(); 136 } 137 138 /// Given an expression, determine the type used to store the result of 139 /// evaluating that expression. 140 static QualType getStorageType(ASTContext &Ctx, Expr *E) { 141 if (E->isRValue()) 142 return E->getType(); 143 return Ctx.getLValueReferenceType(E->getType()); 144 } 145 146 /// Given a CallExpr, try to get the alloc_size attribute. May return null. 147 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { 148 const FunctionDecl *Callee = CE->getDirectCallee(); 149 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr; 150 } 151 152 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. 153 /// This will look through a single cast. 154 /// 155 /// Returns null if we couldn't unwrap a function with alloc_size. 156 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { 157 if (!E->getType()->isPointerType()) 158 return nullptr; 159 160 E = E->IgnoreParens(); 161 // If we're doing a variable assignment from e.g. malloc(N), there will 162 // probably be a cast of some kind. In exotic cases, we might also see a 163 // top-level ExprWithCleanups. Ignore them either way. 164 if (const auto *FE = dyn_cast<FullExpr>(E)) 165 E = FE->getSubExpr()->IgnoreParens(); 166 167 if (const auto *Cast = dyn_cast<CastExpr>(E)) 168 E = Cast->getSubExpr()->IgnoreParens(); 169 170 if (const auto *CE = dyn_cast<CallExpr>(E)) 171 return getAllocSizeAttr(CE) ? CE : nullptr; 172 return nullptr; 173 } 174 175 /// Determines whether or not the given Base contains a call to a function 176 /// with the alloc_size attribute. 177 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { 178 const auto *E = Base.dyn_cast<const Expr *>(); 179 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); 180 } 181 182 /// The bound to claim that an array of unknown bound has. 183 /// The value in MostDerivedArraySize is undefined in this case. So, set it 184 /// to an arbitrary value that's likely to loudly break things if it's used. 185 static const uint64_t AssumedSizeForUnsizedArray = 186 std::numeric_limits<uint64_t>::max() / 2; 187 188 /// Determines if an LValue with the given LValueBase will have an unsized 189 /// array in its designator. 190 /// Find the path length and type of the most-derived subobject in the given 191 /// path, and find the size of the containing array, if any. 192 static unsigned 193 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, 194 ArrayRef<APValue::LValuePathEntry> Path, 195 uint64_t &ArraySize, QualType &Type, bool &IsArray, 196 bool &FirstEntryIsUnsizedArray) { 197 // This only accepts LValueBases from APValues, and APValues don't support 198 // arrays that lack size info. 199 assert(!isBaseAnAllocSizeCall(Base) && 200 "Unsized arrays shouldn't appear here"); 201 unsigned MostDerivedLength = 0; 202 Type = getType(Base); 203 204 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 205 if (Type->isArrayType()) { 206 const ArrayType *AT = Ctx.getAsArrayType(Type); 207 Type = AT->getElementType(); 208 MostDerivedLength = I + 1; 209 IsArray = true; 210 211 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) { 212 ArraySize = CAT->getSize().getZExtValue(); 213 } else { 214 assert(I == 0 && "unexpected unsized array designator"); 215 FirstEntryIsUnsizedArray = true; 216 ArraySize = AssumedSizeForUnsizedArray; 217 } 218 } else if (Type->isAnyComplexType()) { 219 const ComplexType *CT = Type->castAs<ComplexType>(); 220 Type = CT->getElementType(); 221 ArraySize = 2; 222 MostDerivedLength = I + 1; 223 IsArray = true; 224 } else if (const FieldDecl *FD = getAsField(Path[I])) { 225 Type = FD->getType(); 226 ArraySize = 0; 227 MostDerivedLength = I + 1; 228 IsArray = false; 229 } else { 230 // Path[I] describes a base class. 231 ArraySize = 0; 232 IsArray = false; 233 } 234 } 235 return MostDerivedLength; 236 } 237 238 /// A path from a glvalue to a subobject of that glvalue. 239 struct SubobjectDesignator { 240 /// True if the subobject was named in a manner not supported by C++11. Such 241 /// lvalues can still be folded, but they are not core constant expressions 242 /// and we cannot perform lvalue-to-rvalue conversions on them. 243 unsigned Invalid : 1; 244 245 /// Is this a pointer one past the end of an object? 246 unsigned IsOnePastTheEnd : 1; 247 248 /// Indicator of whether the first entry is an unsized array. 249 unsigned FirstEntryIsAnUnsizedArray : 1; 250 251 /// Indicator of whether the most-derived object is an array element. 252 unsigned MostDerivedIsArrayElement : 1; 253 254 /// The length of the path to the most-derived object of which this is a 255 /// subobject. 256 unsigned MostDerivedPathLength : 28; 257 258 /// The size of the array of which the most-derived object is an element. 259 /// This will always be 0 if the most-derived object is not an array 260 /// element. 0 is not an indicator of whether or not the most-derived object 261 /// is an array, however, because 0-length arrays are allowed. 262 /// 263 /// If the current array is an unsized array, the value of this is 264 /// undefined. 265 uint64_t MostDerivedArraySize; 266 267 /// The type of the most derived object referred to by this address. 268 QualType MostDerivedType; 269 270 typedef APValue::LValuePathEntry PathEntry; 271 272 /// The entries on the path from the glvalue to the designated subobject. 273 SmallVector<PathEntry, 8> Entries; 274 275 SubobjectDesignator() : Invalid(true) {} 276 277 explicit SubobjectDesignator(QualType T) 278 : Invalid(false), IsOnePastTheEnd(false), 279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 280 MostDerivedPathLength(0), MostDerivedArraySize(0), 281 MostDerivedType(T) {} 282 283 SubobjectDesignator(ASTContext &Ctx, const APValue &V) 284 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), 285 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), 286 MostDerivedPathLength(0), MostDerivedArraySize(0) { 287 assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); 288 if (!Invalid) { 289 IsOnePastTheEnd = V.isLValueOnePastTheEnd(); 290 ArrayRef<PathEntry> VEntries = V.getLValuePath(); 291 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); 292 if (V.getLValueBase()) { 293 bool IsArray = false; 294 bool FirstIsUnsizedArray = false; 295 MostDerivedPathLength = findMostDerivedSubobject( 296 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, 297 MostDerivedType, IsArray, FirstIsUnsizedArray); 298 MostDerivedIsArrayElement = IsArray; 299 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 300 } 301 } 302 } 303 304 void truncate(ASTContext &Ctx, APValue::LValueBase Base, 305 unsigned NewLength) { 306 if (Invalid) 307 return; 308 309 assert(Base && "cannot truncate path for null pointer"); 310 assert(NewLength <= Entries.size() && "not a truncation"); 311 312 if (NewLength == Entries.size()) 313 return; 314 Entries.resize(NewLength); 315 316 bool IsArray = false; 317 bool FirstIsUnsizedArray = false; 318 MostDerivedPathLength = findMostDerivedSubobject( 319 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, 320 FirstIsUnsizedArray); 321 MostDerivedIsArrayElement = IsArray; 322 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; 323 } 324 325 void setInvalid() { 326 Invalid = true; 327 Entries.clear(); 328 } 329 330 /// Determine whether the most derived subobject is an array without a 331 /// known bound. 332 bool isMostDerivedAnUnsizedArray() const { 333 assert(!Invalid && "Calling this makes no sense on invalid designators"); 334 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; 335 } 336 337 /// Determine what the most derived array's size is. Results in an assertion 338 /// failure if the most derived array lacks a size. 339 uint64_t getMostDerivedArraySize() const { 340 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); 341 return MostDerivedArraySize; 342 } 343 344 /// Determine whether this is a one-past-the-end pointer. 345 bool isOnePastTheEnd() const { 346 assert(!Invalid); 347 if (IsOnePastTheEnd) 348 return true; 349 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && 350 Entries[MostDerivedPathLength - 1].getAsArrayIndex() == 351 MostDerivedArraySize) 352 return true; 353 return false; 354 } 355 356 /// Get the range of valid index adjustments in the form 357 /// {maximum value that can be subtracted from this pointer, 358 /// maximum value that can be added to this pointer} 359 std::pair<uint64_t, uint64_t> validIndexAdjustments() { 360 if (Invalid || isMostDerivedAnUnsizedArray()) 361 return {0, 0}; 362 363 // [expr.add]p4: For the purposes of these operators, a pointer to a 364 // nonarray object behaves the same as a pointer to the first element of 365 // an array of length one with the type of the object as its element type. 366 bool IsArray = MostDerivedPathLength == Entries.size() && 367 MostDerivedIsArrayElement; 368 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 369 : (uint64_t)IsOnePastTheEnd; 370 uint64_t ArraySize = 371 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 372 return {ArrayIndex, ArraySize - ArrayIndex}; 373 } 374 375 /// Check that this refers to a valid subobject. 376 bool isValidSubobject() const { 377 if (Invalid) 378 return false; 379 return !isOnePastTheEnd(); 380 } 381 /// Check that this refers to a valid subobject, and if not, produce a 382 /// relevant diagnostic and set the designator as invalid. 383 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); 384 385 /// Get the type of the designated object. 386 QualType getType(ASTContext &Ctx) const { 387 assert(!Invalid && "invalid designator has no subobject type"); 388 return MostDerivedPathLength == Entries.size() 389 ? MostDerivedType 390 : Ctx.getRecordType(getAsBaseClass(Entries.back())); 391 } 392 393 /// Update this designator to refer to the first element within this array. 394 void addArrayUnchecked(const ConstantArrayType *CAT) { 395 Entries.push_back(PathEntry::ArrayIndex(0)); 396 397 // This is a most-derived object. 398 MostDerivedType = CAT->getElementType(); 399 MostDerivedIsArrayElement = true; 400 MostDerivedArraySize = CAT->getSize().getZExtValue(); 401 MostDerivedPathLength = Entries.size(); 402 } 403 /// Update this designator to refer to the first element within the array of 404 /// elements of type T. This is an array of unknown size. 405 void addUnsizedArrayUnchecked(QualType ElemTy) { 406 Entries.push_back(PathEntry::ArrayIndex(0)); 407 408 MostDerivedType = ElemTy; 409 MostDerivedIsArrayElement = true; 410 // The value in MostDerivedArraySize is undefined in this case. So, set it 411 // to an arbitrary value that's likely to loudly break things if it's 412 // used. 413 MostDerivedArraySize = AssumedSizeForUnsizedArray; 414 MostDerivedPathLength = Entries.size(); 415 } 416 /// Update this designator to refer to the given base or member of this 417 /// object. 418 void addDeclUnchecked(const Decl *D, bool Virtual = false) { 419 Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); 420 421 // If this isn't a base class, it's a new most-derived object. 422 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 423 MostDerivedType = FD->getType(); 424 MostDerivedIsArrayElement = false; 425 MostDerivedArraySize = 0; 426 MostDerivedPathLength = Entries.size(); 427 } 428 } 429 /// Update this designator to refer to the given complex component. 430 void addComplexUnchecked(QualType EltTy, bool Imag) { 431 Entries.push_back(PathEntry::ArrayIndex(Imag)); 432 433 // This is technically a most-derived object, though in practice this 434 // is unlikely to matter. 435 MostDerivedType = EltTy; 436 MostDerivedIsArrayElement = true; 437 MostDerivedArraySize = 2; 438 MostDerivedPathLength = Entries.size(); 439 } 440 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); 441 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, 442 const APSInt &N); 443 /// Add N to the address of this subobject. 444 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { 445 if (Invalid || !N) return; 446 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); 447 if (isMostDerivedAnUnsizedArray()) { 448 diagnoseUnsizedArrayPointerArithmetic(Info, E); 449 // Can't verify -- trust that the user is doing the right thing (or if 450 // not, trust that the caller will catch the bad behavior). 451 // FIXME: Should we reject if this overflows, at least? 452 Entries.back() = PathEntry::ArrayIndex( 453 Entries.back().getAsArrayIndex() + TruncatedN); 454 return; 455 } 456 457 // [expr.add]p4: For the purposes of these operators, a pointer to a 458 // nonarray object behaves the same as a pointer to the first element of 459 // an array of length one with the type of the object as its element type. 460 bool IsArray = MostDerivedPathLength == Entries.size() && 461 MostDerivedIsArrayElement; 462 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() 463 : (uint64_t)IsOnePastTheEnd; 464 uint64_t ArraySize = 465 IsArray ? getMostDerivedArraySize() : (uint64_t)1; 466 467 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { 468 // Calculate the actual index in a wide enough type, so we can include 469 // it in the note. 470 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65)); 471 (llvm::APInt&)N += ArrayIndex; 472 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); 473 diagnosePointerArithmetic(Info, E, N); 474 setInvalid(); 475 return; 476 } 477 478 ArrayIndex += TruncatedN; 479 assert(ArrayIndex <= ArraySize && 480 "bounds check succeeded for out-of-bounds index"); 481 482 if (IsArray) 483 Entries.back() = PathEntry::ArrayIndex(ArrayIndex); 484 else 485 IsOnePastTheEnd = (ArrayIndex != 0); 486 } 487 }; 488 489 /// A stack frame in the constexpr call stack. 490 class CallStackFrame : public interp::Frame { 491 public: 492 EvalInfo &Info; 493 494 /// Parent - The caller of this stack frame. 495 CallStackFrame *Caller; 496 497 /// Callee - The function which was called. 498 const FunctionDecl *Callee; 499 500 /// This - The binding for the this pointer in this call, if any. 501 const LValue *This; 502 503 /// Arguments - Parameter bindings for this function call, indexed by 504 /// parameters' function scope indices. 505 APValue *Arguments; 506 507 /// Source location information about the default argument or default 508 /// initializer expression we're evaluating, if any. 509 CurrentSourceLocExprScope CurSourceLocExprScope; 510 511 // Note that we intentionally use std::map here so that references to 512 // values are stable. 513 typedef std::pair<const void *, unsigned> MapKeyTy; 514 typedef std::map<MapKeyTy, APValue> MapTy; 515 /// Temporaries - Temporary lvalues materialized within this stack frame. 516 MapTy Temporaries; 517 518 /// CallLoc - The location of the call expression for this call. 519 SourceLocation CallLoc; 520 521 /// Index - The call index of this call. 522 unsigned Index; 523 524 /// The stack of integers for tracking version numbers for temporaries. 525 SmallVector<unsigned, 2> TempVersionStack = {1}; 526 unsigned CurTempVersion = TempVersionStack.back(); 527 528 unsigned getTempVersion() const { return TempVersionStack.back(); } 529 530 void pushTempVersion() { 531 TempVersionStack.push_back(++CurTempVersion); 532 } 533 534 void popTempVersion() { 535 TempVersionStack.pop_back(); 536 } 537 538 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact 539 // on the overall stack usage of deeply-recursing constexpr evaluations. 540 // (We should cache this map rather than recomputing it repeatedly.) 541 // But let's try this and see how it goes; we can look into caching the map 542 // as a later change. 543 544 /// LambdaCaptureFields - Mapping from captured variables/this to 545 /// corresponding data members in the closure class. 546 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 547 FieldDecl *LambdaThisCaptureField; 548 549 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 550 const FunctionDecl *Callee, const LValue *This, 551 APValue *Arguments); 552 ~CallStackFrame(); 553 554 // Return the temporary for Key whose version number is Version. 555 APValue *getTemporary(const void *Key, unsigned Version) { 556 MapKeyTy KV(Key, Version); 557 auto LB = Temporaries.lower_bound(KV); 558 if (LB != Temporaries.end() && LB->first == KV) 559 return &LB->second; 560 // Pair (Key,Version) wasn't found in the map. Check that no elements 561 // in the map have 'Key' as their key. 562 assert((LB == Temporaries.end() || LB->first.first != Key) && 563 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && 564 "Element with key 'Key' found in map"); 565 return nullptr; 566 } 567 568 // Return the current temporary for Key in the map. 569 APValue *getCurrentTemporary(const void *Key) { 570 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 571 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 572 return &std::prev(UB)->second; 573 return nullptr; 574 } 575 576 // Return the version number of the current temporary for Key. 577 unsigned getCurrentTemporaryVersion(const void *Key) const { 578 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); 579 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) 580 return std::prev(UB)->first.second; 581 return 0; 582 } 583 584 /// Allocate storage for an object of type T in this stack frame. 585 /// Populates LV with a handle to the created object. Key identifies 586 /// the temporary within the stack frame, and must not be reused without 587 /// bumping the temporary version number. 588 template<typename KeyT> 589 APValue &createTemporary(const KeyT *Key, QualType T, 590 bool IsLifetimeExtended, LValue &LV); 591 592 void describe(llvm::raw_ostream &OS) override; 593 594 Frame *getCaller() const override { return Caller; } 595 SourceLocation getCallLocation() const override { return CallLoc; } 596 const FunctionDecl *getCallee() const override { return Callee; } 597 }; 598 599 /// Temporarily override 'this'. 600 class ThisOverrideRAII { 601 public: 602 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) 603 : Frame(Frame), OldThis(Frame.This) { 604 if (Enable) 605 Frame.This = NewThis; 606 } 607 ~ThisOverrideRAII() { 608 Frame.This = OldThis; 609 } 610 private: 611 CallStackFrame &Frame; 612 const LValue *OldThis; 613 }; 614 } 615 616 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 617 const LValue &This, QualType ThisType); 618 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 619 APValue::LValueBase LVBase, APValue &Value, 620 QualType T); 621 622 namespace { 623 /// A cleanup, and a flag indicating whether it is lifetime-extended. 624 class Cleanup { 625 llvm::PointerIntPair<APValue*, 1, bool> Value; 626 APValue::LValueBase Base; 627 QualType T; 628 629 public: 630 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, 631 bool IsLifetimeExtended) 632 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {} 633 634 bool isLifetimeExtended() const { return Value.getInt(); } 635 bool endLifetime(EvalInfo &Info, bool RunDestructors) { 636 if (RunDestructors) { 637 SourceLocation Loc; 638 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) 639 Loc = VD->getLocation(); 640 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 641 Loc = E->getExprLoc(); 642 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); 643 } 644 *Value.getPointer() = APValue(); 645 return true; 646 } 647 648 bool hasSideEffect() { 649 return T.isDestructedType(); 650 } 651 }; 652 653 /// A reference to an object whose construction we are currently evaluating. 654 struct ObjectUnderConstruction { 655 APValue::LValueBase Base; 656 ArrayRef<APValue::LValuePathEntry> Path; 657 friend bool operator==(const ObjectUnderConstruction &LHS, 658 const ObjectUnderConstruction &RHS) { 659 return LHS.Base == RHS.Base && LHS.Path == RHS.Path; 660 } 661 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { 662 return llvm::hash_combine(Obj.Base, Obj.Path); 663 } 664 }; 665 enum class ConstructionPhase { 666 None, 667 Bases, 668 AfterBases, 669 Destroying, 670 DestroyingBases 671 }; 672 } 673 674 namespace llvm { 675 template<> struct DenseMapInfo<ObjectUnderConstruction> { 676 using Base = DenseMapInfo<APValue::LValueBase>; 677 static ObjectUnderConstruction getEmptyKey() { 678 return {Base::getEmptyKey(), {}}; } 679 static ObjectUnderConstruction getTombstoneKey() { 680 return {Base::getTombstoneKey(), {}}; 681 } 682 static unsigned getHashValue(const ObjectUnderConstruction &Object) { 683 return hash_value(Object); 684 } 685 static bool isEqual(const ObjectUnderConstruction &LHS, 686 const ObjectUnderConstruction &RHS) { 687 return LHS == RHS; 688 } 689 }; 690 } 691 692 namespace { 693 /// EvalInfo - This is a private struct used by the evaluator to capture 694 /// information about a subexpression as it is folded. It retains information 695 /// about the AST context, but also maintains information about the folded 696 /// expression. 697 /// 698 /// If an expression could be evaluated, it is still possible it is not a C 699 /// "integer constant expression" or constant expression. If not, this struct 700 /// captures information about how and why not. 701 /// 702 /// One bit of information passed *into* the request for constant folding 703 /// indicates whether the subexpression is "evaluated" or not according to C 704 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can 705 /// evaluate the expression regardless of what the RHS is, but C only allows 706 /// certain things in certain situations. 707 class EvalInfo : public interp::State { 708 public: 709 ASTContext &Ctx; 710 711 /// EvalStatus - Contains information about the evaluation. 712 Expr::EvalStatus &EvalStatus; 713 714 /// CurrentCall - The top of the constexpr call stack. 715 CallStackFrame *CurrentCall; 716 717 /// CallStackDepth - The number of calls in the call stack right now. 718 unsigned CallStackDepth; 719 720 /// NextCallIndex - The next call index to assign. 721 unsigned NextCallIndex; 722 723 /// StepsLeft - The remaining number of evaluation steps we're permitted 724 /// to perform. This is essentially a limit for the number of statements 725 /// we will evaluate. 726 unsigned StepsLeft; 727 728 /// Force the use of the experimental new constant interpreter, bailing out 729 /// with an error if a feature is not supported. 730 bool ForceNewConstInterp; 731 732 /// Enable the experimental new constant interpreter. 733 bool EnableNewConstInterp; 734 735 /// BottomFrame - The frame in which evaluation started. This must be 736 /// initialized after CurrentCall and CallStackDepth. 737 CallStackFrame BottomFrame; 738 739 /// A stack of values whose lifetimes end at the end of some surrounding 740 /// evaluation frame. 741 llvm::SmallVector<Cleanup, 16> CleanupStack; 742 743 /// EvaluatingDecl - This is the declaration whose initializer is being 744 /// evaluated, if any. 745 APValue::LValueBase EvaluatingDecl; 746 747 enum class EvaluatingDeclKind { 748 None, 749 /// We're evaluating the construction of EvaluatingDecl. 750 Ctor, 751 /// We're evaluating the destruction of EvaluatingDecl. 752 Dtor, 753 }; 754 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; 755 756 /// EvaluatingDeclValue - This is the value being constructed for the 757 /// declaration whose initializer is being evaluated, if any. 758 APValue *EvaluatingDeclValue; 759 760 /// Set of objects that are currently being constructed. 761 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase> 762 ObjectsUnderConstruction; 763 764 /// A dynamically-allocated heap object. 765 struct DynAlloc { 766 /// The value of this heap-allocated object. 767 APValue Value; 768 /// The allocating expression; used for diagnostics. 769 const Expr *AllocExpr = nullptr; 770 }; 771 772 struct DynAllocOrder { 773 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { 774 return L.getIndex() < R.getIndex(); 775 } 776 }; 777 778 /// Current heap allocations, along with the location where each was 779 /// allocated. We use std::map here because we need stable addresses 780 /// for the stored APValues. 781 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs; 782 783 /// The number of heap allocations performed so far in this evaluation. 784 unsigned NumHeapAllocs = 0; 785 786 struct EvaluatingConstructorRAII { 787 EvalInfo &EI; 788 ObjectUnderConstruction Object; 789 bool DidInsert; 790 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, 791 bool HasBases) 792 : EI(EI), Object(Object) { 793 DidInsert = 794 EI.ObjectsUnderConstruction 795 .insert({Object, HasBases ? ConstructionPhase::Bases 796 : ConstructionPhase::AfterBases}) 797 .second; 798 } 799 void finishedConstructingBases() { 800 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; 801 } 802 ~EvaluatingConstructorRAII() { 803 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); 804 } 805 }; 806 807 struct EvaluatingDestructorRAII { 808 EvalInfo &EI; 809 ObjectUnderConstruction Object; 810 bool DidInsert; 811 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) 812 : EI(EI), Object(Object) { 813 DidInsert = EI.ObjectsUnderConstruction 814 .insert({Object, ConstructionPhase::Destroying}) 815 .second; 816 } 817 void startedDestroyingBases() { 818 EI.ObjectsUnderConstruction[Object] = 819 ConstructionPhase::DestroyingBases; 820 } 821 ~EvaluatingDestructorRAII() { 822 if (DidInsert) 823 EI.ObjectsUnderConstruction.erase(Object); 824 } 825 }; 826 827 ConstructionPhase 828 isEvaluatingCtorDtor(APValue::LValueBase Base, 829 ArrayRef<APValue::LValuePathEntry> Path) { 830 return ObjectsUnderConstruction.lookup({Base, Path}); 831 } 832 833 /// If we're currently speculatively evaluating, the outermost call stack 834 /// depth at which we can mutate state, otherwise 0. 835 unsigned SpeculativeEvaluationDepth = 0; 836 837 /// The current array initialization index, if we're performing array 838 /// initialization. 839 uint64_t ArrayInitIndex = -1; 840 841 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further 842 /// notes attached to it will also be stored, otherwise they will not be. 843 bool HasActiveDiagnostic; 844 845 /// Have we emitted a diagnostic explaining why we couldn't constant 846 /// fold (not just why it's not strictly a constant expression)? 847 bool HasFoldFailureDiagnostic; 848 849 /// Whether or not we're in a context where the front end requires a 850 /// constant value. 851 bool InConstantContext; 852 853 /// Whether we're checking that an expression is a potential constant 854 /// expression. If so, do not fail on constructs that could become constant 855 /// later on (such as a use of an undefined global). 856 bool CheckingPotentialConstantExpression = false; 857 858 /// Whether we're checking for an expression that has undefined behavior. 859 /// If so, we will produce warnings if we encounter an operation that is 860 /// always undefined. 861 bool CheckingForUndefinedBehavior = false; 862 863 enum EvaluationMode { 864 /// Evaluate as a constant expression. Stop if we find that the expression 865 /// is not a constant expression. 866 EM_ConstantExpression, 867 868 /// Evaluate as a constant expression. Stop if we find that the expression 869 /// is not a constant expression. Some expressions can be retried in the 870 /// optimizer if we don't constant fold them here, but in an unevaluated 871 /// context we try to fold them immediately since the optimizer never 872 /// gets a chance to look at it. 873 EM_ConstantExpressionUnevaluated, 874 875 /// Fold the expression to a constant. Stop if we hit a side-effect that 876 /// we can't model. 877 EM_ConstantFold, 878 879 /// Evaluate in any way we know how. Don't worry about side-effects that 880 /// can't be modeled. 881 EM_IgnoreSideEffects, 882 } EvalMode; 883 884 /// Are we checking whether the expression is a potential constant 885 /// expression? 886 bool checkingPotentialConstantExpression() const override { 887 return CheckingPotentialConstantExpression; 888 } 889 890 /// Are we checking an expression for overflow? 891 // FIXME: We should check for any kind of undefined or suspicious behavior 892 // in such constructs, not just overflow. 893 bool checkingForUndefinedBehavior() const override { 894 return CheckingForUndefinedBehavior; 895 } 896 897 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) 898 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr), 899 CallStackDepth(0), NextCallIndex(1), 900 StepsLeft(getLangOpts().ConstexprStepLimit), 901 ForceNewConstInterp(getLangOpts().ForceNewConstInterp), 902 EnableNewConstInterp(ForceNewConstInterp || 903 getLangOpts().EnableNewConstInterp), 904 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr), 905 EvaluatingDecl((const ValueDecl *)nullptr), 906 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), 907 HasFoldFailureDiagnostic(false), InConstantContext(false), 908 EvalMode(Mode) {} 909 910 ~EvalInfo() { 911 discardCleanups(); 912 } 913 914 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, 915 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { 916 EvaluatingDecl = Base; 917 IsEvaluatingDecl = EDK; 918 EvaluatingDeclValue = &Value; 919 } 920 921 bool CheckCallLimit(SourceLocation Loc) { 922 // Don't perform any constexpr calls (other than the call we're checking) 923 // when checking a potential constant expression. 924 if (checkingPotentialConstantExpression() && CallStackDepth > 1) 925 return false; 926 if (NextCallIndex == 0) { 927 // NextCallIndex has wrapped around. 928 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); 929 return false; 930 } 931 if (CallStackDepth <= getLangOpts().ConstexprCallDepth) 932 return true; 933 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) 934 << getLangOpts().ConstexprCallDepth; 935 return false; 936 } 937 938 std::pair<CallStackFrame *, unsigned> 939 getCallFrameAndDepth(unsigned CallIndex) { 940 assert(CallIndex && "no call index in getCallFrameAndDepth"); 941 // We will eventually hit BottomFrame, which has Index 1, so Frame can't 942 // be null in this loop. 943 unsigned Depth = CallStackDepth; 944 CallStackFrame *Frame = CurrentCall; 945 while (Frame->Index > CallIndex) { 946 Frame = Frame->Caller; 947 --Depth; 948 } 949 if (Frame->Index == CallIndex) 950 return {Frame, Depth}; 951 return {nullptr, 0}; 952 } 953 954 bool nextStep(const Stmt *S) { 955 if (!StepsLeft) { 956 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); 957 return false; 958 } 959 --StepsLeft; 960 return true; 961 } 962 963 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); 964 965 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) { 966 Optional<DynAlloc*> Result; 967 auto It = HeapAllocs.find(DA); 968 if (It != HeapAllocs.end()) 969 Result = &It->second; 970 return Result; 971 } 972 973 void performLifetimeExtension() { 974 // Disable the cleanups for lifetime-extended temporaries. 975 CleanupStack.erase( 976 std::remove_if(CleanupStack.begin(), CleanupStack.end(), 977 [](Cleanup &C) { return C.isLifetimeExtended(); }), 978 CleanupStack.end()); 979 } 980 981 /// Throw away any remaining cleanups at the end of evaluation. If any 982 /// cleanups would have had a side-effect, note that as an unmodeled 983 /// side-effect and return false. Otherwise, return true. 984 bool discardCleanups() { 985 for (Cleanup &C : CleanupStack) 986 if (C.hasSideEffect()) 987 if (!noteSideEffect()) 988 return false; 989 return true; 990 } 991 992 private: 993 interp::Frame *getCurrentFrame() override { return CurrentCall; } 994 const interp::Frame *getBottomFrame() const override { return &BottomFrame; } 995 996 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } 997 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } 998 999 void setFoldFailureDiagnostic(bool Flag) override { 1000 HasFoldFailureDiagnostic = Flag; 1001 } 1002 1003 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } 1004 1005 ASTContext &getCtx() const override { return Ctx; } 1006 1007 // If we have a prior diagnostic, it will be noting that the expression 1008 // isn't a constant expression. This diagnostic is more important, 1009 // unless we require this evaluation to produce a constant expression. 1010 // 1011 // FIXME: We might want to show both diagnostics to the user in 1012 // EM_ConstantFold mode. 1013 bool hasPriorDiagnostic() override { 1014 if (!EvalStatus.Diag->empty()) { 1015 switch (EvalMode) { 1016 case EM_ConstantFold: 1017 case EM_IgnoreSideEffects: 1018 if (!HasFoldFailureDiagnostic) 1019 break; 1020 // We've already failed to fold something. Keep that diagnostic. 1021 LLVM_FALLTHROUGH; 1022 case EM_ConstantExpression: 1023 case EM_ConstantExpressionUnevaluated: 1024 setActiveDiagnostic(false); 1025 return true; 1026 } 1027 } 1028 return false; 1029 } 1030 1031 unsigned getCallStackDepth() override { return CallStackDepth; } 1032 1033 public: 1034 /// Should we continue evaluation after encountering a side-effect that we 1035 /// couldn't model? 1036 bool keepEvaluatingAfterSideEffect() { 1037 switch (EvalMode) { 1038 case EM_IgnoreSideEffects: 1039 return true; 1040 1041 case EM_ConstantExpression: 1042 case EM_ConstantExpressionUnevaluated: 1043 case EM_ConstantFold: 1044 // By default, assume any side effect might be valid in some other 1045 // evaluation of this expression from a different context. 1046 return checkingPotentialConstantExpression() || 1047 checkingForUndefinedBehavior(); 1048 } 1049 llvm_unreachable("Missed EvalMode case"); 1050 } 1051 1052 /// Note that we have had a side-effect, and determine whether we should 1053 /// keep evaluating. 1054 bool noteSideEffect() { 1055 EvalStatus.HasSideEffects = true; 1056 return keepEvaluatingAfterSideEffect(); 1057 } 1058 1059 /// Should we continue evaluation after encountering undefined behavior? 1060 bool keepEvaluatingAfterUndefinedBehavior() { 1061 switch (EvalMode) { 1062 case EM_IgnoreSideEffects: 1063 case EM_ConstantFold: 1064 return true; 1065 1066 case EM_ConstantExpression: 1067 case EM_ConstantExpressionUnevaluated: 1068 return checkingForUndefinedBehavior(); 1069 } 1070 llvm_unreachable("Missed EvalMode case"); 1071 } 1072 1073 /// Note that we hit something that was technically undefined behavior, but 1074 /// that we can evaluate past it (such as signed overflow or floating-point 1075 /// division by zero.) 1076 bool noteUndefinedBehavior() override { 1077 EvalStatus.HasUndefinedBehavior = true; 1078 return keepEvaluatingAfterUndefinedBehavior(); 1079 } 1080 1081 /// Should we continue evaluation as much as possible after encountering a 1082 /// construct which can't be reduced to a value? 1083 bool keepEvaluatingAfterFailure() const override { 1084 if (!StepsLeft) 1085 return false; 1086 1087 switch (EvalMode) { 1088 case EM_ConstantExpression: 1089 case EM_ConstantExpressionUnevaluated: 1090 case EM_ConstantFold: 1091 case EM_IgnoreSideEffects: 1092 return checkingPotentialConstantExpression() || 1093 checkingForUndefinedBehavior(); 1094 } 1095 llvm_unreachable("Missed EvalMode case"); 1096 } 1097 1098 /// Notes that we failed to evaluate an expression that other expressions 1099 /// directly depend on, and determine if we should keep evaluating. This 1100 /// should only be called if we actually intend to keep evaluating. 1101 /// 1102 /// Call noteSideEffect() instead if we may be able to ignore the value that 1103 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: 1104 /// 1105 /// (Foo(), 1) // use noteSideEffect 1106 /// (Foo() || true) // use noteSideEffect 1107 /// Foo() + 1 // use noteFailure 1108 LLVM_NODISCARD bool noteFailure() { 1109 // Failure when evaluating some expression often means there is some 1110 // subexpression whose evaluation was skipped. Therefore, (because we 1111 // don't track whether we skipped an expression when unwinding after an 1112 // evaluation failure) every evaluation failure that bubbles up from a 1113 // subexpression implies that a side-effect has potentially happened. We 1114 // skip setting the HasSideEffects flag to true until we decide to 1115 // continue evaluating after that point, which happens here. 1116 bool KeepGoing = keepEvaluatingAfterFailure(); 1117 EvalStatus.HasSideEffects |= KeepGoing; 1118 return KeepGoing; 1119 } 1120 1121 class ArrayInitLoopIndex { 1122 EvalInfo &Info; 1123 uint64_t OuterIndex; 1124 1125 public: 1126 ArrayInitLoopIndex(EvalInfo &Info) 1127 : Info(Info), OuterIndex(Info.ArrayInitIndex) { 1128 Info.ArrayInitIndex = 0; 1129 } 1130 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } 1131 1132 operator uint64_t&() { return Info.ArrayInitIndex; } 1133 }; 1134 }; 1135 1136 /// Object used to treat all foldable expressions as constant expressions. 1137 struct FoldConstant { 1138 EvalInfo &Info; 1139 bool Enabled; 1140 bool HadNoPriorDiags; 1141 EvalInfo::EvaluationMode OldMode; 1142 1143 explicit FoldConstant(EvalInfo &Info, bool Enabled) 1144 : Info(Info), 1145 Enabled(Enabled), 1146 HadNoPriorDiags(Info.EvalStatus.Diag && 1147 Info.EvalStatus.Diag->empty() && 1148 !Info.EvalStatus.HasSideEffects), 1149 OldMode(Info.EvalMode) { 1150 if (Enabled) 1151 Info.EvalMode = EvalInfo::EM_ConstantFold; 1152 } 1153 void keepDiagnostics() { Enabled = false; } 1154 ~FoldConstant() { 1155 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && 1156 !Info.EvalStatus.HasSideEffects) 1157 Info.EvalStatus.Diag->clear(); 1158 Info.EvalMode = OldMode; 1159 } 1160 }; 1161 1162 /// RAII object used to set the current evaluation mode to ignore 1163 /// side-effects. 1164 struct IgnoreSideEffectsRAII { 1165 EvalInfo &Info; 1166 EvalInfo::EvaluationMode OldMode; 1167 explicit IgnoreSideEffectsRAII(EvalInfo &Info) 1168 : Info(Info), OldMode(Info.EvalMode) { 1169 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; 1170 } 1171 1172 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } 1173 }; 1174 1175 /// RAII object used to optionally suppress diagnostics and side-effects from 1176 /// a speculative evaluation. 1177 class SpeculativeEvaluationRAII { 1178 EvalInfo *Info = nullptr; 1179 Expr::EvalStatus OldStatus; 1180 unsigned OldSpeculativeEvaluationDepth; 1181 1182 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { 1183 Info = Other.Info; 1184 OldStatus = Other.OldStatus; 1185 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; 1186 Other.Info = nullptr; 1187 } 1188 1189 void maybeRestoreState() { 1190 if (!Info) 1191 return; 1192 1193 Info->EvalStatus = OldStatus; 1194 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; 1195 } 1196 1197 public: 1198 SpeculativeEvaluationRAII() = default; 1199 1200 SpeculativeEvaluationRAII( 1201 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr) 1202 : Info(&Info), OldStatus(Info.EvalStatus), 1203 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { 1204 Info.EvalStatus.Diag = NewDiag; 1205 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; 1206 } 1207 1208 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; 1209 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { 1210 moveFromAndCancel(std::move(Other)); 1211 } 1212 1213 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { 1214 maybeRestoreState(); 1215 moveFromAndCancel(std::move(Other)); 1216 return *this; 1217 } 1218 1219 ~SpeculativeEvaluationRAII() { maybeRestoreState(); } 1220 }; 1221 1222 /// RAII object wrapping a full-expression or block scope, and handling 1223 /// the ending of the lifetime of temporaries created within it. 1224 template<bool IsFullExpression> 1225 class ScopeRAII { 1226 EvalInfo &Info; 1227 unsigned OldStackSize; 1228 public: 1229 ScopeRAII(EvalInfo &Info) 1230 : Info(Info), OldStackSize(Info.CleanupStack.size()) { 1231 // Push a new temporary version. This is needed to distinguish between 1232 // temporaries created in different iterations of a loop. 1233 Info.CurrentCall->pushTempVersion(); 1234 } 1235 bool destroy(bool RunDestructors = true) { 1236 bool OK = cleanup(Info, RunDestructors, OldStackSize); 1237 OldStackSize = -1U; 1238 return OK; 1239 } 1240 ~ScopeRAII() { 1241 if (OldStackSize != -1U) 1242 destroy(false); 1243 // Body moved to a static method to encourage the compiler to inline away 1244 // instances of this class. 1245 Info.CurrentCall->popTempVersion(); 1246 } 1247 private: 1248 static bool cleanup(EvalInfo &Info, bool RunDestructors, 1249 unsigned OldStackSize) { 1250 assert(OldStackSize <= Info.CleanupStack.size() && 1251 "running cleanups out of order?"); 1252 1253 // Run all cleanups for a block scope, and non-lifetime-extended cleanups 1254 // for a full-expression scope. 1255 bool Success = true; 1256 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { 1257 if (!(IsFullExpression && 1258 Info.CleanupStack[I - 1].isLifetimeExtended())) { 1259 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { 1260 Success = false; 1261 break; 1262 } 1263 } 1264 } 1265 1266 // Compact lifetime-extended cleanups. 1267 auto NewEnd = Info.CleanupStack.begin() + OldStackSize; 1268 if (IsFullExpression) 1269 NewEnd = 1270 std::remove_if(NewEnd, Info.CleanupStack.end(), 1271 [](Cleanup &C) { return !C.isLifetimeExtended(); }); 1272 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); 1273 return Success; 1274 } 1275 }; 1276 typedef ScopeRAII<false> BlockScopeRAII; 1277 typedef ScopeRAII<true> FullExpressionRAII; 1278 } 1279 1280 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, 1281 CheckSubobjectKind CSK) { 1282 if (Invalid) 1283 return false; 1284 if (isOnePastTheEnd()) { 1285 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) 1286 << CSK; 1287 setInvalid(); 1288 return false; 1289 } 1290 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there 1291 // must actually be at least one array element; even a VLA cannot have a 1292 // bound of zero. And if our index is nonzero, we already had a CCEDiag. 1293 return true; 1294 } 1295 1296 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, 1297 const Expr *E) { 1298 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); 1299 // Do not set the designator as invalid: we can represent this situation, 1300 // and correct handling of __builtin_object_size requires us to do so. 1301 } 1302 1303 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, 1304 const Expr *E, 1305 const APSInt &N) { 1306 // If we're complaining, we must be able to statically determine the size of 1307 // the most derived array. 1308 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) 1309 Info.CCEDiag(E, diag::note_constexpr_array_index) 1310 << N << /*array*/ 0 1311 << static_cast<unsigned>(getMostDerivedArraySize()); 1312 else 1313 Info.CCEDiag(E, diag::note_constexpr_array_index) 1314 << N << /*non-array*/ 1; 1315 setInvalid(); 1316 } 1317 1318 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, 1319 const FunctionDecl *Callee, const LValue *This, 1320 APValue *Arguments) 1321 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), 1322 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) { 1323 Info.CurrentCall = this; 1324 ++Info.CallStackDepth; 1325 } 1326 1327 CallStackFrame::~CallStackFrame() { 1328 assert(Info.CurrentCall == this && "calls retired out of order"); 1329 --Info.CallStackDepth; 1330 Info.CurrentCall = Caller; 1331 } 1332 1333 static bool isRead(AccessKinds AK) { 1334 return AK == AK_Read || AK == AK_ReadObjectRepresentation; 1335 } 1336 1337 static bool isModification(AccessKinds AK) { 1338 switch (AK) { 1339 case AK_Read: 1340 case AK_ReadObjectRepresentation: 1341 case AK_MemberCall: 1342 case AK_DynamicCast: 1343 case AK_TypeId: 1344 return false; 1345 case AK_Assign: 1346 case AK_Increment: 1347 case AK_Decrement: 1348 case AK_Destroy: 1349 return true; 1350 } 1351 llvm_unreachable("unknown access kind"); 1352 } 1353 1354 static bool isAnyAccess(AccessKinds AK) { 1355 return isRead(AK) || isModification(AK); 1356 } 1357 1358 /// Is this an access per the C++ definition? 1359 static bool isFormalAccess(AccessKinds AK) { 1360 return isAnyAccess(AK) && AK != AK_Destroy; 1361 } 1362 1363 namespace { 1364 struct ComplexValue { 1365 private: 1366 bool IsInt; 1367 1368 public: 1369 APSInt IntReal, IntImag; 1370 APFloat FloatReal, FloatImag; 1371 1372 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} 1373 1374 void makeComplexFloat() { IsInt = false; } 1375 bool isComplexFloat() const { return !IsInt; } 1376 APFloat &getComplexFloatReal() { return FloatReal; } 1377 APFloat &getComplexFloatImag() { return FloatImag; } 1378 1379 void makeComplexInt() { IsInt = true; } 1380 bool isComplexInt() const { return IsInt; } 1381 APSInt &getComplexIntReal() { return IntReal; } 1382 APSInt &getComplexIntImag() { return IntImag; } 1383 1384 void moveInto(APValue &v) const { 1385 if (isComplexFloat()) 1386 v = APValue(FloatReal, FloatImag); 1387 else 1388 v = APValue(IntReal, IntImag); 1389 } 1390 void setFrom(const APValue &v) { 1391 assert(v.isComplexFloat() || v.isComplexInt()); 1392 if (v.isComplexFloat()) { 1393 makeComplexFloat(); 1394 FloatReal = v.getComplexFloatReal(); 1395 FloatImag = v.getComplexFloatImag(); 1396 } else { 1397 makeComplexInt(); 1398 IntReal = v.getComplexIntReal(); 1399 IntImag = v.getComplexIntImag(); 1400 } 1401 } 1402 }; 1403 1404 struct LValue { 1405 APValue::LValueBase Base; 1406 CharUnits Offset; 1407 SubobjectDesignator Designator; 1408 bool IsNullPtr : 1; 1409 bool InvalidBase : 1; 1410 1411 const APValue::LValueBase getLValueBase() const { return Base; } 1412 CharUnits &getLValueOffset() { return Offset; } 1413 const CharUnits &getLValueOffset() const { return Offset; } 1414 SubobjectDesignator &getLValueDesignator() { return Designator; } 1415 const SubobjectDesignator &getLValueDesignator() const { return Designator;} 1416 bool isNullPointer() const { return IsNullPtr;} 1417 1418 unsigned getLValueCallIndex() const { return Base.getCallIndex(); } 1419 unsigned getLValueVersion() const { return Base.getVersion(); } 1420 1421 void moveInto(APValue &V) const { 1422 if (Designator.Invalid) 1423 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); 1424 else { 1425 assert(!InvalidBase && "APValues can't handle invalid LValue bases"); 1426 V = APValue(Base, Offset, Designator.Entries, 1427 Designator.IsOnePastTheEnd, IsNullPtr); 1428 } 1429 } 1430 void setFrom(ASTContext &Ctx, const APValue &V) { 1431 assert(V.isLValue() && "Setting LValue from a non-LValue?"); 1432 Base = V.getLValueBase(); 1433 Offset = V.getLValueOffset(); 1434 InvalidBase = false; 1435 Designator = SubobjectDesignator(Ctx, V); 1436 IsNullPtr = V.isNullPointer(); 1437 } 1438 1439 void set(APValue::LValueBase B, bool BInvalid = false) { 1440 #ifndef NDEBUG 1441 // We only allow a few types of invalid bases. Enforce that here. 1442 if (BInvalid) { 1443 const auto *E = B.get<const Expr *>(); 1444 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) && 1445 "Unexpected type of invalid base"); 1446 } 1447 #endif 1448 1449 Base = B; 1450 Offset = CharUnits::fromQuantity(0); 1451 InvalidBase = BInvalid; 1452 Designator = SubobjectDesignator(getType(B)); 1453 IsNullPtr = false; 1454 } 1455 1456 void setNull(QualType PointerTy, uint64_t TargetVal) { 1457 Base = (Expr *)nullptr; 1458 Offset = CharUnits::fromQuantity(TargetVal); 1459 InvalidBase = false; 1460 Designator = SubobjectDesignator(PointerTy->getPointeeType()); 1461 IsNullPtr = true; 1462 } 1463 1464 void setInvalid(APValue::LValueBase B, unsigned I = 0) { 1465 set(B, true); 1466 } 1467 1468 private: 1469 // Check that this LValue is not based on a null pointer. If it is, produce 1470 // a diagnostic and mark the designator as invalid. 1471 template <typename GenDiagType> 1472 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { 1473 if (Designator.Invalid) 1474 return false; 1475 if (IsNullPtr) { 1476 GenDiag(); 1477 Designator.setInvalid(); 1478 return false; 1479 } 1480 return true; 1481 } 1482 1483 public: 1484 bool checkNullPointer(EvalInfo &Info, const Expr *E, 1485 CheckSubobjectKind CSK) { 1486 return checkNullPointerDiagnosingWith([&Info, E, CSK] { 1487 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; 1488 }); 1489 } 1490 1491 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, 1492 AccessKinds AK) { 1493 return checkNullPointerDiagnosingWith([&Info, E, AK] { 1494 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 1495 }); 1496 } 1497 1498 // Check this LValue refers to an object. If not, set the designator to be 1499 // invalid and emit a diagnostic. 1500 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { 1501 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && 1502 Designator.checkSubobject(Info, E, CSK); 1503 } 1504 1505 void addDecl(EvalInfo &Info, const Expr *E, 1506 const Decl *D, bool Virtual = false) { 1507 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base)) 1508 Designator.addDeclUnchecked(D, Virtual); 1509 } 1510 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { 1511 if (!Designator.Entries.empty()) { 1512 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); 1513 Designator.setInvalid(); 1514 return; 1515 } 1516 if (checkSubobject(Info, E, CSK_ArrayToPointer)) { 1517 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); 1518 Designator.FirstEntryIsAnUnsizedArray = true; 1519 Designator.addUnsizedArrayUnchecked(ElemTy); 1520 } 1521 } 1522 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { 1523 if (checkSubobject(Info, E, CSK_ArrayToPointer)) 1524 Designator.addArrayUnchecked(CAT); 1525 } 1526 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { 1527 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) 1528 Designator.addComplexUnchecked(EltTy, Imag); 1529 } 1530 void clearIsNullPointer() { 1531 IsNullPtr = false; 1532 } 1533 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, 1534 const APSInt &Index, CharUnits ElementSize) { 1535 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, 1536 // but we're not required to diagnose it and it's valid in C++.) 1537 if (!Index) 1538 return; 1539 1540 // Compute the new offset in the appropriate width, wrapping at 64 bits. 1541 // FIXME: When compiling for a 32-bit target, we should use 32-bit 1542 // offsets. 1543 uint64_t Offset64 = Offset.getQuantity(); 1544 uint64_t ElemSize64 = ElementSize.getQuantity(); 1545 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 1546 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); 1547 1548 if (checkNullPointer(Info, E, CSK_ArrayIndex)) 1549 Designator.adjustIndex(Info, E, Index); 1550 clearIsNullPointer(); 1551 } 1552 void adjustOffset(CharUnits N) { 1553 Offset += N; 1554 if (N.getQuantity()) 1555 clearIsNullPointer(); 1556 } 1557 }; 1558 1559 struct MemberPtr { 1560 MemberPtr() {} 1561 explicit MemberPtr(const ValueDecl *Decl) : 1562 DeclAndIsDerivedMember(Decl, false), Path() {} 1563 1564 /// The member or (direct or indirect) field referred to by this member 1565 /// pointer, or 0 if this is a null member pointer. 1566 const ValueDecl *getDecl() const { 1567 return DeclAndIsDerivedMember.getPointer(); 1568 } 1569 /// Is this actually a member of some type derived from the relevant class? 1570 bool isDerivedMember() const { 1571 return DeclAndIsDerivedMember.getInt(); 1572 } 1573 /// Get the class which the declaration actually lives in. 1574 const CXXRecordDecl *getContainingRecord() const { 1575 return cast<CXXRecordDecl>( 1576 DeclAndIsDerivedMember.getPointer()->getDeclContext()); 1577 } 1578 1579 void moveInto(APValue &V) const { 1580 V = APValue(getDecl(), isDerivedMember(), Path); 1581 } 1582 void setFrom(const APValue &V) { 1583 assert(V.isMemberPointer()); 1584 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); 1585 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); 1586 Path.clear(); 1587 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath(); 1588 Path.insert(Path.end(), P.begin(), P.end()); 1589 } 1590 1591 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating 1592 /// whether the member is a member of some class derived from the class type 1593 /// of the member pointer. 1594 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember; 1595 /// Path - The path of base/derived classes from the member declaration's 1596 /// class (exclusive) to the class type of the member pointer (inclusive). 1597 SmallVector<const CXXRecordDecl*, 4> Path; 1598 1599 /// Perform a cast towards the class of the Decl (either up or down the 1600 /// hierarchy). 1601 bool castBack(const CXXRecordDecl *Class) { 1602 assert(!Path.empty()); 1603 const CXXRecordDecl *Expected; 1604 if (Path.size() >= 2) 1605 Expected = Path[Path.size() - 2]; 1606 else 1607 Expected = getContainingRecord(); 1608 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { 1609 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), 1610 // if B does not contain the original member and is not a base or 1611 // derived class of the class containing the original member, the result 1612 // of the cast is undefined. 1613 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to 1614 // (D::*). We consider that to be a language defect. 1615 return false; 1616 } 1617 Path.pop_back(); 1618 return true; 1619 } 1620 /// Perform a base-to-derived member pointer cast. 1621 bool castToDerived(const CXXRecordDecl *Derived) { 1622 if (!getDecl()) 1623 return true; 1624 if (!isDerivedMember()) { 1625 Path.push_back(Derived); 1626 return true; 1627 } 1628 if (!castBack(Derived)) 1629 return false; 1630 if (Path.empty()) 1631 DeclAndIsDerivedMember.setInt(false); 1632 return true; 1633 } 1634 /// Perform a derived-to-base member pointer cast. 1635 bool castToBase(const CXXRecordDecl *Base) { 1636 if (!getDecl()) 1637 return true; 1638 if (Path.empty()) 1639 DeclAndIsDerivedMember.setInt(true); 1640 if (isDerivedMember()) { 1641 Path.push_back(Base); 1642 return true; 1643 } 1644 return castBack(Base); 1645 } 1646 }; 1647 1648 /// Compare two member pointers, which are assumed to be of the same type. 1649 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { 1650 if (!LHS.getDecl() || !RHS.getDecl()) 1651 return !LHS.getDecl() && !RHS.getDecl(); 1652 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) 1653 return false; 1654 return LHS.Path == RHS.Path; 1655 } 1656 } 1657 1658 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); 1659 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, 1660 const LValue &This, const Expr *E, 1661 bool AllowNonLiteralTypes = false); 1662 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 1663 bool InvalidBaseOK = false); 1664 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, 1665 bool InvalidBaseOK = false); 1666 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 1667 EvalInfo &Info); 1668 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); 1669 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); 1670 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 1671 EvalInfo &Info); 1672 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); 1673 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); 1674 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 1675 EvalInfo &Info); 1676 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); 1677 1678 /// Evaluate an integer or fixed point expression into an APResult. 1679 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 1680 EvalInfo &Info); 1681 1682 /// Evaluate only a fixed point expression into an APResult. 1683 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 1684 EvalInfo &Info); 1685 1686 //===----------------------------------------------------------------------===// 1687 // Misc utilities 1688 //===----------------------------------------------------------------------===// 1689 1690 /// Negate an APSInt in place, converting it to a signed form if necessary, and 1691 /// preserving its value (by extending by up to one bit as needed). 1692 static void negateAsSigned(APSInt &Int) { 1693 if (Int.isUnsigned() || Int.isMinSignedValue()) { 1694 Int = Int.extend(Int.getBitWidth() + 1); 1695 Int.setIsSigned(true); 1696 } 1697 Int = -Int; 1698 } 1699 1700 template<typename KeyT> 1701 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, 1702 bool IsLifetimeExtended, LValue &LV) { 1703 unsigned Version = getTempVersion(); 1704 APValue::LValueBase Base(Key, Index, Version); 1705 LV.set(Base); 1706 APValue &Result = Temporaries[MapKeyTy(Key, Version)]; 1707 assert(Result.isAbsent() && "temporary created multiple times"); 1708 1709 // If we're creating a temporary immediately in the operand of a speculative 1710 // evaluation, don't register a cleanup to be run outside the speculative 1711 // evaluation context, since we won't actually be able to initialize this 1712 // object. 1713 if (Index <= Info.SpeculativeEvaluationDepth) { 1714 if (T.isDestructedType()) 1715 Info.noteSideEffect(); 1716 } else { 1717 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended)); 1718 } 1719 return Result; 1720 } 1721 1722 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { 1723 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { 1724 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); 1725 return nullptr; 1726 } 1727 1728 DynamicAllocLValue DA(NumHeapAllocs++); 1729 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T)); 1730 auto Result = HeapAllocs.emplace(std::piecewise_construct, 1731 std::forward_as_tuple(DA), std::tuple<>()); 1732 assert(Result.second && "reused a heap alloc index?"); 1733 Result.first->second.AllocExpr = E; 1734 return &Result.first->second.Value; 1735 } 1736 1737 /// Produce a string describing the given constexpr call. 1738 void CallStackFrame::describe(raw_ostream &Out) { 1739 unsigned ArgIndex = 0; 1740 bool IsMemberCall = isa<CXXMethodDecl>(Callee) && 1741 !isa<CXXConstructorDecl>(Callee) && 1742 cast<CXXMethodDecl>(Callee)->isInstance(); 1743 1744 if (!IsMemberCall) 1745 Out << *Callee << '('; 1746 1747 if (This && IsMemberCall) { 1748 APValue Val; 1749 This->moveInto(Val); 1750 Val.printPretty(Out, Info.Ctx, 1751 This->Designator.MostDerivedType); 1752 // FIXME: Add parens around Val if needed. 1753 Out << "->" << *Callee << '('; 1754 IsMemberCall = false; 1755 } 1756 1757 for (FunctionDecl::param_const_iterator I = Callee->param_begin(), 1758 E = Callee->param_end(); I != E; ++I, ++ArgIndex) { 1759 if (ArgIndex > (unsigned)IsMemberCall) 1760 Out << ", "; 1761 1762 const ParmVarDecl *Param = *I; 1763 const APValue &Arg = Arguments[ArgIndex]; 1764 Arg.printPretty(Out, Info.Ctx, Param->getType()); 1765 1766 if (ArgIndex == 0 && IsMemberCall) 1767 Out << "->" << *Callee << '('; 1768 } 1769 1770 Out << ')'; 1771 } 1772 1773 /// Evaluate an expression to see if it had side-effects, and discard its 1774 /// result. 1775 /// \return \c true if the caller should keep evaluating. 1776 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { 1777 APValue Scratch; 1778 if (!Evaluate(Scratch, Info, E)) 1779 // We don't need the value, but we might have skipped a side effect here. 1780 return Info.noteSideEffect(); 1781 return true; 1782 } 1783 1784 /// Should this call expression be treated as a string literal? 1785 static bool IsStringLiteralCall(const CallExpr *E) { 1786 unsigned Builtin = E->getBuiltinCallee(); 1787 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 1788 Builtin == Builtin::BI__builtin___NSStringMakeConstantString); 1789 } 1790 1791 static bool IsGlobalLValue(APValue::LValueBase B) { 1792 // C++11 [expr.const]p3 An address constant expression is a prvalue core 1793 // constant expression of pointer type that evaluates to... 1794 1795 // ... a null pointer value, or a prvalue core constant expression of type 1796 // std::nullptr_t. 1797 if (!B) return true; 1798 1799 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 1800 // ... the address of an object with static storage duration, 1801 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1802 return VD->hasGlobalStorage(); 1803 // ... the address of a function, 1804 return isa<FunctionDecl>(D); 1805 } 1806 1807 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>()) 1808 return true; 1809 1810 const Expr *E = B.get<const Expr*>(); 1811 switch (E->getStmtClass()) { 1812 default: 1813 return false; 1814 case Expr::CompoundLiteralExprClass: { 1815 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1816 return CLE->isFileScope() && CLE->isLValue(); 1817 } 1818 case Expr::MaterializeTemporaryExprClass: 1819 // A materialized temporary might have been lifetime-extended to static 1820 // storage duration. 1821 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static; 1822 // A string literal has static storage duration. 1823 case Expr::StringLiteralClass: 1824 case Expr::PredefinedExprClass: 1825 case Expr::ObjCStringLiteralClass: 1826 case Expr::ObjCEncodeExprClass: 1827 case Expr::CXXUuidofExprClass: 1828 return true; 1829 case Expr::ObjCBoxedExprClass: 1830 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer(); 1831 case Expr::CallExprClass: 1832 return IsStringLiteralCall(cast<CallExpr>(E)); 1833 // For GCC compatibility, &&label has static storage duration. 1834 case Expr::AddrLabelExprClass: 1835 return true; 1836 // A Block literal expression may be used as the initialization value for 1837 // Block variables at global or local static scope. 1838 case Expr::BlockExprClass: 1839 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures(); 1840 case Expr::ImplicitValueInitExprClass: 1841 // FIXME: 1842 // We can never form an lvalue with an implicit value initialization as its 1843 // base through expression evaluation, so these only appear in one case: the 1844 // implicit variable declaration we invent when checking whether a constexpr 1845 // constructor can produce a constant expression. We must assume that such 1846 // an expression might be a global lvalue. 1847 return true; 1848 } 1849 } 1850 1851 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { 1852 return LVal.Base.dyn_cast<const ValueDecl*>(); 1853 } 1854 1855 static bool IsLiteralLValue(const LValue &Value) { 1856 if (Value.getLValueCallIndex()) 1857 return false; 1858 const Expr *E = Value.Base.dyn_cast<const Expr*>(); 1859 return E && !isa<MaterializeTemporaryExpr>(E); 1860 } 1861 1862 static bool IsWeakLValue(const LValue &Value) { 1863 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1864 return Decl && Decl->isWeak(); 1865 } 1866 1867 static bool isZeroSized(const LValue &Value) { 1868 const ValueDecl *Decl = GetLValueBaseDecl(Value); 1869 if (Decl && isa<VarDecl>(Decl)) { 1870 QualType Ty = Decl->getType(); 1871 if (Ty->isArrayType()) 1872 return Ty->isIncompleteType() || 1873 Decl->getASTContext().getTypeSize(Ty) == 0; 1874 } 1875 return false; 1876 } 1877 1878 static bool HasSameBase(const LValue &A, const LValue &B) { 1879 if (!A.getLValueBase()) 1880 return !B.getLValueBase(); 1881 if (!B.getLValueBase()) 1882 return false; 1883 1884 if (A.getLValueBase().getOpaqueValue() != 1885 B.getLValueBase().getOpaqueValue()) { 1886 const Decl *ADecl = GetLValueBaseDecl(A); 1887 if (!ADecl) 1888 return false; 1889 const Decl *BDecl = GetLValueBaseDecl(B); 1890 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl()) 1891 return false; 1892 } 1893 1894 return IsGlobalLValue(A.getLValueBase()) || 1895 (A.getLValueCallIndex() == B.getLValueCallIndex() && 1896 A.getLValueVersion() == B.getLValueVersion()); 1897 } 1898 1899 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { 1900 assert(Base && "no location for a null lvalue"); 1901 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1902 if (VD) 1903 Info.Note(VD->getLocation(), diag::note_declared_at); 1904 else if (const Expr *E = Base.dyn_cast<const Expr*>()) 1905 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); 1906 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) { 1907 // FIXME: Produce a note for dangling pointers too. 1908 if (Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA)) 1909 Info.Note((*Alloc)->AllocExpr->getExprLoc(), 1910 diag::note_constexpr_dynamic_alloc_here); 1911 } 1912 // We have no information to show for a typeid(T) object. 1913 } 1914 1915 enum class CheckEvaluationResultKind { 1916 ConstantExpression, 1917 FullyInitialized, 1918 }; 1919 1920 /// Materialized temporaries that we've already checked to determine if they're 1921 /// initializsed by a constant expression. 1922 using CheckedTemporaries = 1923 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>; 1924 1925 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 1926 EvalInfo &Info, SourceLocation DiagLoc, 1927 QualType Type, const APValue &Value, 1928 Expr::ConstExprUsage Usage, 1929 SourceLocation SubobjectLoc, 1930 CheckedTemporaries &CheckedTemps); 1931 1932 /// Check that this reference or pointer core constant expression is a valid 1933 /// value for an address or reference constant expression. Return true if we 1934 /// can fold this expression, whether or not it's a constant expression. 1935 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, 1936 QualType Type, const LValue &LVal, 1937 Expr::ConstExprUsage Usage, 1938 CheckedTemporaries &CheckedTemps) { 1939 bool IsReferenceType = Type->isReferenceType(); 1940 1941 APValue::LValueBase Base = LVal.getLValueBase(); 1942 const SubobjectDesignator &Designator = LVal.getLValueDesignator(); 1943 1944 // Check that the object is a global. Note that the fake 'this' object we 1945 // manufacture when checking potential constant expressions is conservatively 1946 // assumed to be global here. 1947 if (!IsGlobalLValue(Base)) { 1948 if (Info.getLangOpts().CPlusPlus11) { 1949 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 1950 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) 1951 << IsReferenceType << !Designator.Entries.empty() 1952 << !!VD << VD; 1953 NoteLValueLocation(Info, Base); 1954 } else { 1955 Info.FFDiag(Loc); 1956 } 1957 // Don't allow references to temporaries to escape. 1958 return false; 1959 } 1960 assert((Info.checkingPotentialConstantExpression() || 1961 LVal.getLValueCallIndex() == 0) && 1962 "have call index for global lvalue"); 1963 1964 if (Base.is<DynamicAllocLValue>()) { 1965 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc) 1966 << IsReferenceType << !Designator.Entries.empty(); 1967 NoteLValueLocation(Info, Base); 1968 return false; 1969 } 1970 1971 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) { 1972 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) { 1973 // Check if this is a thread-local variable. 1974 if (Var->getTLSKind()) 1975 // FIXME: Diagnostic! 1976 return false; 1977 1978 // A dllimport variable never acts like a constant. 1979 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>()) 1980 // FIXME: Diagnostic! 1981 return false; 1982 } 1983 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) { 1984 // __declspec(dllimport) must be handled very carefully: 1985 // We must never initialize an expression with the thunk in C++. 1986 // Doing otherwise would allow the same id-expression to yield 1987 // different addresses for the same function in different translation 1988 // units. However, this means that we must dynamically initialize the 1989 // expression with the contents of the import address table at runtime. 1990 // 1991 // The C language has no notion of ODR; furthermore, it has no notion of 1992 // dynamic initialization. This means that we are permitted to 1993 // perform initialization with the address of the thunk. 1994 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen && 1995 FD->hasAttr<DLLImportAttr>()) 1996 // FIXME: Diagnostic! 1997 return false; 1998 } 1999 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>( 2000 Base.dyn_cast<const Expr *>())) { 2001 if (CheckedTemps.insert(MTE).second) { 2002 QualType TempType = getType(Base); 2003 if (TempType.isDestructedType()) { 2004 Info.FFDiag(MTE->getExprLoc(), 2005 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor) 2006 << TempType; 2007 return false; 2008 } 2009 2010 APValue *V = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 2011 assert(V && "evasluation result refers to uninitialised temporary"); 2012 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2013 Info, MTE->getExprLoc(), TempType, *V, 2014 Usage, SourceLocation(), CheckedTemps)) 2015 return false; 2016 } 2017 } 2018 2019 // Allow address constant expressions to be past-the-end pointers. This is 2020 // an extension: the standard requires them to point to an object. 2021 if (!IsReferenceType) 2022 return true; 2023 2024 // A reference constant expression must refer to an object. 2025 if (!Base) { 2026 // FIXME: diagnostic 2027 Info.CCEDiag(Loc); 2028 return true; 2029 } 2030 2031 // Does this refer one past the end of some object? 2032 if (!Designator.Invalid && Designator.isOnePastTheEnd()) { 2033 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>(); 2034 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) 2035 << !Designator.Entries.empty() << !!VD << VD; 2036 NoteLValueLocation(Info, Base); 2037 } 2038 2039 return true; 2040 } 2041 2042 /// Member pointers are constant expressions unless they point to a 2043 /// non-virtual dllimport member function. 2044 static bool CheckMemberPointerConstantExpression(EvalInfo &Info, 2045 SourceLocation Loc, 2046 QualType Type, 2047 const APValue &Value, 2048 Expr::ConstExprUsage Usage) { 2049 const ValueDecl *Member = Value.getMemberPointerDecl(); 2050 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member); 2051 if (!FD) 2052 return true; 2053 return Usage == Expr::EvaluateForMangling || FD->isVirtual() || 2054 !FD->hasAttr<DLLImportAttr>(); 2055 } 2056 2057 /// Check that this core constant expression is of literal type, and if not, 2058 /// produce an appropriate diagnostic. 2059 static bool CheckLiteralType(EvalInfo &Info, const Expr *E, 2060 const LValue *This = nullptr) { 2061 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx)) 2062 return true; 2063 2064 // C++1y: A constant initializer for an object o [...] may also invoke 2065 // constexpr constructors for o and its subobjects even if those objects 2066 // are of non-literal class types. 2067 // 2068 // C++11 missed this detail for aggregates, so classes like this: 2069 // struct foo_t { union { int i; volatile int j; } u; }; 2070 // are not (obviously) initializable like so: 2071 // __attribute__((__require_constant_initialization__)) 2072 // static const foo_t x = {{0}}; 2073 // because "i" is a subobject with non-literal initialization (due to the 2074 // volatile member of the union). See: 2075 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677 2076 // Therefore, we use the C++1y behavior. 2077 if (This && Info.EvaluatingDecl == This->getLValueBase()) 2078 return true; 2079 2080 // Prvalue constant expressions must be of literal types. 2081 if (Info.getLangOpts().CPlusPlus11) 2082 Info.FFDiag(E, diag::note_constexpr_nonliteral) 2083 << E->getType(); 2084 else 2085 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2086 return false; 2087 } 2088 2089 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, 2090 EvalInfo &Info, SourceLocation DiagLoc, 2091 QualType Type, const APValue &Value, 2092 Expr::ConstExprUsage Usage, 2093 SourceLocation SubobjectLoc, 2094 CheckedTemporaries &CheckedTemps) { 2095 if (!Value.hasValue()) { 2096 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) 2097 << true << Type; 2098 if (SubobjectLoc.isValid()) 2099 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); 2100 return false; 2101 } 2102 2103 // We allow _Atomic(T) to be initialized from anything that T can be 2104 // initialized from. 2105 if (const AtomicType *AT = Type->getAs<AtomicType>()) 2106 Type = AT->getValueType(); 2107 2108 // Core issue 1454: For a literal constant expression of array or class type, 2109 // each subobject of its value shall have been initialized by a constant 2110 // expression. 2111 if (Value.isArray()) { 2112 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType(); 2113 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) { 2114 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2115 Value.getArrayInitializedElt(I), Usage, 2116 SubobjectLoc, CheckedTemps)) 2117 return false; 2118 } 2119 if (!Value.hasArrayFiller()) 2120 return true; 2121 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy, 2122 Value.getArrayFiller(), Usage, SubobjectLoc, 2123 CheckedTemps); 2124 } 2125 if (Value.isUnion() && Value.getUnionField()) { 2126 return CheckEvaluationResult( 2127 CERK, Info, DiagLoc, Value.getUnionField()->getType(), 2128 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(), 2129 CheckedTemps); 2130 } 2131 if (Value.isStruct()) { 2132 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 2133 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 2134 unsigned BaseIndex = 0; 2135 for (const CXXBaseSpecifier &BS : CD->bases()) { 2136 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), 2137 Value.getStructBase(BaseIndex), Usage, 2138 BS.getBeginLoc(), CheckedTemps)) 2139 return false; 2140 ++BaseIndex; 2141 } 2142 } 2143 for (const auto *I : RD->fields()) { 2144 if (I->isUnnamedBitfield()) 2145 continue; 2146 2147 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), 2148 Value.getStructField(I->getFieldIndex()), 2149 Usage, I->getLocation(), CheckedTemps)) 2150 return false; 2151 } 2152 } 2153 2154 if (Value.isLValue() && 2155 CERK == CheckEvaluationResultKind::ConstantExpression) { 2156 LValue LVal; 2157 LVal.setFrom(Info.Ctx, Value); 2158 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage, 2159 CheckedTemps); 2160 } 2161 2162 if (Value.isMemberPointer() && 2163 CERK == CheckEvaluationResultKind::ConstantExpression) 2164 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage); 2165 2166 // Everything else is fine. 2167 return true; 2168 } 2169 2170 /// Check that this core constant expression value is a valid value for a 2171 /// constant expression. If not, report an appropriate diagnostic. Does not 2172 /// check that the expression is of literal type. 2173 static bool 2174 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, 2175 const APValue &Value, 2176 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) { 2177 CheckedTemporaries CheckedTemps; 2178 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, 2179 Info, DiagLoc, Type, Value, Usage, 2180 SourceLocation(), CheckedTemps); 2181 } 2182 2183 /// Check that this evaluated value is fully-initialized and can be loaded by 2184 /// an lvalue-to-rvalue conversion. 2185 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, 2186 QualType Type, const APValue &Value) { 2187 CheckedTemporaries CheckedTemps; 2188 return CheckEvaluationResult( 2189 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, 2190 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps); 2191 } 2192 2193 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless 2194 /// "the allocated storage is deallocated within the evaluation". 2195 static bool CheckMemoryLeaks(EvalInfo &Info) { 2196 if (!Info.HeapAllocs.empty()) { 2197 // We can still fold to a constant despite a compile-time memory leak, 2198 // so long as the heap allocation isn't referenced in the result (we check 2199 // that in CheckConstantExpression). 2200 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr, 2201 diag::note_constexpr_memory_leak) 2202 << unsigned(Info.HeapAllocs.size() - 1); 2203 } 2204 return true; 2205 } 2206 2207 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { 2208 // A null base expression indicates a null pointer. These are always 2209 // evaluatable, and they are false unless the offset is zero. 2210 if (!Value.getLValueBase()) { 2211 Result = !Value.getLValueOffset().isZero(); 2212 return true; 2213 } 2214 2215 // We have a non-null base. These are generally known to be true, but if it's 2216 // a weak declaration it can be null at runtime. 2217 Result = true; 2218 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>(); 2219 return !Decl || !Decl->isWeak(); 2220 } 2221 2222 static bool HandleConversionToBool(const APValue &Val, bool &Result) { 2223 switch (Val.getKind()) { 2224 case APValue::None: 2225 case APValue::Indeterminate: 2226 return false; 2227 case APValue::Int: 2228 Result = Val.getInt().getBoolValue(); 2229 return true; 2230 case APValue::FixedPoint: 2231 Result = Val.getFixedPoint().getBoolValue(); 2232 return true; 2233 case APValue::Float: 2234 Result = !Val.getFloat().isZero(); 2235 return true; 2236 case APValue::ComplexInt: 2237 Result = Val.getComplexIntReal().getBoolValue() || 2238 Val.getComplexIntImag().getBoolValue(); 2239 return true; 2240 case APValue::ComplexFloat: 2241 Result = !Val.getComplexFloatReal().isZero() || 2242 !Val.getComplexFloatImag().isZero(); 2243 return true; 2244 case APValue::LValue: 2245 return EvalPointerValueAsBool(Val, Result); 2246 case APValue::MemberPointer: 2247 Result = Val.getMemberPointerDecl(); 2248 return true; 2249 case APValue::Vector: 2250 case APValue::Array: 2251 case APValue::Struct: 2252 case APValue::Union: 2253 case APValue::AddrLabelDiff: 2254 return false; 2255 } 2256 2257 llvm_unreachable("unknown APValue kind"); 2258 } 2259 2260 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, 2261 EvalInfo &Info) { 2262 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition"); 2263 APValue Val; 2264 if (!Evaluate(Val, Info, E)) 2265 return false; 2266 return HandleConversionToBool(Val, Result); 2267 } 2268 2269 template<typename T> 2270 static bool HandleOverflow(EvalInfo &Info, const Expr *E, 2271 const T &SrcValue, QualType DestType) { 2272 Info.CCEDiag(E, diag::note_constexpr_overflow) 2273 << SrcValue << DestType; 2274 return Info.noteUndefinedBehavior(); 2275 } 2276 2277 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, 2278 QualType SrcType, const APFloat &Value, 2279 QualType DestType, APSInt &Result) { 2280 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2281 // Determine whether we are converting to unsigned or signed. 2282 bool DestSigned = DestType->isSignedIntegerOrEnumerationType(); 2283 2284 Result = APSInt(DestWidth, !DestSigned); 2285 bool ignored; 2286 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) 2287 & APFloat::opInvalidOp) 2288 return HandleOverflow(Info, E, Value, DestType); 2289 return true; 2290 } 2291 2292 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, 2293 QualType SrcType, QualType DestType, 2294 APFloat &Result) { 2295 APFloat Value = Result; 2296 bool ignored; 2297 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), 2298 APFloat::rmNearestTiesToEven, &ignored); 2299 return true; 2300 } 2301 2302 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, 2303 QualType DestType, QualType SrcType, 2304 const APSInt &Value) { 2305 unsigned DestWidth = Info.Ctx.getIntWidth(DestType); 2306 // Figure out if this is a truncate, extend or noop cast. 2307 // If the input is signed, do a sign extend, noop, or truncate. 2308 APSInt Result = Value.extOrTrunc(DestWidth); 2309 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType()); 2310 if (DestType->isBooleanType()) 2311 Result = Value.getBoolValue(); 2312 return Result; 2313 } 2314 2315 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, 2316 QualType SrcType, const APSInt &Value, 2317 QualType DestType, APFloat &Result) { 2318 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); 2319 Result.convertFromAPInt(Value, Value.isSigned(), 2320 APFloat::rmNearestTiesToEven); 2321 return true; 2322 } 2323 2324 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, 2325 APValue &Value, const FieldDecl *FD) { 2326 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); 2327 2328 if (!Value.isInt()) { 2329 // Trying to store a pointer-cast-to-integer into a bitfield. 2330 // FIXME: In this case, we should provide the diagnostic for casting 2331 // a pointer to an integer. 2332 assert(Value.isLValue() && "integral value neither int nor lvalue?"); 2333 Info.FFDiag(E); 2334 return false; 2335 } 2336 2337 APSInt &Int = Value.getInt(); 2338 unsigned OldBitWidth = Int.getBitWidth(); 2339 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx); 2340 if (NewBitWidth < OldBitWidth) 2341 Int = Int.trunc(NewBitWidth).extend(OldBitWidth); 2342 return true; 2343 } 2344 2345 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, 2346 llvm::APInt &Res) { 2347 APValue SVal; 2348 if (!Evaluate(SVal, Info, E)) 2349 return false; 2350 if (SVal.isInt()) { 2351 Res = SVal.getInt(); 2352 return true; 2353 } 2354 if (SVal.isFloat()) { 2355 Res = SVal.getFloat().bitcastToAPInt(); 2356 return true; 2357 } 2358 if (SVal.isVector()) { 2359 QualType VecTy = E->getType(); 2360 unsigned VecSize = Info.Ctx.getTypeSize(VecTy); 2361 QualType EltTy = VecTy->castAs<VectorType>()->getElementType(); 2362 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 2363 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 2364 Res = llvm::APInt::getNullValue(VecSize); 2365 for (unsigned i = 0; i < SVal.getVectorLength(); i++) { 2366 APValue &Elt = SVal.getVectorElt(i); 2367 llvm::APInt EltAsInt; 2368 if (Elt.isInt()) { 2369 EltAsInt = Elt.getInt(); 2370 } else if (Elt.isFloat()) { 2371 EltAsInt = Elt.getFloat().bitcastToAPInt(); 2372 } else { 2373 // Don't try to handle vectors of anything other than int or float 2374 // (not sure if it's possible to hit this case). 2375 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2376 return false; 2377 } 2378 unsigned BaseEltSize = EltAsInt.getBitWidth(); 2379 if (BigEndian) 2380 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); 2381 else 2382 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); 2383 } 2384 return true; 2385 } 2386 // Give up if the input isn't an int, float, or vector. For example, we 2387 // reject "(v4i16)(intptr_t)&a". 2388 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2389 return false; 2390 } 2391 2392 /// Perform the given integer operation, which is known to need at most BitWidth 2393 /// bits, and check for overflow in the original type (if that type was not an 2394 /// unsigned type). 2395 template<typename Operation> 2396 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, 2397 const APSInt &LHS, const APSInt &RHS, 2398 unsigned BitWidth, Operation Op, 2399 APSInt &Result) { 2400 if (LHS.isUnsigned()) { 2401 Result = Op(LHS, RHS); 2402 return true; 2403 } 2404 2405 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false); 2406 Result = Value.trunc(LHS.getBitWidth()); 2407 if (Result.extend(BitWidth) != Value) { 2408 if (Info.checkingForUndefinedBehavior()) 2409 Info.Ctx.getDiagnostics().Report(E->getExprLoc(), 2410 diag::warn_integer_constant_overflow) 2411 << Result.toString(10) << E->getType(); 2412 else 2413 return HandleOverflow(Info, E, Value, E->getType()); 2414 } 2415 return true; 2416 } 2417 2418 /// Perform the given binary integer operation. 2419 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, 2420 BinaryOperatorKind Opcode, APSInt RHS, 2421 APSInt &Result) { 2422 switch (Opcode) { 2423 default: 2424 Info.FFDiag(E); 2425 return false; 2426 case BO_Mul: 2427 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2, 2428 std::multiplies<APSInt>(), Result); 2429 case BO_Add: 2430 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2431 std::plus<APSInt>(), Result); 2432 case BO_Sub: 2433 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, 2434 std::minus<APSInt>(), Result); 2435 case BO_And: Result = LHS & RHS; return true; 2436 case BO_Xor: Result = LHS ^ RHS; return true; 2437 case BO_Or: Result = LHS | RHS; return true; 2438 case BO_Div: 2439 case BO_Rem: 2440 if (RHS == 0) { 2441 Info.FFDiag(E, diag::note_expr_divide_by_zero); 2442 return false; 2443 } 2444 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); 2445 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports 2446 // this operation and gives the two's complement result. 2447 if (RHS.isNegative() && RHS.isAllOnesValue() && 2448 LHS.isSigned() && LHS.isMinSignedValue()) 2449 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), 2450 E->getType()); 2451 return true; 2452 case BO_Shl: { 2453 if (Info.getLangOpts().OpenCL) 2454 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2455 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2456 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2457 RHS.isUnsigned()); 2458 else if (RHS.isSigned() && RHS.isNegative()) { 2459 // During constant-folding, a negative shift is an opposite shift. Such 2460 // a shift is not a constant expression. 2461 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2462 RHS = -RHS; 2463 goto shift_right; 2464 } 2465 shift_left: 2466 // C++11 [expr.shift]p1: Shift width must be less than the bit width of 2467 // the shifted type. 2468 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2469 if (SA != RHS) { 2470 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2471 << RHS << E->getType() << LHS.getBitWidth(); 2472 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) { 2473 // C++11 [expr.shift]p2: A signed left shift must have a non-negative 2474 // operand, and must not overflow the corresponding unsigned type. 2475 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to 2476 // E1 x 2^E2 module 2^N. 2477 if (LHS.isNegative()) 2478 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS; 2479 else if (LHS.countLeadingZeros() < SA) 2480 Info.CCEDiag(E, diag::note_constexpr_lshift_discards); 2481 } 2482 Result = LHS << SA; 2483 return true; 2484 } 2485 case BO_Shr: { 2486 if (Info.getLangOpts().OpenCL) 2487 // OpenCL 6.3j: shift values are effectively % word size of LHS. 2488 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), 2489 static_cast<uint64_t>(LHS.getBitWidth() - 1)), 2490 RHS.isUnsigned()); 2491 else if (RHS.isSigned() && RHS.isNegative()) { 2492 // During constant-folding, a negative shift is an opposite shift. Such a 2493 // shift is not a constant expression. 2494 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS; 2495 RHS = -RHS; 2496 goto shift_left; 2497 } 2498 shift_right: 2499 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the 2500 // shifted type. 2501 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); 2502 if (SA != RHS) 2503 Info.CCEDiag(E, diag::note_constexpr_large_shift) 2504 << RHS << E->getType() << LHS.getBitWidth(); 2505 Result = LHS >> SA; 2506 return true; 2507 } 2508 2509 case BO_LT: Result = LHS < RHS; return true; 2510 case BO_GT: Result = LHS > RHS; return true; 2511 case BO_LE: Result = LHS <= RHS; return true; 2512 case BO_GE: Result = LHS >= RHS; return true; 2513 case BO_EQ: Result = LHS == RHS; return true; 2514 case BO_NE: Result = LHS != RHS; return true; 2515 case BO_Cmp: 2516 llvm_unreachable("BO_Cmp should be handled elsewhere"); 2517 } 2518 } 2519 2520 /// Perform the given binary floating-point operation, in-place, on LHS. 2521 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E, 2522 APFloat &LHS, BinaryOperatorKind Opcode, 2523 const APFloat &RHS) { 2524 switch (Opcode) { 2525 default: 2526 Info.FFDiag(E); 2527 return false; 2528 case BO_Mul: 2529 LHS.multiply(RHS, APFloat::rmNearestTiesToEven); 2530 break; 2531 case BO_Add: 2532 LHS.add(RHS, APFloat::rmNearestTiesToEven); 2533 break; 2534 case BO_Sub: 2535 LHS.subtract(RHS, APFloat::rmNearestTiesToEven); 2536 break; 2537 case BO_Div: 2538 // [expr.mul]p4: 2539 // If the second operand of / or % is zero the behavior is undefined. 2540 if (RHS.isZero()) 2541 Info.CCEDiag(E, diag::note_expr_divide_by_zero); 2542 LHS.divide(RHS, APFloat::rmNearestTiesToEven); 2543 break; 2544 } 2545 2546 // [expr.pre]p4: 2547 // If during the evaluation of an expression, the result is not 2548 // mathematically defined [...], the behavior is undefined. 2549 // FIXME: C++ rules require us to not conform to IEEE 754 here. 2550 if (LHS.isNaN()) { 2551 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN(); 2552 return Info.noteUndefinedBehavior(); 2553 } 2554 return true; 2555 } 2556 2557 /// Cast an lvalue referring to a base subobject to a derived class, by 2558 /// truncating the lvalue's path to the given length. 2559 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, 2560 const RecordDecl *TruncatedType, 2561 unsigned TruncatedElements) { 2562 SubobjectDesignator &D = Result.Designator; 2563 2564 // Check we actually point to a derived class object. 2565 if (TruncatedElements == D.Entries.size()) 2566 return true; 2567 assert(TruncatedElements >= D.MostDerivedPathLength && 2568 "not casting to a derived class"); 2569 if (!Result.checkSubobject(Info, E, CSK_Derived)) 2570 return false; 2571 2572 // Truncate the path to the subobject, and remove any derived-to-base offsets. 2573 const RecordDecl *RD = TruncatedType; 2574 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { 2575 if (RD->isInvalidDecl()) return false; 2576 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 2577 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); 2578 if (isVirtualBaseClass(D.Entries[I])) 2579 Result.Offset -= Layout.getVBaseClassOffset(Base); 2580 else 2581 Result.Offset -= Layout.getBaseClassOffset(Base); 2582 RD = Base; 2583 } 2584 D.Entries.resize(TruncatedElements); 2585 return true; 2586 } 2587 2588 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2589 const CXXRecordDecl *Derived, 2590 const CXXRecordDecl *Base, 2591 const ASTRecordLayout *RL = nullptr) { 2592 if (!RL) { 2593 if (Derived->isInvalidDecl()) return false; 2594 RL = &Info.Ctx.getASTRecordLayout(Derived); 2595 } 2596 2597 Obj.getLValueOffset() += RL->getBaseClassOffset(Base); 2598 Obj.addDecl(Info, E, Base, /*Virtual*/ false); 2599 return true; 2600 } 2601 2602 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, 2603 const CXXRecordDecl *DerivedDecl, 2604 const CXXBaseSpecifier *Base) { 2605 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 2606 2607 if (!Base->isVirtual()) 2608 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); 2609 2610 SubobjectDesignator &D = Obj.Designator; 2611 if (D.Invalid) 2612 return false; 2613 2614 // Extract most-derived object and corresponding type. 2615 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl(); 2616 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength)) 2617 return false; 2618 2619 // Find the virtual base class. 2620 if (DerivedDecl->isInvalidDecl()) return false; 2621 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); 2622 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); 2623 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); 2624 return true; 2625 } 2626 2627 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, 2628 QualType Type, LValue &Result) { 2629 for (CastExpr::path_const_iterator PathI = E->path_begin(), 2630 PathE = E->path_end(); 2631 PathI != PathE; ++PathI) { 2632 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), 2633 *PathI)) 2634 return false; 2635 Type = (*PathI)->getType(); 2636 } 2637 return true; 2638 } 2639 2640 /// Cast an lvalue referring to a derived class to a known base subobject. 2641 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, 2642 const CXXRecordDecl *DerivedRD, 2643 const CXXRecordDecl *BaseRD) { 2644 CXXBasePaths Paths(/*FindAmbiguities=*/false, 2645 /*RecordPaths=*/true, /*DetectVirtual=*/false); 2646 if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) 2647 llvm_unreachable("Class must be derived from the passed in base class!"); 2648 2649 for (CXXBasePathElement &Elem : Paths.front()) 2650 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base)) 2651 return false; 2652 return true; 2653 } 2654 2655 /// Update LVal to refer to the given field, which must be a member of the type 2656 /// currently described by LVal. 2657 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, 2658 const FieldDecl *FD, 2659 const ASTRecordLayout *RL = nullptr) { 2660 if (!RL) { 2661 if (FD->getParent()->isInvalidDecl()) return false; 2662 RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); 2663 } 2664 2665 unsigned I = FD->getFieldIndex(); 2666 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I))); 2667 LVal.addDecl(Info, E, FD); 2668 return true; 2669 } 2670 2671 /// Update LVal to refer to the given indirect field. 2672 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, 2673 LValue &LVal, 2674 const IndirectFieldDecl *IFD) { 2675 for (const auto *C : IFD->chain()) 2676 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C))) 2677 return false; 2678 return true; 2679 } 2680 2681 /// Get the size of the given type in char units. 2682 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, 2683 QualType Type, CharUnits &Size) { 2684 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc 2685 // extension. 2686 if (Type->isVoidType() || Type->isFunctionType()) { 2687 Size = CharUnits::One(); 2688 return true; 2689 } 2690 2691 if (Type->isDependentType()) { 2692 Info.FFDiag(Loc); 2693 return false; 2694 } 2695 2696 if (!Type->isConstantSizeType()) { 2697 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2. 2698 // FIXME: Better diagnostic. 2699 Info.FFDiag(Loc); 2700 return false; 2701 } 2702 2703 Size = Info.Ctx.getTypeSizeInChars(Type); 2704 return true; 2705 } 2706 2707 /// Update a pointer value to model pointer arithmetic. 2708 /// \param Info - Information about the ongoing evaluation. 2709 /// \param E - The expression being evaluated, for diagnostic purposes. 2710 /// \param LVal - The pointer value to be updated. 2711 /// \param EltTy - The pointee type represented by LVal. 2712 /// \param Adjustment - The adjustment, in objects of type EltTy, to add. 2713 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2714 LValue &LVal, QualType EltTy, 2715 APSInt Adjustment) { 2716 CharUnits SizeOfPointee; 2717 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee)) 2718 return false; 2719 2720 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee); 2721 return true; 2722 } 2723 2724 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, 2725 LValue &LVal, QualType EltTy, 2726 int64_t Adjustment) { 2727 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, 2728 APSInt::get(Adjustment)); 2729 } 2730 2731 /// Update an lvalue to refer to a component of a complex number. 2732 /// \param Info - Information about the ongoing evaluation. 2733 /// \param LVal - The lvalue to be updated. 2734 /// \param EltTy - The complex number's component type. 2735 /// \param Imag - False for the real component, true for the imaginary. 2736 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, 2737 LValue &LVal, QualType EltTy, 2738 bool Imag) { 2739 if (Imag) { 2740 CharUnits SizeOfComponent; 2741 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent)) 2742 return false; 2743 LVal.Offset += SizeOfComponent; 2744 } 2745 LVal.addComplex(Info, E, EltTy, Imag); 2746 return true; 2747 } 2748 2749 /// Try to evaluate the initializer for a variable declaration. 2750 /// 2751 /// \param Info Information about the ongoing evaluation. 2752 /// \param E An expression to be used when printing diagnostics. 2753 /// \param VD The variable whose initializer should be obtained. 2754 /// \param Frame The frame in which the variable was created. Must be null 2755 /// if this variable is not local to the evaluation. 2756 /// \param Result Filled in with a pointer to the value of the variable. 2757 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, 2758 const VarDecl *VD, CallStackFrame *Frame, 2759 APValue *&Result, const LValue *LVal) { 2760 2761 // If this is a parameter to an active constexpr function call, perform 2762 // argument substitution. 2763 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) { 2764 // Assume arguments of a potential constant expression are unknown 2765 // constant expressions. 2766 if (Info.checkingPotentialConstantExpression()) 2767 return false; 2768 if (!Frame || !Frame->Arguments) { 2769 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2770 return false; 2771 } 2772 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()]; 2773 return true; 2774 } 2775 2776 // If this is a local variable, dig out its value. 2777 if (Frame) { 2778 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion()) 2779 : Frame->getCurrentTemporary(VD); 2780 if (!Result) { 2781 // Assume variables referenced within a lambda's call operator that were 2782 // not declared within the call operator are captures and during checking 2783 // of a potential constant expression, assume they are unknown constant 2784 // expressions. 2785 assert(isLambdaCallOperator(Frame->Callee) && 2786 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) && 2787 "missing value for local variable"); 2788 if (Info.checkingPotentialConstantExpression()) 2789 return false; 2790 // FIXME: implement capture evaluation during constant expr evaluation. 2791 Info.FFDiag(E->getBeginLoc(), 2792 diag::note_unimplemented_constexpr_lambda_feature_ast) 2793 << "captures not currently allowed"; 2794 return false; 2795 } 2796 return true; 2797 } 2798 2799 // Dig out the initializer, and use the declaration which it's attached to. 2800 const Expr *Init = VD->getAnyInitializer(VD); 2801 if (!Init || Init->isValueDependent()) { 2802 // If we're checking a potential constant expression, the variable could be 2803 // initialized later. 2804 if (!Info.checkingPotentialConstantExpression()) 2805 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2806 return false; 2807 } 2808 2809 // If we're currently evaluating the initializer of this declaration, use that 2810 // in-flight value. 2811 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) { 2812 Result = Info.EvaluatingDeclValue; 2813 return true; 2814 } 2815 2816 // Never evaluate the initializer of a weak variable. We can't be sure that 2817 // this is the definition which will be used. 2818 if (VD->isWeak()) { 2819 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 2820 return false; 2821 } 2822 2823 // Check that we can fold the initializer. In C++, we will have already done 2824 // this in the cases where it matters for conformance. 2825 SmallVector<PartialDiagnosticAt, 8> Notes; 2826 if (!VD->evaluateValue(Notes)) { 2827 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 2828 Notes.size() + 1) << VD; 2829 Info.Note(VD->getLocation(), diag::note_declared_at); 2830 Info.addNotes(Notes); 2831 return false; 2832 } else if (!VD->checkInitIsICE()) { 2833 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 2834 Notes.size() + 1) << VD; 2835 Info.Note(VD->getLocation(), diag::note_declared_at); 2836 Info.addNotes(Notes); 2837 } 2838 2839 Result = VD->getEvaluatedValue(); 2840 return true; 2841 } 2842 2843 static bool IsConstNonVolatile(QualType T) { 2844 Qualifiers Quals = T.getQualifiers(); 2845 return Quals.hasConst() && !Quals.hasVolatile(); 2846 } 2847 2848 /// Get the base index of the given base class within an APValue representing 2849 /// the given derived class. 2850 static unsigned getBaseIndex(const CXXRecordDecl *Derived, 2851 const CXXRecordDecl *Base) { 2852 Base = Base->getCanonicalDecl(); 2853 unsigned Index = 0; 2854 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), 2855 E = Derived->bases_end(); I != E; ++I, ++Index) { 2856 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) 2857 return Index; 2858 } 2859 2860 llvm_unreachable("base class missing from derived class's bases list"); 2861 } 2862 2863 /// Extract the value of a character from a string literal. 2864 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, 2865 uint64_t Index) { 2866 assert(!isa<SourceLocExpr>(Lit) && 2867 "SourceLocExpr should have already been converted to a StringLiteral"); 2868 2869 // FIXME: Support MakeStringConstant 2870 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) { 2871 std::string Str; 2872 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); 2873 assert(Index <= Str.size() && "Index too large"); 2874 return APSInt::getUnsigned(Str.c_str()[Index]); 2875 } 2876 2877 if (auto PE = dyn_cast<PredefinedExpr>(Lit)) 2878 Lit = PE->getFunctionName(); 2879 const StringLiteral *S = cast<StringLiteral>(Lit); 2880 const ConstantArrayType *CAT = 2881 Info.Ctx.getAsConstantArrayType(S->getType()); 2882 assert(CAT && "string literal isn't an array"); 2883 QualType CharType = CAT->getElementType(); 2884 assert(CharType->isIntegerType() && "unexpected character type"); 2885 2886 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2887 CharType->isUnsignedIntegerType()); 2888 if (Index < S->getLength()) 2889 Value = S->getCodeUnit(Index); 2890 return Value; 2891 } 2892 2893 // Expand a string literal into an array of characters. 2894 // 2895 // FIXME: This is inefficient; we should probably introduce something similar 2896 // to the LLVM ConstantDataArray to make this cheaper. 2897 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, 2898 APValue &Result, 2899 QualType AllocType = QualType()) { 2900 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 2901 AllocType.isNull() ? S->getType() : AllocType); 2902 assert(CAT && "string literal isn't an array"); 2903 QualType CharType = CAT->getElementType(); 2904 assert(CharType->isIntegerType() && "unexpected character type"); 2905 2906 unsigned Elts = CAT->getSize().getZExtValue(); 2907 Result = APValue(APValue::UninitArray(), 2908 std::min(S->getLength(), Elts), Elts); 2909 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), 2910 CharType->isUnsignedIntegerType()); 2911 if (Result.hasArrayFiller()) 2912 Result.getArrayFiller() = APValue(Value); 2913 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) { 2914 Value = S->getCodeUnit(I); 2915 Result.getArrayInitializedElt(I) = APValue(Value); 2916 } 2917 } 2918 2919 // Expand an array so that it has more than Index filled elements. 2920 static void expandArray(APValue &Array, unsigned Index) { 2921 unsigned Size = Array.getArraySize(); 2922 assert(Index < Size); 2923 2924 // Always at least double the number of elements for which we store a value. 2925 unsigned OldElts = Array.getArrayInitializedElts(); 2926 unsigned NewElts = std::max(Index+1, OldElts * 2); 2927 NewElts = std::min(Size, std::max(NewElts, 8u)); 2928 2929 // Copy the data across. 2930 APValue NewValue(APValue::UninitArray(), NewElts, Size); 2931 for (unsigned I = 0; I != OldElts; ++I) 2932 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I)); 2933 for (unsigned I = OldElts; I != NewElts; ++I) 2934 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller(); 2935 if (NewValue.hasArrayFiller()) 2936 NewValue.getArrayFiller() = Array.getArrayFiller(); 2937 Array.swap(NewValue); 2938 } 2939 2940 /// Determine whether a type would actually be read by an lvalue-to-rvalue 2941 /// conversion. If it's of class type, we may assume that the copy operation 2942 /// is trivial. Note that this is never true for a union type with fields 2943 /// (because the copy always "reads" the active member) and always true for 2944 /// a non-class type. 2945 static bool isReadByLvalueToRvalueConversion(QualType T) { 2946 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2947 if (!RD || (RD->isUnion() && !RD->field_empty())) 2948 return true; 2949 if (RD->isEmpty()) 2950 return false; 2951 2952 for (auto *Field : RD->fields()) 2953 if (isReadByLvalueToRvalueConversion(Field->getType())) 2954 return true; 2955 2956 for (auto &BaseSpec : RD->bases()) 2957 if (isReadByLvalueToRvalueConversion(BaseSpec.getType())) 2958 return true; 2959 2960 return false; 2961 } 2962 2963 /// Diagnose an attempt to read from any unreadable field within the specified 2964 /// type, which might be a class type. 2965 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, 2966 QualType T) { 2967 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2968 if (!RD) 2969 return false; 2970 2971 if (!RD->hasMutableFields()) 2972 return false; 2973 2974 for (auto *Field : RD->fields()) { 2975 // If we're actually going to read this field in some way, then it can't 2976 // be mutable. If we're in a union, then assigning to a mutable field 2977 // (even an empty one) can change the active member, so that's not OK. 2978 // FIXME: Add core issue number for the union case. 2979 if (Field->isMutable() && 2980 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) { 2981 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field; 2982 Info.Note(Field->getLocation(), diag::note_declared_at); 2983 return true; 2984 } 2985 2986 if (diagnoseMutableFields(Info, E, AK, Field->getType())) 2987 return true; 2988 } 2989 2990 for (auto &BaseSpec : RD->bases()) 2991 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType())) 2992 return true; 2993 2994 // All mutable fields were empty, and thus not actually read. 2995 return false; 2996 } 2997 2998 static bool lifetimeStartedInEvaluation(EvalInfo &Info, 2999 APValue::LValueBase Base, 3000 bool MutableSubobject = false) { 3001 // A temporary we created. 3002 if (Base.getCallIndex()) 3003 return true; 3004 3005 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>(); 3006 if (!Evaluating) 3007 return false; 3008 3009 auto *BaseD = Base.dyn_cast<const ValueDecl*>(); 3010 3011 switch (Info.IsEvaluatingDecl) { 3012 case EvalInfo::EvaluatingDeclKind::None: 3013 return false; 3014 3015 case EvalInfo::EvaluatingDeclKind::Ctor: 3016 // The variable whose initializer we're evaluating. 3017 if (BaseD) 3018 return declaresSameEntity(Evaluating, BaseD); 3019 3020 // A temporary lifetime-extended by the variable whose initializer we're 3021 // evaluating. 3022 if (auto *BaseE = Base.dyn_cast<const Expr *>()) 3023 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE)) 3024 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating); 3025 return false; 3026 3027 case EvalInfo::EvaluatingDeclKind::Dtor: 3028 // C++2a [expr.const]p6: 3029 // [during constant destruction] the lifetime of a and its non-mutable 3030 // subobjects (but not its mutable subobjects) [are] considered to start 3031 // within e. 3032 // 3033 // FIXME: We can meaningfully extend this to cover non-const objects, but 3034 // we will need special handling: we should be able to access only 3035 // subobjects of such objects that are themselves declared const. 3036 if (!BaseD || 3037 !(BaseD->getType().isConstQualified() || 3038 BaseD->getType()->isReferenceType()) || 3039 MutableSubobject) 3040 return false; 3041 return declaresSameEntity(Evaluating, BaseD); 3042 } 3043 3044 llvm_unreachable("unknown evaluating decl kind"); 3045 } 3046 3047 namespace { 3048 /// A handle to a complete object (an object that is not a subobject of 3049 /// another object). 3050 struct CompleteObject { 3051 /// The identity of the object. 3052 APValue::LValueBase Base; 3053 /// The value of the complete object. 3054 APValue *Value; 3055 /// The type of the complete object. 3056 QualType Type; 3057 3058 CompleteObject() : Value(nullptr) {} 3059 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type) 3060 : Base(Base), Value(Value), Type(Type) {} 3061 3062 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const { 3063 // In C++14 onwards, it is permitted to read a mutable member whose 3064 // lifetime began within the evaluation. 3065 // FIXME: Should we also allow this in C++11? 3066 if (!Info.getLangOpts().CPlusPlus14) 3067 return false; 3068 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); 3069 } 3070 3071 explicit operator bool() const { return !Type.isNull(); } 3072 }; 3073 } // end anonymous namespace 3074 3075 static QualType getSubobjectType(QualType ObjType, QualType SubobjType, 3076 bool IsMutable = false) { 3077 // C++ [basic.type.qualifier]p1: 3078 // - A const object is an object of type const T or a non-mutable subobject 3079 // of a const object. 3080 if (ObjType.isConstQualified() && !IsMutable) 3081 SubobjType.addConst(); 3082 // - A volatile object is an object of type const T or a subobject of a 3083 // volatile object. 3084 if (ObjType.isVolatileQualified()) 3085 SubobjType.addVolatile(); 3086 return SubobjType; 3087 } 3088 3089 /// Find the designated sub-object of an rvalue. 3090 template<typename SubobjectHandler> 3091 typename SubobjectHandler::result_type 3092 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, 3093 const SubobjectDesignator &Sub, SubobjectHandler &handler) { 3094 if (Sub.Invalid) 3095 // A diagnostic will have already been produced. 3096 return handler.failed(); 3097 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) { 3098 if (Info.getLangOpts().CPlusPlus11) 3099 Info.FFDiag(E, Sub.isOnePastTheEnd() 3100 ? diag::note_constexpr_access_past_end 3101 : diag::note_constexpr_access_unsized_array) 3102 << handler.AccessKind; 3103 else 3104 Info.FFDiag(E); 3105 return handler.failed(); 3106 } 3107 3108 APValue *O = Obj.Value; 3109 QualType ObjType = Obj.Type; 3110 const FieldDecl *LastField = nullptr; 3111 const FieldDecl *VolatileField = nullptr; 3112 3113 // Walk the designator's path to find the subobject. 3114 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { 3115 // Reading an indeterminate value is undefined, but assigning over one is OK. 3116 if (O->isAbsent() || 3117 (O->isIndeterminate() && handler.AccessKind != AK_Assign && 3118 handler.AccessKind != AK_ReadObjectRepresentation)) { 3119 if (!Info.checkingPotentialConstantExpression()) 3120 Info.FFDiag(E, diag::note_constexpr_access_uninit) 3121 << handler.AccessKind << O->isIndeterminate(); 3122 return handler.failed(); 3123 } 3124 3125 // C++ [class.ctor]p5, C++ [class.dtor]p5: 3126 // const and volatile semantics are not applied on an object under 3127 // {con,de}struction. 3128 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && 3129 ObjType->isRecordType() && 3130 Info.isEvaluatingCtorDtor( 3131 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), 3132 Sub.Entries.begin() + I)) != 3133 ConstructionPhase::None) { 3134 ObjType = Info.Ctx.getCanonicalType(ObjType); 3135 ObjType.removeLocalConst(); 3136 ObjType.removeLocalVolatile(); 3137 } 3138 3139 // If this is our last pass, check that the final object type is OK. 3140 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) { 3141 // Accesses to volatile objects are prohibited. 3142 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) { 3143 if (Info.getLangOpts().CPlusPlus) { 3144 int DiagKind; 3145 SourceLocation Loc; 3146 const NamedDecl *Decl = nullptr; 3147 if (VolatileField) { 3148 DiagKind = 2; 3149 Loc = VolatileField->getLocation(); 3150 Decl = VolatileField; 3151 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) { 3152 DiagKind = 1; 3153 Loc = VD->getLocation(); 3154 Decl = VD; 3155 } else { 3156 DiagKind = 0; 3157 if (auto *E = Obj.Base.dyn_cast<const Expr *>()) 3158 Loc = E->getExprLoc(); 3159 } 3160 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) 3161 << handler.AccessKind << DiagKind << Decl; 3162 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind; 3163 } else { 3164 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 3165 } 3166 return handler.failed(); 3167 } 3168 3169 // If we are reading an object of class type, there may still be more 3170 // things we need to check: if there are any mutable subobjects, we 3171 // cannot perform this read. (This only happens when performing a trivial 3172 // copy or assignment.) 3173 if (ObjType->isRecordType() && 3174 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) && 3175 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)) 3176 return handler.failed(); 3177 } 3178 3179 if (I == N) { 3180 if (!handler.found(*O, ObjType)) 3181 return false; 3182 3183 // If we modified a bit-field, truncate it to the right width. 3184 if (isModification(handler.AccessKind) && 3185 LastField && LastField->isBitField() && 3186 !truncateBitfieldValue(Info, E, *O, LastField)) 3187 return false; 3188 3189 return true; 3190 } 3191 3192 LastField = nullptr; 3193 if (ObjType->isArrayType()) { 3194 // Next subobject is an array element. 3195 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); 3196 assert(CAT && "vla in literal type?"); 3197 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3198 if (CAT->getSize().ule(Index)) { 3199 // Note, it should not be possible to form a pointer with a valid 3200 // designator which points more than one past the end of the array. 3201 if (Info.getLangOpts().CPlusPlus11) 3202 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3203 << handler.AccessKind; 3204 else 3205 Info.FFDiag(E); 3206 return handler.failed(); 3207 } 3208 3209 ObjType = CAT->getElementType(); 3210 3211 if (O->getArrayInitializedElts() > Index) 3212 O = &O->getArrayInitializedElt(Index); 3213 else if (!isRead(handler.AccessKind)) { 3214 expandArray(*O, Index); 3215 O = &O->getArrayInitializedElt(Index); 3216 } else 3217 O = &O->getArrayFiller(); 3218 } else if (ObjType->isAnyComplexType()) { 3219 // Next subobject is a complex number. 3220 uint64_t Index = Sub.Entries[I].getAsArrayIndex(); 3221 if (Index > 1) { 3222 if (Info.getLangOpts().CPlusPlus11) 3223 Info.FFDiag(E, diag::note_constexpr_access_past_end) 3224 << handler.AccessKind; 3225 else 3226 Info.FFDiag(E); 3227 return handler.failed(); 3228 } 3229 3230 ObjType = getSubobjectType( 3231 ObjType, ObjType->castAs<ComplexType>()->getElementType()); 3232 3233 assert(I == N - 1 && "extracting subobject of scalar?"); 3234 if (O->isComplexInt()) { 3235 return handler.found(Index ? O->getComplexIntImag() 3236 : O->getComplexIntReal(), ObjType); 3237 } else { 3238 assert(O->isComplexFloat()); 3239 return handler.found(Index ? O->getComplexFloatImag() 3240 : O->getComplexFloatReal(), ObjType); 3241 } 3242 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { 3243 if (Field->isMutable() && 3244 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { 3245 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) 3246 << handler.AccessKind << Field; 3247 Info.Note(Field->getLocation(), diag::note_declared_at); 3248 return handler.failed(); 3249 } 3250 3251 // Next subobject is a class, struct or union field. 3252 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl(); 3253 if (RD->isUnion()) { 3254 const FieldDecl *UnionField = O->getUnionField(); 3255 if (!UnionField || 3256 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { 3257 // FIXME: If O->getUnionValue() is absent, report that there's no 3258 // active union member rather than reporting the prior active union 3259 // member. We'll need to fix nullptr_t to not use APValue() as its 3260 // representation first. 3261 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member) 3262 << handler.AccessKind << Field << !UnionField << UnionField; 3263 return handler.failed(); 3264 } 3265 O = &O->getUnionValue(); 3266 } else 3267 O = &O->getStructField(Field->getFieldIndex()); 3268 3269 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable()); 3270 LastField = Field; 3271 if (Field->getType().isVolatileQualified()) 3272 VolatileField = Field; 3273 } else { 3274 // Next subobject is a base class. 3275 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); 3276 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); 3277 O = &O->getStructBase(getBaseIndex(Derived, Base)); 3278 3279 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); 3280 } 3281 } 3282 } 3283 3284 namespace { 3285 struct ExtractSubobjectHandler { 3286 EvalInfo &Info; 3287 const Expr *E; 3288 APValue &Result; 3289 const AccessKinds AccessKind; 3290 3291 typedef bool result_type; 3292 bool failed() { return false; } 3293 bool found(APValue &Subobj, QualType SubobjType) { 3294 Result = Subobj; 3295 if (AccessKind == AK_ReadObjectRepresentation) 3296 return true; 3297 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result); 3298 } 3299 bool found(APSInt &Value, QualType SubobjType) { 3300 Result = APValue(Value); 3301 return true; 3302 } 3303 bool found(APFloat &Value, QualType SubobjType) { 3304 Result = APValue(Value); 3305 return true; 3306 } 3307 }; 3308 } // end anonymous namespace 3309 3310 /// Extract the designated sub-object of an rvalue. 3311 static bool extractSubobject(EvalInfo &Info, const Expr *E, 3312 const CompleteObject &Obj, 3313 const SubobjectDesignator &Sub, APValue &Result, 3314 AccessKinds AK = AK_Read) { 3315 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); 3316 ExtractSubobjectHandler Handler = {Info, E, Result, AK}; 3317 return findSubobject(Info, E, Obj, Sub, Handler); 3318 } 3319 3320 namespace { 3321 struct ModifySubobjectHandler { 3322 EvalInfo &Info; 3323 APValue &NewVal; 3324 const Expr *E; 3325 3326 typedef bool result_type; 3327 static const AccessKinds AccessKind = AK_Assign; 3328 3329 bool checkConst(QualType QT) { 3330 // Assigning to a const object has undefined behavior. 3331 if (QT.isConstQualified()) { 3332 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3333 return false; 3334 } 3335 return true; 3336 } 3337 3338 bool failed() { return false; } 3339 bool found(APValue &Subobj, QualType SubobjType) { 3340 if (!checkConst(SubobjType)) 3341 return false; 3342 // We've been given ownership of NewVal, so just swap it in. 3343 Subobj.swap(NewVal); 3344 return true; 3345 } 3346 bool found(APSInt &Value, QualType SubobjType) { 3347 if (!checkConst(SubobjType)) 3348 return false; 3349 if (!NewVal.isInt()) { 3350 // Maybe trying to write a cast pointer value into a complex? 3351 Info.FFDiag(E); 3352 return false; 3353 } 3354 Value = NewVal.getInt(); 3355 return true; 3356 } 3357 bool found(APFloat &Value, QualType SubobjType) { 3358 if (!checkConst(SubobjType)) 3359 return false; 3360 Value = NewVal.getFloat(); 3361 return true; 3362 } 3363 }; 3364 } // end anonymous namespace 3365 3366 const AccessKinds ModifySubobjectHandler::AccessKind; 3367 3368 /// Update the designated sub-object of an rvalue to the given value. 3369 static bool modifySubobject(EvalInfo &Info, const Expr *E, 3370 const CompleteObject &Obj, 3371 const SubobjectDesignator &Sub, 3372 APValue &NewVal) { 3373 ModifySubobjectHandler Handler = { Info, NewVal, E }; 3374 return findSubobject(Info, E, Obj, Sub, Handler); 3375 } 3376 3377 /// Find the position where two subobject designators diverge, or equivalently 3378 /// the length of the common initial subsequence. 3379 static unsigned FindDesignatorMismatch(QualType ObjType, 3380 const SubobjectDesignator &A, 3381 const SubobjectDesignator &B, 3382 bool &WasArrayIndex) { 3383 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); 3384 for (/**/; I != N; ++I) { 3385 if (!ObjType.isNull() && 3386 (ObjType->isArrayType() || ObjType->isAnyComplexType())) { 3387 // Next subobject is an array element. 3388 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) { 3389 WasArrayIndex = true; 3390 return I; 3391 } 3392 if (ObjType->isAnyComplexType()) 3393 ObjType = ObjType->castAs<ComplexType>()->getElementType(); 3394 else 3395 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType(); 3396 } else { 3397 if (A.Entries[I].getAsBaseOrMember() != 3398 B.Entries[I].getAsBaseOrMember()) { 3399 WasArrayIndex = false; 3400 return I; 3401 } 3402 if (const FieldDecl *FD = getAsField(A.Entries[I])) 3403 // Next subobject is a field. 3404 ObjType = FD->getType(); 3405 else 3406 // Next subobject is a base class. 3407 ObjType = QualType(); 3408 } 3409 } 3410 WasArrayIndex = false; 3411 return I; 3412 } 3413 3414 /// Determine whether the given subobject designators refer to elements of the 3415 /// same array object. 3416 static bool AreElementsOfSameArray(QualType ObjType, 3417 const SubobjectDesignator &A, 3418 const SubobjectDesignator &B) { 3419 if (A.Entries.size() != B.Entries.size()) 3420 return false; 3421 3422 bool IsArray = A.MostDerivedIsArrayElement; 3423 if (IsArray && A.MostDerivedPathLength != A.Entries.size()) 3424 // A is a subobject of the array element. 3425 return false; 3426 3427 // If A (and B) designates an array element, the last entry will be the array 3428 // index. That doesn't have to match. Otherwise, we're in the 'implicit array 3429 // of length 1' case, and the entire path must match. 3430 bool WasArrayIndex; 3431 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex); 3432 return CommonLength >= A.Entries.size() - IsArray; 3433 } 3434 3435 /// Find the complete object to which an LValue refers. 3436 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, 3437 AccessKinds AK, const LValue &LVal, 3438 QualType LValType) { 3439 if (LVal.InvalidBase) { 3440 Info.FFDiag(E); 3441 return CompleteObject(); 3442 } 3443 3444 if (!LVal.Base) { 3445 Info.FFDiag(E, diag::note_constexpr_access_null) << AK; 3446 return CompleteObject(); 3447 } 3448 3449 CallStackFrame *Frame = nullptr; 3450 unsigned Depth = 0; 3451 if (LVal.getLValueCallIndex()) { 3452 std::tie(Frame, Depth) = 3453 Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); 3454 if (!Frame) { 3455 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) 3456 << AK << LVal.Base.is<const ValueDecl*>(); 3457 NoteLValueLocation(Info, LVal.Base); 3458 return CompleteObject(); 3459 } 3460 } 3461 3462 bool IsAccess = isAnyAccess(AK); 3463 3464 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type 3465 // is not a constant expression (even if the object is non-volatile). We also 3466 // apply this rule to C++98, in order to conform to the expected 'volatile' 3467 // semantics. 3468 if (isFormalAccess(AK) && LValType.isVolatileQualified()) { 3469 if (Info.getLangOpts().CPlusPlus) 3470 Info.FFDiag(E, diag::note_constexpr_access_volatile_type) 3471 << AK << LValType; 3472 else 3473 Info.FFDiag(E); 3474 return CompleteObject(); 3475 } 3476 3477 // Compute value storage location and type of base object. 3478 APValue *BaseVal = nullptr; 3479 QualType BaseType = getType(LVal.Base); 3480 3481 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) { 3482 // In C++98, const, non-volatile integers initialized with ICEs are ICEs. 3483 // In C++11, constexpr, non-volatile variables initialized with constant 3484 // expressions are constant expressions too. Inside constexpr functions, 3485 // parameters are constant expressions even if they're non-const. 3486 // In C++1y, objects local to a constant expression (those with a Frame) are 3487 // both readable and writable inside constant expressions. 3488 // In C, such things can also be folded, although they are not ICEs. 3489 const VarDecl *VD = dyn_cast<VarDecl>(D); 3490 if (VD) { 3491 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) 3492 VD = VDef; 3493 } 3494 if (!VD || VD->isInvalidDecl()) { 3495 Info.FFDiag(E); 3496 return CompleteObject(); 3497 } 3498 3499 // Unless we're looking at a local variable or argument in a constexpr call, 3500 // the variable we're reading must be const. 3501 if (!Frame) { 3502 if (Info.getLangOpts().CPlusPlus14 && 3503 lifetimeStartedInEvaluation(Info, LVal.Base)) { 3504 // OK, we can read and modify an object if we're in the process of 3505 // evaluating its initializer, because its lifetime began in this 3506 // evaluation. 3507 } else if (isModification(AK)) { 3508 // All the remaining cases do not permit modification of the object. 3509 Info.FFDiag(E, diag::note_constexpr_modify_global); 3510 return CompleteObject(); 3511 } else if (VD->isConstexpr()) { 3512 // OK, we can read this variable. 3513 } else if (BaseType->isIntegralOrEnumerationType()) { 3514 // In OpenCL if a variable is in constant address space it is a const 3515 // value. 3516 if (!(BaseType.isConstQualified() || 3517 (Info.getLangOpts().OpenCL && 3518 BaseType.getAddressSpace() == LangAS::opencl_constant))) { 3519 if (!IsAccess) 3520 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3521 if (Info.getLangOpts().CPlusPlus) { 3522 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD; 3523 Info.Note(VD->getLocation(), diag::note_declared_at); 3524 } else { 3525 Info.FFDiag(E); 3526 } 3527 return CompleteObject(); 3528 } 3529 } else if (!IsAccess) { 3530 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3531 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) { 3532 // We support folding of const floating-point types, in order to make 3533 // static const data members of such types (supported as an extension) 3534 // more useful. 3535 if (Info.getLangOpts().CPlusPlus11) { 3536 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3537 Info.Note(VD->getLocation(), diag::note_declared_at); 3538 } else { 3539 Info.CCEDiag(E); 3540 } 3541 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) { 3542 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD; 3543 // Keep evaluating to see what we can do. 3544 } else { 3545 // FIXME: Allow folding of values of any literal type in all languages. 3546 if (Info.checkingPotentialConstantExpression() && 3547 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) { 3548 // The definition of this variable could be constexpr. We can't 3549 // access it right now, but may be able to in future. 3550 } else if (Info.getLangOpts().CPlusPlus11) { 3551 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD; 3552 Info.Note(VD->getLocation(), diag::note_declared_at); 3553 } else { 3554 Info.FFDiag(E); 3555 } 3556 return CompleteObject(); 3557 } 3558 } 3559 3560 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal)) 3561 return CompleteObject(); 3562 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) { 3563 Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 3564 if (!Alloc) { 3565 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; 3566 return CompleteObject(); 3567 } 3568 return CompleteObject(LVal.Base, &(*Alloc)->Value, 3569 LVal.Base.getDynamicAllocType()); 3570 } else { 3571 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3572 3573 if (!Frame) { 3574 if (const MaterializeTemporaryExpr *MTE = 3575 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) { 3576 assert(MTE->getStorageDuration() == SD_Static && 3577 "should have a frame for a non-global materialized temporary"); 3578 3579 // Per C++1y [expr.const]p2: 3580 // an lvalue-to-rvalue conversion [is not allowed unless it applies to] 3581 // - a [...] glvalue of integral or enumeration type that refers to 3582 // a non-volatile const object [...] 3583 // [...] 3584 // - a [...] glvalue of literal type that refers to a non-volatile 3585 // object whose lifetime began within the evaluation of e. 3586 // 3587 // C++11 misses the 'began within the evaluation of e' check and 3588 // instead allows all temporaries, including things like: 3589 // int &&r = 1; 3590 // int x = ++r; 3591 // constexpr int k = r; 3592 // Therefore we use the C++14 rules in C++11 too. 3593 // 3594 // Note that temporaries whose lifetimes began while evaluating a 3595 // variable's constructor are not usable while evaluating the 3596 // corresponding destructor, not even if they're of const-qualified 3597 // types. 3598 if (!(BaseType.isConstQualified() && 3599 BaseType->isIntegralOrEnumerationType()) && 3600 !lifetimeStartedInEvaluation(Info, LVal.Base)) { 3601 if (!IsAccess) 3602 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3603 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK; 3604 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here); 3605 return CompleteObject(); 3606 } 3607 3608 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false); 3609 assert(BaseVal && "got reference to unevaluated temporary"); 3610 } else { 3611 if (!IsAccess) 3612 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType); 3613 APValue Val; 3614 LVal.moveInto(Val); 3615 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object) 3616 << AK 3617 << Val.getAsString(Info.Ctx, 3618 Info.Ctx.getLValueReferenceType(LValType)); 3619 NoteLValueLocation(Info, LVal.Base); 3620 return CompleteObject(); 3621 } 3622 } else { 3623 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion()); 3624 assert(BaseVal && "missing value for temporary"); 3625 } 3626 } 3627 3628 // In C++14, we can't safely access any mutable state when we might be 3629 // evaluating after an unmodeled side effect. 3630 // 3631 // FIXME: Not all local state is mutable. Allow local constant subobjects 3632 // to be read here (but take care with 'mutable' fields). 3633 if ((Frame && Info.getLangOpts().CPlusPlus14 && 3634 Info.EvalStatus.HasSideEffects) || 3635 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth)) 3636 return CompleteObject(); 3637 3638 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType); 3639 } 3640 3641 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This 3642 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the 3643 /// glvalue referred to by an entity of reference type. 3644 /// 3645 /// \param Info - Information about the ongoing evaluation. 3646 /// \param Conv - The expression for which we are performing the conversion. 3647 /// Used for diagnostics. 3648 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the 3649 /// case of a non-class type). 3650 /// \param LVal - The glvalue on which we are attempting to perform this action. 3651 /// \param RVal - The produced value will be placed here. 3652 /// \param WantObjectRepresentation - If true, we're looking for the object 3653 /// representation rather than the value, and in particular, 3654 /// there is no requirement that the result be fully initialized. 3655 static bool 3656 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, 3657 const LValue &LVal, APValue &RVal, 3658 bool WantObjectRepresentation = false) { 3659 if (LVal.Designator.Invalid) 3660 return false; 3661 3662 // Check for special cases where there is no existing APValue to look at. 3663 const Expr *Base = LVal.Base.dyn_cast<const Expr*>(); 3664 3665 AccessKinds AK = 3666 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; 3667 3668 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { 3669 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) { 3670 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the 3671 // initializer until now for such expressions. Such an expression can't be 3672 // an ICE in C, so this only matters for fold. 3673 if (Type.isVolatileQualified()) { 3674 Info.FFDiag(Conv); 3675 return false; 3676 } 3677 APValue Lit; 3678 if (!Evaluate(Lit, Info, CLE->getInitializer())) 3679 return false; 3680 CompleteObject LitObj(LVal.Base, &Lit, Base->getType()); 3681 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK); 3682 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) { 3683 // Special-case character extraction so we don't have to construct an 3684 // APValue for the whole string. 3685 assert(LVal.Designator.Entries.size() <= 1 && 3686 "Can only read characters from string literals"); 3687 if (LVal.Designator.Entries.empty()) { 3688 // Fail for now for LValue to RValue conversion of an array. 3689 // (This shouldn't show up in C/C++, but it could be triggered by a 3690 // weird EvaluateAsRValue call from a tool.) 3691 Info.FFDiag(Conv); 3692 return false; 3693 } 3694 if (LVal.Designator.isOnePastTheEnd()) { 3695 if (Info.getLangOpts().CPlusPlus11) 3696 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK; 3697 else 3698 Info.FFDiag(Conv); 3699 return false; 3700 } 3701 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex(); 3702 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex)); 3703 return true; 3704 } 3705 } 3706 3707 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type); 3708 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK); 3709 } 3710 3711 /// Perform an assignment of Val to LVal. Takes ownership of Val. 3712 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, 3713 QualType LValType, APValue &Val) { 3714 if (LVal.Designator.Invalid) 3715 return false; 3716 3717 if (!Info.getLangOpts().CPlusPlus14) { 3718 Info.FFDiag(E); 3719 return false; 3720 } 3721 3722 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3723 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val); 3724 } 3725 3726 namespace { 3727 struct CompoundAssignSubobjectHandler { 3728 EvalInfo &Info; 3729 const Expr *E; 3730 QualType PromotedLHSType; 3731 BinaryOperatorKind Opcode; 3732 const APValue &RHS; 3733 3734 static const AccessKinds AccessKind = AK_Assign; 3735 3736 typedef bool result_type; 3737 3738 bool checkConst(QualType QT) { 3739 // Assigning to a const object has undefined behavior. 3740 if (QT.isConstQualified()) { 3741 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3742 return false; 3743 } 3744 return true; 3745 } 3746 3747 bool failed() { return false; } 3748 bool found(APValue &Subobj, QualType SubobjType) { 3749 switch (Subobj.getKind()) { 3750 case APValue::Int: 3751 return found(Subobj.getInt(), SubobjType); 3752 case APValue::Float: 3753 return found(Subobj.getFloat(), SubobjType); 3754 case APValue::ComplexInt: 3755 case APValue::ComplexFloat: 3756 // FIXME: Implement complex compound assignment. 3757 Info.FFDiag(E); 3758 return false; 3759 case APValue::LValue: 3760 return foundPointer(Subobj, SubobjType); 3761 default: 3762 // FIXME: can this happen? 3763 Info.FFDiag(E); 3764 return false; 3765 } 3766 } 3767 bool found(APSInt &Value, QualType SubobjType) { 3768 if (!checkConst(SubobjType)) 3769 return false; 3770 3771 if (!SubobjType->isIntegerType()) { 3772 // We don't support compound assignment on integer-cast-to-pointer 3773 // values. 3774 Info.FFDiag(E); 3775 return false; 3776 } 3777 3778 if (RHS.isInt()) { 3779 APSInt LHS = 3780 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value); 3781 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS)) 3782 return false; 3783 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); 3784 return true; 3785 } else if (RHS.isFloat()) { 3786 APFloat FValue(0.0); 3787 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType, 3788 FValue) && 3789 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) && 3790 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType, 3791 Value); 3792 } 3793 3794 Info.FFDiag(E); 3795 return false; 3796 } 3797 bool found(APFloat &Value, QualType SubobjType) { 3798 return checkConst(SubobjType) && 3799 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType, 3800 Value) && 3801 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) && 3802 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value); 3803 } 3804 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3805 if (!checkConst(SubobjType)) 3806 return false; 3807 3808 QualType PointeeType; 3809 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3810 PointeeType = PT->getPointeeType(); 3811 3812 if (PointeeType.isNull() || !RHS.isInt() || 3813 (Opcode != BO_Add && Opcode != BO_Sub)) { 3814 Info.FFDiag(E); 3815 return false; 3816 } 3817 3818 APSInt Offset = RHS.getInt(); 3819 if (Opcode == BO_Sub) 3820 negateAsSigned(Offset); 3821 3822 LValue LVal; 3823 LVal.setFrom(Info.Ctx, Subobj); 3824 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset)) 3825 return false; 3826 LVal.moveInto(Subobj); 3827 return true; 3828 } 3829 }; 3830 } // end anonymous namespace 3831 3832 const AccessKinds CompoundAssignSubobjectHandler::AccessKind; 3833 3834 /// Perform a compound assignment of LVal <op>= RVal. 3835 static bool handleCompoundAssignment( 3836 EvalInfo &Info, const Expr *E, 3837 const LValue &LVal, QualType LValType, QualType PromotedLValType, 3838 BinaryOperatorKind Opcode, const APValue &RVal) { 3839 if (LVal.Designator.Invalid) 3840 return false; 3841 3842 if (!Info.getLangOpts().CPlusPlus14) { 3843 Info.FFDiag(E); 3844 return false; 3845 } 3846 3847 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); 3848 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, 3849 RVal }; 3850 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3851 } 3852 3853 namespace { 3854 struct IncDecSubobjectHandler { 3855 EvalInfo &Info; 3856 const UnaryOperator *E; 3857 AccessKinds AccessKind; 3858 APValue *Old; 3859 3860 typedef bool result_type; 3861 3862 bool checkConst(QualType QT) { 3863 // Assigning to a const object has undefined behavior. 3864 if (QT.isConstQualified()) { 3865 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT; 3866 return false; 3867 } 3868 return true; 3869 } 3870 3871 bool failed() { return false; } 3872 bool found(APValue &Subobj, QualType SubobjType) { 3873 // Stash the old value. Also clear Old, so we don't clobber it later 3874 // if we're post-incrementing a complex. 3875 if (Old) { 3876 *Old = Subobj; 3877 Old = nullptr; 3878 } 3879 3880 switch (Subobj.getKind()) { 3881 case APValue::Int: 3882 return found(Subobj.getInt(), SubobjType); 3883 case APValue::Float: 3884 return found(Subobj.getFloat(), SubobjType); 3885 case APValue::ComplexInt: 3886 return found(Subobj.getComplexIntReal(), 3887 SubobjType->castAs<ComplexType>()->getElementType() 3888 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3889 case APValue::ComplexFloat: 3890 return found(Subobj.getComplexFloatReal(), 3891 SubobjType->castAs<ComplexType>()->getElementType() 3892 .withCVRQualifiers(SubobjType.getCVRQualifiers())); 3893 case APValue::LValue: 3894 return foundPointer(Subobj, SubobjType); 3895 default: 3896 // FIXME: can this happen? 3897 Info.FFDiag(E); 3898 return false; 3899 } 3900 } 3901 bool found(APSInt &Value, QualType SubobjType) { 3902 if (!checkConst(SubobjType)) 3903 return false; 3904 3905 if (!SubobjType->isIntegerType()) { 3906 // We don't support increment / decrement on integer-cast-to-pointer 3907 // values. 3908 Info.FFDiag(E); 3909 return false; 3910 } 3911 3912 if (Old) *Old = APValue(Value); 3913 3914 // bool arithmetic promotes to int, and the conversion back to bool 3915 // doesn't reduce mod 2^n, so special-case it. 3916 if (SubobjType->isBooleanType()) { 3917 if (AccessKind == AK_Increment) 3918 Value = 1; 3919 else 3920 Value = !Value; 3921 return true; 3922 } 3923 3924 bool WasNegative = Value.isNegative(); 3925 if (AccessKind == AK_Increment) { 3926 ++Value; 3927 3928 if (!WasNegative && Value.isNegative() && E->canOverflow()) { 3929 APSInt ActualValue(Value, /*IsUnsigned*/true); 3930 return HandleOverflow(Info, E, ActualValue, SubobjType); 3931 } 3932 } else { 3933 --Value; 3934 3935 if (WasNegative && !Value.isNegative() && E->canOverflow()) { 3936 unsigned BitWidth = Value.getBitWidth(); 3937 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); 3938 ActualValue.setBit(BitWidth); 3939 return HandleOverflow(Info, E, ActualValue, SubobjType); 3940 } 3941 } 3942 return true; 3943 } 3944 bool found(APFloat &Value, QualType SubobjType) { 3945 if (!checkConst(SubobjType)) 3946 return false; 3947 3948 if (Old) *Old = APValue(Value); 3949 3950 APFloat One(Value.getSemantics(), 1); 3951 if (AccessKind == AK_Increment) 3952 Value.add(One, APFloat::rmNearestTiesToEven); 3953 else 3954 Value.subtract(One, APFloat::rmNearestTiesToEven); 3955 return true; 3956 } 3957 bool foundPointer(APValue &Subobj, QualType SubobjType) { 3958 if (!checkConst(SubobjType)) 3959 return false; 3960 3961 QualType PointeeType; 3962 if (const PointerType *PT = SubobjType->getAs<PointerType>()) 3963 PointeeType = PT->getPointeeType(); 3964 else { 3965 Info.FFDiag(E); 3966 return false; 3967 } 3968 3969 LValue LVal; 3970 LVal.setFrom(Info.Ctx, Subobj); 3971 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, 3972 AccessKind == AK_Increment ? 1 : -1)) 3973 return false; 3974 LVal.moveInto(Subobj); 3975 return true; 3976 } 3977 }; 3978 } // end anonymous namespace 3979 3980 /// Perform an increment or decrement on LVal. 3981 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, 3982 QualType LValType, bool IsIncrement, APValue *Old) { 3983 if (LVal.Designator.Invalid) 3984 return false; 3985 3986 if (!Info.getLangOpts().CPlusPlus14) { 3987 Info.FFDiag(E); 3988 return false; 3989 } 3990 3991 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement; 3992 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType); 3993 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old}; 3994 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); 3995 } 3996 3997 /// Build an lvalue for the object argument of a member function call. 3998 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, 3999 LValue &This) { 4000 if (Object->getType()->isPointerType()) 4001 return EvaluatePointer(Object, This, Info); 4002 4003 if (Object->isGLValue()) 4004 return EvaluateLValue(Object, This, Info); 4005 4006 if (Object->getType()->isLiteralType(Info.Ctx)) 4007 return EvaluateTemporary(Object, This, Info); 4008 4009 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType(); 4010 return false; 4011 } 4012 4013 /// HandleMemberPointerAccess - Evaluate a member access operation and build an 4014 /// lvalue referring to the result. 4015 /// 4016 /// \param Info - Information about the ongoing evaluation. 4017 /// \param LV - An lvalue referring to the base of the member pointer. 4018 /// \param RHS - The member pointer expression. 4019 /// \param IncludeMember - Specifies whether the member itself is included in 4020 /// the resulting LValue subobject designator. This is not possible when 4021 /// creating a bound member function. 4022 /// \return The field or method declaration to which the member pointer refers, 4023 /// or 0 if evaluation fails. 4024 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4025 QualType LVType, 4026 LValue &LV, 4027 const Expr *RHS, 4028 bool IncludeMember = true) { 4029 MemberPtr MemPtr; 4030 if (!EvaluateMemberPointer(RHS, MemPtr, Info)) 4031 return nullptr; 4032 4033 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to 4034 // member value, the behavior is undefined. 4035 if (!MemPtr.getDecl()) { 4036 // FIXME: Specific diagnostic. 4037 Info.FFDiag(RHS); 4038 return nullptr; 4039 } 4040 4041 if (MemPtr.isDerivedMember()) { 4042 // This is a member of some derived class. Truncate LV appropriately. 4043 // The end of the derived-to-base path for the base object must match the 4044 // derived-to-base path for the member pointer. 4045 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() > 4046 LV.Designator.Entries.size()) { 4047 Info.FFDiag(RHS); 4048 return nullptr; 4049 } 4050 unsigned PathLengthToMember = 4051 LV.Designator.Entries.size() - MemPtr.Path.size(); 4052 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { 4053 const CXXRecordDecl *LVDecl = getAsBaseClass( 4054 LV.Designator.Entries[PathLengthToMember + I]); 4055 const CXXRecordDecl *MPDecl = MemPtr.Path[I]; 4056 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { 4057 Info.FFDiag(RHS); 4058 return nullptr; 4059 } 4060 } 4061 4062 // Truncate the lvalue to the appropriate derived class. 4063 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(), 4064 PathLengthToMember)) 4065 return nullptr; 4066 } else if (!MemPtr.Path.empty()) { 4067 // Extend the LValue path with the member pointer's path. 4068 LV.Designator.Entries.reserve(LV.Designator.Entries.size() + 4069 MemPtr.Path.size() + IncludeMember); 4070 4071 // Walk down to the appropriate base class. 4072 if (const PointerType *PT = LVType->getAs<PointerType>()) 4073 LVType = PT->getPointeeType(); 4074 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); 4075 assert(RD && "member pointer access on non-class-type expression"); 4076 // The first class in the path is that of the lvalue. 4077 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { 4078 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; 4079 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) 4080 return nullptr; 4081 RD = Base; 4082 } 4083 // Finally cast to the class containing the member. 4084 if (!HandleLValueDirectBase(Info, RHS, LV, RD, 4085 MemPtr.getContainingRecord())) 4086 return nullptr; 4087 } 4088 4089 // Add the member. Note that we cannot build bound member functions here. 4090 if (IncludeMember) { 4091 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) { 4092 if (!HandleLValueMember(Info, RHS, LV, FD)) 4093 return nullptr; 4094 } else if (const IndirectFieldDecl *IFD = 4095 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) { 4096 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) 4097 return nullptr; 4098 } else { 4099 llvm_unreachable("can't construct reference to bound member function"); 4100 } 4101 } 4102 4103 return MemPtr.getDecl(); 4104 } 4105 4106 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, 4107 const BinaryOperator *BO, 4108 LValue &LV, 4109 bool IncludeMember = true) { 4110 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); 4111 4112 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) { 4113 if (Info.noteFailure()) { 4114 MemberPtr MemPtr; 4115 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info); 4116 } 4117 return nullptr; 4118 } 4119 4120 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV, 4121 BO->getRHS(), IncludeMember); 4122 } 4123 4124 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on 4125 /// the provided lvalue, which currently refers to the base object. 4126 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, 4127 LValue &Result) { 4128 SubobjectDesignator &D = Result.Designator; 4129 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) 4130 return false; 4131 4132 QualType TargetQT = E->getType(); 4133 if (const PointerType *PT = TargetQT->getAs<PointerType>()) 4134 TargetQT = PT->getPointeeType(); 4135 4136 // Check this cast lands within the final derived-to-base subobject path. 4137 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { 4138 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4139 << D.MostDerivedType << TargetQT; 4140 return false; 4141 } 4142 4143 // Check the type of the final cast. We don't need to check the path, 4144 // since a cast can only be formed if the path is unique. 4145 unsigned NewEntriesSize = D.Entries.size() - E->path_size(); 4146 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); 4147 const CXXRecordDecl *FinalType; 4148 if (NewEntriesSize == D.MostDerivedPathLength) 4149 FinalType = D.MostDerivedType->getAsCXXRecordDecl(); 4150 else 4151 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); 4152 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { 4153 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) 4154 << D.MostDerivedType << TargetQT; 4155 return false; 4156 } 4157 4158 // Truncate the lvalue to the appropriate derived class. 4159 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize); 4160 } 4161 4162 /// Get the value to use for a default-initialized object of type T. 4163 static APValue getDefaultInitValue(QualType T) { 4164 if (auto *RD = T->getAsCXXRecordDecl()) { 4165 if (RD->isUnion()) 4166 return APValue((const FieldDecl*)nullptr); 4167 4168 APValue Struct(APValue::UninitStruct(), RD->getNumBases(), 4169 std::distance(RD->field_begin(), RD->field_end())); 4170 4171 unsigned Index = 0; 4172 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 4173 End = RD->bases_end(); I != End; ++I, ++Index) 4174 Struct.getStructBase(Index) = getDefaultInitValue(I->getType()); 4175 4176 for (const auto *I : RD->fields()) { 4177 if (I->isUnnamedBitfield()) 4178 continue; 4179 Struct.getStructField(I->getFieldIndex()) = 4180 getDefaultInitValue(I->getType()); 4181 } 4182 return Struct; 4183 } 4184 4185 if (auto *AT = 4186 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) { 4187 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue()); 4188 if (Array.hasArrayFiller()) 4189 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType()); 4190 return Array; 4191 } 4192 4193 return APValue::IndeterminateValue(); 4194 } 4195 4196 namespace { 4197 enum EvalStmtResult { 4198 /// Evaluation failed. 4199 ESR_Failed, 4200 /// Hit a 'return' statement. 4201 ESR_Returned, 4202 /// Evaluation succeeded. 4203 ESR_Succeeded, 4204 /// Hit a 'continue' statement. 4205 ESR_Continue, 4206 /// Hit a 'break' statement. 4207 ESR_Break, 4208 /// Still scanning for 'case' or 'default' statement. 4209 ESR_CaseNotFound 4210 }; 4211 } 4212 4213 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { 4214 // We don't need to evaluate the initializer for a static local. 4215 if (!VD->hasLocalStorage()) 4216 return true; 4217 4218 LValue Result; 4219 APValue &Val = 4220 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result); 4221 4222 const Expr *InitE = VD->getInit(); 4223 if (!InitE) { 4224 Val = getDefaultInitValue(VD->getType()); 4225 return true; 4226 } 4227 4228 if (InitE->isValueDependent()) 4229 return false; 4230 4231 if (!EvaluateInPlace(Val, Info, Result, InitE)) { 4232 // Wipe out any partially-computed value, to allow tracking that this 4233 // evaluation failed. 4234 Val = APValue(); 4235 return false; 4236 } 4237 4238 return true; 4239 } 4240 4241 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { 4242 bool OK = true; 4243 4244 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 4245 OK &= EvaluateVarDecl(Info, VD); 4246 4247 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D)) 4248 for (auto *BD : DD->bindings()) 4249 if (auto *VD = BD->getHoldingVar()) 4250 OK &= EvaluateDecl(Info, VD); 4251 4252 return OK; 4253 } 4254 4255 4256 /// Evaluate a condition (either a variable declaration or an expression). 4257 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, 4258 const Expr *Cond, bool &Result) { 4259 FullExpressionRAII Scope(Info); 4260 if (CondDecl && !EvaluateDecl(Info, CondDecl)) 4261 return false; 4262 if (!EvaluateAsBooleanCondition(Cond, Result, Info)) 4263 return false; 4264 return Scope.destroy(); 4265 } 4266 4267 namespace { 4268 /// A location where the result (returned value) of evaluating a 4269 /// statement should be stored. 4270 struct StmtResult { 4271 /// The APValue that should be filled in with the returned value. 4272 APValue &Value; 4273 /// The location containing the result, if any (used to support RVO). 4274 const LValue *Slot; 4275 }; 4276 4277 struct TempVersionRAII { 4278 CallStackFrame &Frame; 4279 4280 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) { 4281 Frame.pushTempVersion(); 4282 } 4283 4284 ~TempVersionRAII() { 4285 Frame.popTempVersion(); 4286 } 4287 }; 4288 4289 } 4290 4291 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4292 const Stmt *S, 4293 const SwitchCase *SC = nullptr); 4294 4295 /// Evaluate the body of a loop, and translate the result as appropriate. 4296 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, 4297 const Stmt *Body, 4298 const SwitchCase *Case = nullptr) { 4299 BlockScopeRAII Scope(Info); 4300 4301 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); 4302 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4303 ESR = ESR_Failed; 4304 4305 switch (ESR) { 4306 case ESR_Break: 4307 return ESR_Succeeded; 4308 case ESR_Succeeded: 4309 case ESR_Continue: 4310 return ESR_Continue; 4311 case ESR_Failed: 4312 case ESR_Returned: 4313 case ESR_CaseNotFound: 4314 return ESR; 4315 } 4316 llvm_unreachable("Invalid EvalStmtResult!"); 4317 } 4318 4319 /// Evaluate a switch statement. 4320 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, 4321 const SwitchStmt *SS) { 4322 BlockScopeRAII Scope(Info); 4323 4324 // Evaluate the switch condition. 4325 APSInt Value; 4326 { 4327 if (const Stmt *Init = SS->getInit()) { 4328 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4329 if (ESR != ESR_Succeeded) { 4330 if (ESR != ESR_Failed && !Scope.destroy()) 4331 ESR = ESR_Failed; 4332 return ESR; 4333 } 4334 } 4335 4336 FullExpressionRAII CondScope(Info); 4337 if (SS->getConditionVariable() && 4338 !EvaluateDecl(Info, SS->getConditionVariable())) 4339 return ESR_Failed; 4340 if (!EvaluateInteger(SS->getCond(), Value, Info)) 4341 return ESR_Failed; 4342 if (!CondScope.destroy()) 4343 return ESR_Failed; 4344 } 4345 4346 // Find the switch case corresponding to the value of the condition. 4347 // FIXME: Cache this lookup. 4348 const SwitchCase *Found = nullptr; 4349 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; 4350 SC = SC->getNextSwitchCase()) { 4351 if (isa<DefaultStmt>(SC)) { 4352 Found = SC; 4353 continue; 4354 } 4355 4356 const CaseStmt *CS = cast<CaseStmt>(SC); 4357 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); 4358 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) 4359 : LHS; 4360 if (LHS <= Value && Value <= RHS) { 4361 Found = SC; 4362 break; 4363 } 4364 } 4365 4366 if (!Found) 4367 return Scope.destroy() ? ESR_Failed : ESR_Succeeded; 4368 4369 // Search the switch body for the switch case and evaluate it from there. 4370 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found); 4371 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy()) 4372 return ESR_Failed; 4373 4374 switch (ESR) { 4375 case ESR_Break: 4376 return ESR_Succeeded; 4377 case ESR_Succeeded: 4378 case ESR_Continue: 4379 case ESR_Failed: 4380 case ESR_Returned: 4381 return ESR; 4382 case ESR_CaseNotFound: 4383 // This can only happen if the switch case is nested within a statement 4384 // expression. We have no intention of supporting that. 4385 Info.FFDiag(Found->getBeginLoc(), 4386 diag::note_constexpr_stmt_expr_unsupported); 4387 return ESR_Failed; 4388 } 4389 llvm_unreachable("Invalid EvalStmtResult!"); 4390 } 4391 4392 // Evaluate a statement. 4393 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, 4394 const Stmt *S, const SwitchCase *Case) { 4395 if (!Info.nextStep(S)) 4396 return ESR_Failed; 4397 4398 // If we're hunting down a 'case' or 'default' label, recurse through 4399 // substatements until we hit the label. 4400 if (Case) { 4401 switch (S->getStmtClass()) { 4402 case Stmt::CompoundStmtClass: 4403 // FIXME: Precompute which substatement of a compound statement we 4404 // would jump to, and go straight there rather than performing a 4405 // linear scan each time. 4406 case Stmt::LabelStmtClass: 4407 case Stmt::AttributedStmtClass: 4408 case Stmt::DoStmtClass: 4409 break; 4410 4411 case Stmt::CaseStmtClass: 4412 case Stmt::DefaultStmtClass: 4413 if (Case == S) 4414 Case = nullptr; 4415 break; 4416 4417 case Stmt::IfStmtClass: { 4418 // FIXME: Precompute which side of an 'if' we would jump to, and go 4419 // straight there rather than scanning both sides. 4420 const IfStmt *IS = cast<IfStmt>(S); 4421 4422 // Wrap the evaluation in a block scope, in case it's a DeclStmt 4423 // preceded by our switch label. 4424 BlockScopeRAII Scope(Info); 4425 4426 // Step into the init statement in case it brings an (uninitialized) 4427 // variable into scope. 4428 if (const Stmt *Init = IS->getInit()) { 4429 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4430 if (ESR != ESR_CaseNotFound) { 4431 assert(ESR != ESR_Succeeded); 4432 return ESR; 4433 } 4434 } 4435 4436 // Condition variable must be initialized if it exists. 4437 // FIXME: We can skip evaluating the body if there's a condition 4438 // variable, as there can't be any case labels within it. 4439 // (The same is true for 'for' statements.) 4440 4441 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case); 4442 if (ESR == ESR_Failed) 4443 return ESR; 4444 if (ESR != ESR_CaseNotFound) 4445 return Scope.destroy() ? ESR : ESR_Failed; 4446 if (!IS->getElse()) 4447 return ESR_CaseNotFound; 4448 4449 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case); 4450 if (ESR == ESR_Failed) 4451 return ESR; 4452 if (ESR != ESR_CaseNotFound) 4453 return Scope.destroy() ? ESR : ESR_Failed; 4454 return ESR_CaseNotFound; 4455 } 4456 4457 case Stmt::WhileStmtClass: { 4458 EvalStmtResult ESR = 4459 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case); 4460 if (ESR != ESR_Continue) 4461 return ESR; 4462 break; 4463 } 4464 4465 case Stmt::ForStmtClass: { 4466 const ForStmt *FS = cast<ForStmt>(S); 4467 BlockScopeRAII Scope(Info); 4468 4469 // Step into the init statement in case it brings an (uninitialized) 4470 // variable into scope. 4471 if (const Stmt *Init = FS->getInit()) { 4472 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); 4473 if (ESR != ESR_CaseNotFound) { 4474 assert(ESR != ESR_Succeeded); 4475 return ESR; 4476 } 4477 } 4478 4479 EvalStmtResult ESR = 4480 EvaluateLoopBody(Result, Info, FS->getBody(), Case); 4481 if (ESR != ESR_Continue) 4482 return ESR; 4483 if (FS->getInc()) { 4484 FullExpressionRAII IncScope(Info); 4485 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4486 return ESR_Failed; 4487 } 4488 break; 4489 } 4490 4491 case Stmt::DeclStmtClass: { 4492 // Start the lifetime of any uninitialized variables we encounter. They 4493 // might be used by the selected branch of the switch. 4494 const DeclStmt *DS = cast<DeclStmt>(S); 4495 for (const auto *D : DS->decls()) { 4496 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4497 if (VD->hasLocalStorage() && !VD->getInit()) 4498 if (!EvaluateVarDecl(Info, VD)) 4499 return ESR_Failed; 4500 // FIXME: If the variable has initialization that can't be jumped 4501 // over, bail out of any immediately-surrounding compound-statement 4502 // too. There can't be any case labels here. 4503 } 4504 } 4505 return ESR_CaseNotFound; 4506 } 4507 4508 default: 4509 return ESR_CaseNotFound; 4510 } 4511 } 4512 4513 switch (S->getStmtClass()) { 4514 default: 4515 if (const Expr *E = dyn_cast<Expr>(S)) { 4516 // Don't bother evaluating beyond an expression-statement which couldn't 4517 // be evaluated. 4518 // FIXME: Do we need the FullExpressionRAII object here? 4519 // VisitExprWithCleanups should create one when necessary. 4520 FullExpressionRAII Scope(Info); 4521 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy()) 4522 return ESR_Failed; 4523 return ESR_Succeeded; 4524 } 4525 4526 Info.FFDiag(S->getBeginLoc()); 4527 return ESR_Failed; 4528 4529 case Stmt::NullStmtClass: 4530 return ESR_Succeeded; 4531 4532 case Stmt::DeclStmtClass: { 4533 const DeclStmt *DS = cast<DeclStmt>(S); 4534 for (const auto *D : DS->decls()) { 4535 // Each declaration initialization is its own full-expression. 4536 FullExpressionRAII Scope(Info); 4537 if (!EvaluateDecl(Info, D) && !Info.noteFailure()) 4538 return ESR_Failed; 4539 if (!Scope.destroy()) 4540 return ESR_Failed; 4541 } 4542 return ESR_Succeeded; 4543 } 4544 4545 case Stmt::ReturnStmtClass: { 4546 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue(); 4547 FullExpressionRAII Scope(Info); 4548 if (RetExpr && 4549 !(Result.Slot 4550 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) 4551 : Evaluate(Result.Value, Info, RetExpr))) 4552 return ESR_Failed; 4553 return Scope.destroy() ? ESR_Returned : ESR_Failed; 4554 } 4555 4556 case Stmt::CompoundStmtClass: { 4557 BlockScopeRAII Scope(Info); 4558 4559 const CompoundStmt *CS = cast<CompoundStmt>(S); 4560 for (const auto *BI : CS->body()) { 4561 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); 4562 if (ESR == ESR_Succeeded) 4563 Case = nullptr; 4564 else if (ESR != ESR_CaseNotFound) { 4565 if (ESR != ESR_Failed && !Scope.destroy()) 4566 return ESR_Failed; 4567 return ESR; 4568 } 4569 } 4570 if (Case) 4571 return ESR_CaseNotFound; 4572 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4573 } 4574 4575 case Stmt::IfStmtClass: { 4576 const IfStmt *IS = cast<IfStmt>(S); 4577 4578 // Evaluate the condition, as either a var decl or as an expression. 4579 BlockScopeRAII Scope(Info); 4580 if (const Stmt *Init = IS->getInit()) { 4581 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); 4582 if (ESR != ESR_Succeeded) { 4583 if (ESR != ESR_Failed && !Scope.destroy()) 4584 return ESR_Failed; 4585 return ESR; 4586 } 4587 } 4588 bool Cond; 4589 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) 4590 return ESR_Failed; 4591 4592 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { 4593 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); 4594 if (ESR != ESR_Succeeded) { 4595 if (ESR != ESR_Failed && !Scope.destroy()) 4596 return ESR_Failed; 4597 return ESR; 4598 } 4599 } 4600 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4601 } 4602 4603 case Stmt::WhileStmtClass: { 4604 const WhileStmt *WS = cast<WhileStmt>(S); 4605 while (true) { 4606 BlockScopeRAII Scope(Info); 4607 bool Continue; 4608 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(), 4609 Continue)) 4610 return ESR_Failed; 4611 if (!Continue) 4612 break; 4613 4614 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody()); 4615 if (ESR != ESR_Continue) { 4616 if (ESR != ESR_Failed && !Scope.destroy()) 4617 return ESR_Failed; 4618 return ESR; 4619 } 4620 if (!Scope.destroy()) 4621 return ESR_Failed; 4622 } 4623 return ESR_Succeeded; 4624 } 4625 4626 case Stmt::DoStmtClass: { 4627 const DoStmt *DS = cast<DoStmt>(S); 4628 bool Continue; 4629 do { 4630 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); 4631 if (ESR != ESR_Continue) 4632 return ESR; 4633 Case = nullptr; 4634 4635 FullExpressionRAII CondScope(Info); 4636 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) || 4637 !CondScope.destroy()) 4638 return ESR_Failed; 4639 } while (Continue); 4640 return ESR_Succeeded; 4641 } 4642 4643 case Stmt::ForStmtClass: { 4644 const ForStmt *FS = cast<ForStmt>(S); 4645 BlockScopeRAII ForScope(Info); 4646 if (FS->getInit()) { 4647 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4648 if (ESR != ESR_Succeeded) { 4649 if (ESR != ESR_Failed && !ForScope.destroy()) 4650 return ESR_Failed; 4651 return ESR; 4652 } 4653 } 4654 while (true) { 4655 BlockScopeRAII IterScope(Info); 4656 bool Continue = true; 4657 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(), 4658 FS->getCond(), Continue)) 4659 return ESR_Failed; 4660 if (!Continue) 4661 break; 4662 4663 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4664 if (ESR != ESR_Continue) { 4665 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy())) 4666 return ESR_Failed; 4667 return ESR; 4668 } 4669 4670 if (FS->getInc()) { 4671 FullExpressionRAII IncScope(Info); 4672 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy()) 4673 return ESR_Failed; 4674 } 4675 4676 if (!IterScope.destroy()) 4677 return ESR_Failed; 4678 } 4679 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed; 4680 } 4681 4682 case Stmt::CXXForRangeStmtClass: { 4683 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S); 4684 BlockScopeRAII Scope(Info); 4685 4686 // Evaluate the init-statement if present. 4687 if (FS->getInit()) { 4688 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); 4689 if (ESR != ESR_Succeeded) { 4690 if (ESR != ESR_Failed && !Scope.destroy()) 4691 return ESR_Failed; 4692 return ESR; 4693 } 4694 } 4695 4696 // Initialize the __range variable. 4697 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt()); 4698 if (ESR != ESR_Succeeded) { 4699 if (ESR != ESR_Failed && !Scope.destroy()) 4700 return ESR_Failed; 4701 return ESR; 4702 } 4703 4704 // Create the __begin and __end iterators. 4705 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt()); 4706 if (ESR != ESR_Succeeded) { 4707 if (ESR != ESR_Failed && !Scope.destroy()) 4708 return ESR_Failed; 4709 return ESR; 4710 } 4711 ESR = EvaluateStmt(Result, Info, FS->getEndStmt()); 4712 if (ESR != ESR_Succeeded) { 4713 if (ESR != ESR_Failed && !Scope.destroy()) 4714 return ESR_Failed; 4715 return ESR; 4716 } 4717 4718 while (true) { 4719 // Condition: __begin != __end. 4720 { 4721 bool Continue = true; 4722 FullExpressionRAII CondExpr(Info); 4723 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info)) 4724 return ESR_Failed; 4725 if (!Continue) 4726 break; 4727 } 4728 4729 // User's variable declaration, initialized by *__begin. 4730 BlockScopeRAII InnerScope(Info); 4731 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt()); 4732 if (ESR != ESR_Succeeded) { 4733 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 4734 return ESR_Failed; 4735 return ESR; 4736 } 4737 4738 // Loop body. 4739 ESR = EvaluateLoopBody(Result, Info, FS->getBody()); 4740 if (ESR != ESR_Continue) { 4741 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy())) 4742 return ESR_Failed; 4743 return ESR; 4744 } 4745 4746 // Increment: ++__begin 4747 if (!EvaluateIgnoredValue(Info, FS->getInc())) 4748 return ESR_Failed; 4749 4750 if (!InnerScope.destroy()) 4751 return ESR_Failed; 4752 } 4753 4754 return Scope.destroy() ? ESR_Succeeded : ESR_Failed; 4755 } 4756 4757 case Stmt::SwitchStmtClass: 4758 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S)); 4759 4760 case Stmt::ContinueStmtClass: 4761 return ESR_Continue; 4762 4763 case Stmt::BreakStmtClass: 4764 return ESR_Break; 4765 4766 case Stmt::LabelStmtClass: 4767 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case); 4768 4769 case Stmt::AttributedStmtClass: 4770 // As a general principle, C++11 attributes can be ignored without 4771 // any semantic impact. 4772 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(), 4773 Case); 4774 4775 case Stmt::CaseStmtClass: 4776 case Stmt::DefaultStmtClass: 4777 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case); 4778 case Stmt::CXXTryStmtClass: 4779 // Evaluate try blocks by evaluating all sub statements. 4780 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case); 4781 } 4782 } 4783 4784 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial 4785 /// default constructor. If so, we'll fold it whether or not it's marked as 4786 /// constexpr. If it is marked as constexpr, we will never implicitly define it, 4787 /// so we need special handling. 4788 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, 4789 const CXXConstructorDecl *CD, 4790 bool IsValueInitialization) { 4791 if (!CD->isTrivial() || !CD->isDefaultConstructor()) 4792 return false; 4793 4794 // Value-initialization does not call a trivial default constructor, so such a 4795 // call is a core constant expression whether or not the constructor is 4796 // constexpr. 4797 if (!CD->isConstexpr() && !IsValueInitialization) { 4798 if (Info.getLangOpts().CPlusPlus11) { 4799 // FIXME: If DiagDecl is an implicitly-declared special member function, 4800 // we should be much more explicit about why it's not constexpr. 4801 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) 4802 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; 4803 Info.Note(CD->getLocation(), diag::note_declared_at); 4804 } else { 4805 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); 4806 } 4807 } 4808 return true; 4809 } 4810 4811 /// CheckConstexprFunction - Check that a function can be called in a constant 4812 /// expression. 4813 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, 4814 const FunctionDecl *Declaration, 4815 const FunctionDecl *Definition, 4816 const Stmt *Body) { 4817 // Potential constant expressions can contain calls to declared, but not yet 4818 // defined, constexpr functions. 4819 if (Info.checkingPotentialConstantExpression() && !Definition && 4820 Declaration->isConstexpr()) 4821 return false; 4822 4823 // Bail out if the function declaration itself is invalid. We will 4824 // have produced a relevant diagnostic while parsing it, so just 4825 // note the problematic sub-expression. 4826 if (Declaration->isInvalidDecl()) { 4827 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4828 return false; 4829 } 4830 4831 // DR1872: An instantiated virtual constexpr function can't be called in a 4832 // constant expression (prior to C++20). We can still constant-fold such a 4833 // call. 4834 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) && 4835 cast<CXXMethodDecl>(Declaration)->isVirtual()) 4836 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call); 4837 4838 if (Definition && Definition->isInvalidDecl()) { 4839 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4840 return false; 4841 } 4842 4843 // Can we evaluate this function call? 4844 if (Definition && Definition->isConstexpr() && Body) 4845 return true; 4846 4847 if (Info.getLangOpts().CPlusPlus11) { 4848 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; 4849 4850 // If this function is not constexpr because it is an inherited 4851 // non-constexpr constructor, diagnose that directly. 4852 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl); 4853 if (CD && CD->isInheritingConstructor()) { 4854 auto *Inherited = CD->getInheritedConstructor().getConstructor(); 4855 if (!Inherited->isConstexpr()) 4856 DiagDecl = CD = Inherited; 4857 } 4858 4859 // FIXME: If DiagDecl is an implicitly-declared special member function 4860 // or an inheriting constructor, we should be much more explicit about why 4861 // it's not constexpr. 4862 if (CD && CD->isInheritingConstructor()) 4863 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) 4864 << CD->getInheritedConstructor().getConstructor()->getParent(); 4865 else 4866 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) 4867 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; 4868 Info.Note(DiagDecl->getLocation(), diag::note_declared_at); 4869 } else { 4870 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); 4871 } 4872 return false; 4873 } 4874 4875 namespace { 4876 struct CheckDynamicTypeHandler { 4877 AccessKinds AccessKind; 4878 typedef bool result_type; 4879 bool failed() { return false; } 4880 bool found(APValue &Subobj, QualType SubobjType) { return true; } 4881 bool found(APSInt &Value, QualType SubobjType) { return true; } 4882 bool found(APFloat &Value, QualType SubobjType) { return true; } 4883 }; 4884 } // end anonymous namespace 4885 4886 /// Check that we can access the notional vptr of an object / determine its 4887 /// dynamic type. 4888 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, 4889 AccessKinds AK, bool Polymorphic) { 4890 if (This.Designator.Invalid) 4891 return false; 4892 4893 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType()); 4894 4895 if (!Obj) 4896 return false; 4897 4898 if (!Obj.Value) { 4899 // The object is not usable in constant expressions, so we can't inspect 4900 // its value to see if it's in-lifetime or what the active union members 4901 // are. We can still check for a one-past-the-end lvalue. 4902 if (This.Designator.isOnePastTheEnd() || 4903 This.Designator.isMostDerivedAnUnsizedArray()) { 4904 Info.FFDiag(E, This.Designator.isOnePastTheEnd() 4905 ? diag::note_constexpr_access_past_end 4906 : diag::note_constexpr_access_unsized_array) 4907 << AK; 4908 return false; 4909 } else if (Polymorphic) { 4910 // Conservatively refuse to perform a polymorphic operation if we would 4911 // not be able to read a notional 'vptr' value. 4912 APValue Val; 4913 This.moveInto(Val); 4914 QualType StarThisType = 4915 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx)); 4916 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type) 4917 << AK << Val.getAsString(Info.Ctx, StarThisType); 4918 return false; 4919 } 4920 return true; 4921 } 4922 4923 CheckDynamicTypeHandler Handler{AK}; 4924 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 4925 } 4926 4927 /// Check that the pointee of the 'this' pointer in a member function call is 4928 /// either within its lifetime or in its period of construction or destruction. 4929 static bool 4930 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, 4931 const LValue &This, 4932 const CXXMethodDecl *NamedMember) { 4933 return checkDynamicType( 4934 Info, E, This, 4935 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false); 4936 } 4937 4938 struct DynamicType { 4939 /// The dynamic class type of the object. 4940 const CXXRecordDecl *Type; 4941 /// The corresponding path length in the lvalue. 4942 unsigned PathLength; 4943 }; 4944 4945 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, 4946 unsigned PathLength) { 4947 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= 4948 Designator.Entries.size() && "invalid path length"); 4949 return (PathLength == Designator.MostDerivedPathLength) 4950 ? Designator.MostDerivedType->getAsCXXRecordDecl() 4951 : getAsBaseClass(Designator.Entries[PathLength - 1]); 4952 } 4953 4954 /// Determine the dynamic type of an object. 4955 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E, 4956 LValue &This, AccessKinds AK) { 4957 // If we don't have an lvalue denoting an object of class type, there is no 4958 // meaningful dynamic type. (We consider objects of non-class type to have no 4959 // dynamic type.) 4960 if (!checkDynamicType(Info, E, This, AK, true)) 4961 return None; 4962 4963 // Refuse to compute a dynamic type in the presence of virtual bases. This 4964 // shouldn't happen other than in constant-folding situations, since literal 4965 // types can't have virtual bases. 4966 // 4967 // Note that consumers of DynamicType assume that the type has no virtual 4968 // bases, and will need modifications if this restriction is relaxed. 4969 const CXXRecordDecl *Class = 4970 This.Designator.MostDerivedType->getAsCXXRecordDecl(); 4971 if (!Class || Class->getNumVBases()) { 4972 Info.FFDiag(E); 4973 return None; 4974 } 4975 4976 // FIXME: For very deep class hierarchies, it might be beneficial to use a 4977 // binary search here instead. But the overwhelmingly common case is that 4978 // we're not in the middle of a constructor, so it probably doesn't matter 4979 // in practice. 4980 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries; 4981 for (unsigned PathLength = This.Designator.MostDerivedPathLength; 4982 PathLength <= Path.size(); ++PathLength) { 4983 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(), 4984 Path.slice(0, PathLength))) { 4985 case ConstructionPhase::Bases: 4986 case ConstructionPhase::DestroyingBases: 4987 // We're constructing or destroying a base class. This is not the dynamic 4988 // type. 4989 break; 4990 4991 case ConstructionPhase::None: 4992 case ConstructionPhase::AfterBases: 4993 case ConstructionPhase::Destroying: 4994 // We've finished constructing the base classes and not yet started 4995 // destroying them again, so this is the dynamic type. 4996 return DynamicType{getBaseClassType(This.Designator, PathLength), 4997 PathLength}; 4998 } 4999 } 5000 5001 // CWG issue 1517: we're constructing a base class of the object described by 5002 // 'This', so that object has not yet begun its period of construction and 5003 // any polymorphic operation on it results in undefined behavior. 5004 Info.FFDiag(E); 5005 return None; 5006 } 5007 5008 /// Perform virtual dispatch. 5009 static const CXXMethodDecl *HandleVirtualDispatch( 5010 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, 5011 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) { 5012 Optional<DynamicType> DynType = ComputeDynamicType( 5013 Info, E, This, 5014 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall); 5015 if (!DynType) 5016 return nullptr; 5017 5018 // Find the final overrider. It must be declared in one of the classes on the 5019 // path from the dynamic type to the static type. 5020 // FIXME: If we ever allow literal types to have virtual base classes, that 5021 // won't be true. 5022 const CXXMethodDecl *Callee = Found; 5023 unsigned PathLength = DynType->PathLength; 5024 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { 5025 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); 5026 const CXXMethodDecl *Overrider = 5027 Found->getCorrespondingMethodDeclaredInClass(Class, false); 5028 if (Overrider) { 5029 Callee = Overrider; 5030 break; 5031 } 5032 } 5033 5034 // C++2a [class.abstract]p6: 5035 // the effect of making a virtual call to a pure virtual function [...] is 5036 // undefined 5037 if (Callee->isPure()) { 5038 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee; 5039 Info.Note(Callee->getLocation(), diag::note_declared_at); 5040 return nullptr; 5041 } 5042 5043 // If necessary, walk the rest of the path to determine the sequence of 5044 // covariant adjustment steps to apply. 5045 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(), 5046 Found->getReturnType())) { 5047 CovariantAdjustmentPath.push_back(Callee->getReturnType()); 5048 for (unsigned CovariantPathLength = PathLength + 1; 5049 CovariantPathLength != This.Designator.Entries.size(); 5050 ++CovariantPathLength) { 5051 const CXXRecordDecl *NextClass = 5052 getBaseClassType(This.Designator, CovariantPathLength); 5053 const CXXMethodDecl *Next = 5054 Found->getCorrespondingMethodDeclaredInClass(NextClass, false); 5055 if (Next && !Info.Ctx.hasSameUnqualifiedType( 5056 Next->getReturnType(), CovariantAdjustmentPath.back())) 5057 CovariantAdjustmentPath.push_back(Next->getReturnType()); 5058 } 5059 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(), 5060 CovariantAdjustmentPath.back())) 5061 CovariantAdjustmentPath.push_back(Found->getReturnType()); 5062 } 5063 5064 // Perform 'this' adjustment. 5065 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength)) 5066 return nullptr; 5067 5068 return Callee; 5069 } 5070 5071 /// Perform the adjustment from a value returned by a virtual function to 5072 /// a value of the statically expected type, which may be a pointer or 5073 /// reference to a base class of the returned type. 5074 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, 5075 APValue &Result, 5076 ArrayRef<QualType> Path) { 5077 assert(Result.isLValue() && 5078 "unexpected kind of APValue for covariant return"); 5079 if (Result.isNullPointer()) 5080 return true; 5081 5082 LValue LVal; 5083 LVal.setFrom(Info.Ctx, Result); 5084 5085 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); 5086 for (unsigned I = 1; I != Path.size(); ++I) { 5087 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); 5088 assert(OldClass && NewClass && "unexpected kind of covariant return"); 5089 if (OldClass != NewClass && 5090 !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) 5091 return false; 5092 OldClass = NewClass; 5093 } 5094 5095 LVal.moveInto(Result); 5096 return true; 5097 } 5098 5099 /// Determine whether \p Base, which is known to be a direct base class of 5100 /// \p Derived, is a public base class. 5101 static bool isBaseClassPublic(const CXXRecordDecl *Derived, 5102 const CXXRecordDecl *Base) { 5103 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { 5104 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); 5105 if (BaseClass && declaresSameEntity(BaseClass, Base)) 5106 return BaseSpec.getAccessSpecifier() == AS_public; 5107 } 5108 llvm_unreachable("Base is not a direct base of Derived"); 5109 } 5110 5111 /// Apply the given dynamic cast operation on the provided lvalue. 5112 /// 5113 /// This implements the hard case of dynamic_cast, requiring a "runtime check" 5114 /// to find a suitable target subobject. 5115 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, 5116 LValue &Ptr) { 5117 // We can't do anything with a non-symbolic pointer value. 5118 SubobjectDesignator &D = Ptr.Designator; 5119 if (D.Invalid) 5120 return false; 5121 5122 // C++ [expr.dynamic.cast]p6: 5123 // If v is a null pointer value, the result is a null pointer value. 5124 if (Ptr.isNullPointer() && !E->isGLValue()) 5125 return true; 5126 5127 // For all the other cases, we need the pointer to point to an object within 5128 // its lifetime / period of construction / destruction, and we need to know 5129 // its dynamic type. 5130 Optional<DynamicType> DynType = 5131 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast); 5132 if (!DynType) 5133 return false; 5134 5135 // C++ [expr.dynamic.cast]p7: 5136 // If T is "pointer to cv void", then the result is a pointer to the most 5137 // derived object 5138 if (E->getType()->isVoidPointerType()) 5139 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); 5140 5141 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); 5142 assert(C && "dynamic_cast target is not void pointer nor class"); 5143 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); 5144 5145 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { 5146 // C++ [expr.dynamic.cast]p9: 5147 if (!E->isGLValue()) { 5148 // The value of a failed cast to pointer type is the null pointer value 5149 // of the required result type. 5150 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 5151 Ptr.setNull(E->getType(), TargetVal); 5152 return true; 5153 } 5154 5155 // A failed cast to reference type throws [...] std::bad_cast. 5156 unsigned DiagKind; 5157 if (!Paths && (declaresSameEntity(DynType->Type, C) || 5158 DynType->Type->isDerivedFrom(C))) 5159 DiagKind = 0; 5160 else if (!Paths || Paths->begin() == Paths->end()) 5161 DiagKind = 1; 5162 else if (Paths->isAmbiguous(CQT)) 5163 DiagKind = 2; 5164 else { 5165 assert(Paths->front().Access != AS_public && "why did the cast fail?"); 5166 DiagKind = 3; 5167 } 5168 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed) 5169 << DiagKind << Ptr.Designator.getType(Info.Ctx) 5170 << Info.Ctx.getRecordType(DynType->Type) 5171 << E->getType().getUnqualifiedType(); 5172 return false; 5173 }; 5174 5175 // Runtime check, phase 1: 5176 // Walk from the base subobject towards the derived object looking for the 5177 // target type. 5178 for (int PathLength = Ptr.Designator.Entries.size(); 5179 PathLength >= (int)DynType->PathLength; --PathLength) { 5180 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); 5181 if (declaresSameEntity(Class, C)) 5182 return CastToDerivedClass(Info, E, Ptr, Class, PathLength); 5183 // We can only walk across public inheritance edges. 5184 if (PathLength > (int)DynType->PathLength && 5185 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1), 5186 Class)) 5187 return RuntimeCheckFailed(nullptr); 5188 } 5189 5190 // Runtime check, phase 2: 5191 // Search the dynamic type for an unambiguous public base of type C. 5192 CXXBasePaths Paths(/*FindAmbiguities=*/true, 5193 /*RecordPaths=*/true, /*DetectVirtual=*/false); 5194 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) && 5195 Paths.front().Access == AS_public) { 5196 // Downcast to the dynamic type... 5197 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength)) 5198 return false; 5199 // ... then upcast to the chosen base class subobject. 5200 for (CXXBasePathElement &Elem : Paths.front()) 5201 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base)) 5202 return false; 5203 return true; 5204 } 5205 5206 // Otherwise, the runtime check fails. 5207 return RuntimeCheckFailed(&Paths); 5208 } 5209 5210 namespace { 5211 struct StartLifetimeOfUnionMemberHandler { 5212 const FieldDecl *Field; 5213 5214 static const AccessKinds AccessKind = AK_Assign; 5215 5216 typedef bool result_type; 5217 bool failed() { return false; } 5218 bool found(APValue &Subobj, QualType SubobjType) { 5219 // We are supposed to perform no initialization but begin the lifetime of 5220 // the object. We interpret that as meaning to do what default 5221 // initialization of the object would do if all constructors involved were 5222 // trivial: 5223 // * All base, non-variant member, and array element subobjects' lifetimes 5224 // begin 5225 // * No variant members' lifetimes begin 5226 // * All scalar subobjects whose lifetimes begin have indeterminate values 5227 assert(SubobjType->isUnionType()); 5228 if (!declaresSameEntity(Subobj.getUnionField(), Field) || 5229 !Subobj.getUnionValue().hasValue()) 5230 Subobj.setUnion(Field, getDefaultInitValue(Field->getType())); 5231 return true; 5232 } 5233 bool found(APSInt &Value, QualType SubobjType) { 5234 llvm_unreachable("wrong value kind for union object"); 5235 } 5236 bool found(APFloat &Value, QualType SubobjType) { 5237 llvm_unreachable("wrong value kind for union object"); 5238 } 5239 }; 5240 } // end anonymous namespace 5241 5242 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind; 5243 5244 /// Handle a builtin simple-assignment or a call to a trivial assignment 5245 /// operator whose left-hand side might involve a union member access. If it 5246 /// does, implicitly start the lifetime of any accessed union elements per 5247 /// C++20 [class.union]5. 5248 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, 5249 const LValue &LHS) { 5250 if (LHS.InvalidBase || LHS.Designator.Invalid) 5251 return false; 5252 5253 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths; 5254 // C++ [class.union]p5: 5255 // define the set S(E) of subexpressions of E as follows: 5256 unsigned PathLength = LHS.Designator.Entries.size(); 5257 for (const Expr *E = LHSExpr; E != nullptr;) { 5258 // -- If E is of the form A.B, S(E) contains the elements of S(A)... 5259 if (auto *ME = dyn_cast<MemberExpr>(E)) { 5260 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 5261 // Note that we can't implicitly start the lifetime of a reference, 5262 // so we don't need to proceed any further if we reach one. 5263 if (!FD || FD->getType()->isReferenceType()) 5264 break; 5265 5266 // ... and also contains A.B if B names a union member 5267 if (FD->getParent()->isUnion()) 5268 UnionPathLengths.push_back({PathLength - 1, FD}); 5269 5270 E = ME->getBase(); 5271 --PathLength; 5272 assert(declaresSameEntity(FD, 5273 LHS.Designator.Entries[PathLength] 5274 .getAsBaseOrMember().getPointer())); 5275 5276 // -- If E is of the form A[B] and is interpreted as a built-in array 5277 // subscripting operator, S(E) is [S(the array operand, if any)]. 5278 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) { 5279 // Step over an ArrayToPointerDecay implicit cast. 5280 auto *Base = ASE->getBase()->IgnoreImplicit(); 5281 if (!Base->getType()->isArrayType()) 5282 break; 5283 5284 E = Base; 5285 --PathLength; 5286 5287 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) { 5288 // Step over a derived-to-base conversion. 5289 E = ICE->getSubExpr(); 5290 if (ICE->getCastKind() == CK_NoOp) 5291 continue; 5292 if (ICE->getCastKind() != CK_DerivedToBase && 5293 ICE->getCastKind() != CK_UncheckedDerivedToBase) 5294 break; 5295 // Walk path backwards as we walk up from the base to the derived class. 5296 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { 5297 --PathLength; 5298 (void)Elt; 5299 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), 5300 LHS.Designator.Entries[PathLength] 5301 .getAsBaseOrMember().getPointer())); 5302 } 5303 5304 // -- Otherwise, S(E) is empty. 5305 } else { 5306 break; 5307 } 5308 } 5309 5310 // Common case: no unions' lifetimes are started. 5311 if (UnionPathLengths.empty()) 5312 return true; 5313 5314 // if modification of X [would access an inactive union member], an object 5315 // of the type of X is implicitly created 5316 CompleteObject Obj = 5317 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); 5318 if (!Obj) 5319 return false; 5320 for (std::pair<unsigned, const FieldDecl *> LengthAndField : 5321 llvm::reverse(UnionPathLengths)) { 5322 // Form a designator for the union object. 5323 SubobjectDesignator D = LHS.Designator; 5324 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); 5325 5326 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second}; 5327 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime)) 5328 return false; 5329 } 5330 5331 return true; 5332 } 5333 5334 /// Determine if a class has any fields that might need to be copied by a 5335 /// trivial copy or move operation. 5336 static bool hasFields(const CXXRecordDecl *RD) { 5337 if (!RD || RD->isEmpty()) 5338 return false; 5339 for (auto *FD : RD->fields()) { 5340 if (FD->isUnnamedBitfield()) 5341 continue; 5342 return true; 5343 } 5344 for (auto &Base : RD->bases()) 5345 if (hasFields(Base.getType()->getAsCXXRecordDecl())) 5346 return true; 5347 return false; 5348 } 5349 5350 namespace { 5351 typedef SmallVector<APValue, 8> ArgVector; 5352 } 5353 5354 /// EvaluateArgs - Evaluate the arguments to a function call. 5355 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues, 5356 EvalInfo &Info, const FunctionDecl *Callee) { 5357 bool Success = true; 5358 llvm::SmallBitVector ForbiddenNullArgs; 5359 if (Callee->hasAttr<NonNullAttr>()) { 5360 ForbiddenNullArgs.resize(Args.size()); 5361 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) { 5362 if (!Attr->args_size()) { 5363 ForbiddenNullArgs.set(); 5364 break; 5365 } else 5366 for (auto Idx : Attr->args()) { 5367 unsigned ASTIdx = Idx.getASTIndex(); 5368 if (ASTIdx >= Args.size()) 5369 continue; 5370 ForbiddenNullArgs[ASTIdx] = 1; 5371 } 5372 } 5373 } 5374 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 5375 I != E; ++I) { 5376 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) { 5377 // If we're checking for a potential constant expression, evaluate all 5378 // initializers even if some of them fail. 5379 if (!Info.noteFailure()) 5380 return false; 5381 Success = false; 5382 } else if (!ForbiddenNullArgs.empty() && 5383 ForbiddenNullArgs[I - Args.begin()] && 5384 ArgValues[I - Args.begin()].isNullPointer()) { 5385 Info.CCEDiag(*I, diag::note_non_null_attribute_failed); 5386 if (!Info.noteFailure()) 5387 return false; 5388 Success = false; 5389 } 5390 } 5391 return Success; 5392 } 5393 5394 /// Evaluate a function call. 5395 static bool HandleFunctionCall(SourceLocation CallLoc, 5396 const FunctionDecl *Callee, const LValue *This, 5397 ArrayRef<const Expr*> Args, const Stmt *Body, 5398 EvalInfo &Info, APValue &Result, 5399 const LValue *ResultSlot) { 5400 ArgVector ArgValues(Args.size()); 5401 if (!EvaluateArgs(Args, ArgValues, Info, Callee)) 5402 return false; 5403 5404 if (!Info.CheckCallLimit(CallLoc)) 5405 return false; 5406 5407 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data()); 5408 5409 // For a trivial copy or move assignment, perform an APValue copy. This is 5410 // essential for unions, where the operations performed by the assignment 5411 // operator cannot be represented as statements. 5412 // 5413 // Skip this for non-union classes with no fields; in that case, the defaulted 5414 // copy/move does not actually read the object. 5415 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee); 5416 if (MD && MD->isDefaulted() && 5417 (MD->getParent()->isUnion() || 5418 (MD->isTrivial() && hasFields(MD->getParent())))) { 5419 assert(This && 5420 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())); 5421 LValue RHS; 5422 RHS.setFrom(Info.Ctx, ArgValues[0]); 5423 APValue RHSValue; 5424 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS, 5425 RHSValue, MD->getParent()->isUnion())) 5426 return false; 5427 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() && 5428 !HandleUnionActiveMemberChange(Info, Args[0], *This)) 5429 return false; 5430 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), 5431 RHSValue)) 5432 return false; 5433 This->moveInto(Result); 5434 return true; 5435 } else if (MD && isLambdaCallOperator(MD)) { 5436 // We're in a lambda; determine the lambda capture field maps unless we're 5437 // just constexpr checking a lambda's call operator. constexpr checking is 5438 // done before the captures have been added to the closure object (unless 5439 // we're inferring constexpr-ness), so we don't have access to them in this 5440 // case. But since we don't need the captures to constexpr check, we can 5441 // just ignore them. 5442 if (!Info.checkingPotentialConstantExpression()) 5443 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields, 5444 Frame.LambdaThisCaptureField); 5445 } 5446 5447 StmtResult Ret = {Result, ResultSlot}; 5448 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body); 5449 if (ESR == ESR_Succeeded) { 5450 if (Callee->getReturnType()->isVoidType()) 5451 return true; 5452 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return); 5453 } 5454 return ESR == ESR_Returned; 5455 } 5456 5457 /// Evaluate a constructor call. 5458 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5459 APValue *ArgValues, 5460 const CXXConstructorDecl *Definition, 5461 EvalInfo &Info, APValue &Result) { 5462 SourceLocation CallLoc = E->getExprLoc(); 5463 if (!Info.CheckCallLimit(CallLoc)) 5464 return false; 5465 5466 const CXXRecordDecl *RD = Definition->getParent(); 5467 if (RD->getNumVBases()) { 5468 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5469 return false; 5470 } 5471 5472 EvalInfo::EvaluatingConstructorRAII EvalObj( 5473 Info, 5474 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 5475 RD->getNumBases()); 5476 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues); 5477 5478 // FIXME: Creating an APValue just to hold a nonexistent return value is 5479 // wasteful. 5480 APValue RetVal; 5481 StmtResult Ret = {RetVal, nullptr}; 5482 5483 // If it's a delegating constructor, delegate. 5484 if (Definition->isDelegatingConstructor()) { 5485 CXXConstructorDecl::init_const_iterator I = Definition->init_begin(); 5486 { 5487 FullExpressionRAII InitScope(Info); 5488 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) || 5489 !InitScope.destroy()) 5490 return false; 5491 } 5492 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed; 5493 } 5494 5495 // For a trivial copy or move constructor, perform an APValue copy. This is 5496 // essential for unions (or classes with anonymous union members), where the 5497 // operations performed by the constructor cannot be represented by 5498 // ctor-initializers. 5499 // 5500 // Skip this for empty non-union classes; we should not perform an 5501 // lvalue-to-rvalue conversion on them because their copy constructor does not 5502 // actually read them. 5503 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() && 5504 (Definition->getParent()->isUnion() || 5505 (Definition->isTrivial() && hasFields(Definition->getParent())))) { 5506 LValue RHS; 5507 RHS.setFrom(Info.Ctx, ArgValues[0]); 5508 return handleLValueToRValueConversion( 5509 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(), 5510 RHS, Result, Definition->getParent()->isUnion()); 5511 } 5512 5513 // Reserve space for the struct members. 5514 if (!RD->isUnion() && !Result.hasValue()) 5515 Result = APValue(APValue::UninitStruct(), RD->getNumBases(), 5516 std::distance(RD->field_begin(), RD->field_end())); 5517 5518 if (RD->isInvalidDecl()) return false; 5519 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5520 5521 // A scope for temporaries lifetime-extended by reference members. 5522 BlockScopeRAII LifetimeExtendedScope(Info); 5523 5524 bool Success = true; 5525 unsigned BasesSeen = 0; 5526 #ifndef NDEBUG 5527 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin(); 5528 #endif 5529 CXXRecordDecl::field_iterator FieldIt = RD->field_begin(); 5530 auto SkipToField = [&](FieldDecl *FD, bool Indirect) { 5531 // We might be initializing the same field again if this is an indirect 5532 // field initialization. 5533 if (FieldIt == RD->field_end() || 5534 FieldIt->getFieldIndex() > FD->getFieldIndex()) { 5535 assert(Indirect && "fields out of order?"); 5536 return; 5537 } 5538 5539 // Default-initialize any fields with no explicit initializer. 5540 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) { 5541 assert(FieldIt != RD->field_end() && "missing field?"); 5542 if (!FieldIt->isUnnamedBitfield()) 5543 Result.getStructField(FieldIt->getFieldIndex()) = 5544 getDefaultInitValue(FieldIt->getType()); 5545 } 5546 ++FieldIt; 5547 }; 5548 for (const auto *I : Definition->inits()) { 5549 LValue Subobject = This; 5550 LValue SubobjectParent = This; 5551 APValue *Value = &Result; 5552 5553 // Determine the subobject to initialize. 5554 FieldDecl *FD = nullptr; 5555 if (I->isBaseInitializer()) { 5556 QualType BaseType(I->getBaseClass(), 0); 5557 #ifndef NDEBUG 5558 // Non-virtual base classes are initialized in the order in the class 5559 // definition. We have already checked for virtual base classes. 5560 assert(!BaseIt->isVirtual() && "virtual base for literal type"); 5561 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) && 5562 "base class initializers not in expected order"); 5563 ++BaseIt; 5564 #endif 5565 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD, 5566 BaseType->getAsCXXRecordDecl(), &Layout)) 5567 return false; 5568 Value = &Result.getStructBase(BasesSeen++); 5569 } else if ((FD = I->getMember())) { 5570 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout)) 5571 return false; 5572 if (RD->isUnion()) { 5573 Result = APValue(FD); 5574 Value = &Result.getUnionValue(); 5575 } else { 5576 SkipToField(FD, false); 5577 Value = &Result.getStructField(FD->getFieldIndex()); 5578 } 5579 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) { 5580 // Walk the indirect field decl's chain to find the object to initialize, 5581 // and make sure we've initialized every step along it. 5582 auto IndirectFieldChain = IFD->chain(); 5583 for (auto *C : IndirectFieldChain) { 5584 FD = cast<FieldDecl>(C); 5585 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent()); 5586 // Switch the union field if it differs. This happens if we had 5587 // preceding zero-initialization, and we're now initializing a union 5588 // subobject other than the first. 5589 // FIXME: In this case, the values of the other subobjects are 5590 // specified, since zero-initialization sets all padding bits to zero. 5591 if (!Value->hasValue() || 5592 (Value->isUnion() && Value->getUnionField() != FD)) { 5593 if (CD->isUnion()) 5594 *Value = APValue(FD); 5595 else 5596 // FIXME: This immediately starts the lifetime of all members of an 5597 // anonymous struct. It would be preferable to strictly start member 5598 // lifetime in initialization order. 5599 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD)); 5600 } 5601 // Store Subobject as its parent before updating it for the last element 5602 // in the chain. 5603 if (C == IndirectFieldChain.back()) 5604 SubobjectParent = Subobject; 5605 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD)) 5606 return false; 5607 if (CD->isUnion()) 5608 Value = &Value->getUnionValue(); 5609 else { 5610 if (C == IndirectFieldChain.front() && !RD->isUnion()) 5611 SkipToField(FD, true); 5612 Value = &Value->getStructField(FD->getFieldIndex()); 5613 } 5614 } 5615 } else { 5616 llvm_unreachable("unknown base initializer kind"); 5617 } 5618 5619 // Need to override This for implicit field initializers as in this case 5620 // This refers to innermost anonymous struct/union containing initializer, 5621 // not to currently constructed class. 5622 const Expr *Init = I->getInit(); 5623 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent, 5624 isa<CXXDefaultInitExpr>(Init)); 5625 FullExpressionRAII InitScope(Info); 5626 if (!EvaluateInPlace(*Value, Info, Subobject, Init) || 5627 (FD && FD->isBitField() && 5628 !truncateBitfieldValue(Info, Init, *Value, FD))) { 5629 // If we're checking for a potential constant expression, evaluate all 5630 // initializers even if some of them fail. 5631 if (!Info.noteFailure()) 5632 return false; 5633 Success = false; 5634 } 5635 5636 // This is the point at which the dynamic type of the object becomes this 5637 // class type. 5638 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases()) 5639 EvalObj.finishedConstructingBases(); 5640 } 5641 5642 // Default-initialize any remaining fields. 5643 if (!RD->isUnion()) { 5644 for (; FieldIt != RD->field_end(); ++FieldIt) { 5645 if (!FieldIt->isUnnamedBitfield()) 5646 Result.getStructField(FieldIt->getFieldIndex()) = 5647 getDefaultInitValue(FieldIt->getType()); 5648 } 5649 } 5650 5651 return Success && 5652 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed && 5653 LifetimeExtendedScope.destroy(); 5654 } 5655 5656 static bool HandleConstructorCall(const Expr *E, const LValue &This, 5657 ArrayRef<const Expr*> Args, 5658 const CXXConstructorDecl *Definition, 5659 EvalInfo &Info, APValue &Result) { 5660 ArgVector ArgValues(Args.size()); 5661 if (!EvaluateArgs(Args, ArgValues, Info, Definition)) 5662 return false; 5663 5664 return HandleConstructorCall(E, This, ArgValues.data(), Definition, 5665 Info, Result); 5666 } 5667 5668 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, 5669 const LValue &This, APValue &Value, 5670 QualType T) { 5671 // Objects can only be destroyed while they're within their lifetimes. 5672 // FIXME: We have no representation for whether an object of type nullptr_t 5673 // is in its lifetime; it usually doesn't matter. Perhaps we should model it 5674 // as indeterminate instead? 5675 if (Value.isAbsent() && !T->isNullPtrType()) { 5676 APValue Printable; 5677 This.moveInto(Printable); 5678 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) 5679 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); 5680 return false; 5681 } 5682 5683 // Invent an expression for location purposes. 5684 // FIXME: We shouldn't need to do this. 5685 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue); 5686 5687 // For arrays, destroy elements right-to-left. 5688 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { 5689 uint64_t Size = CAT->getSize().getZExtValue(); 5690 QualType ElemT = CAT->getElementType(); 5691 5692 LValue ElemLV = This; 5693 ElemLV.addArray(Info, &LocE, CAT); 5694 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size)) 5695 return false; 5696 5697 // Ensure that we have actual array elements available to destroy; the 5698 // destructors might mutate the value, so we can't run them on the array 5699 // filler. 5700 if (Size && Size > Value.getArrayInitializedElts()) 5701 expandArray(Value, Value.getArraySize() - 1); 5702 5703 for (; Size != 0; --Size) { 5704 APValue &Elem = Value.getArrayInitializedElt(Size - 1); 5705 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) || 5706 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT)) 5707 return false; 5708 } 5709 5710 // End the lifetime of this array now. 5711 Value = APValue(); 5712 return true; 5713 } 5714 5715 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5716 if (!RD) { 5717 if (T.isDestructedType()) { 5718 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; 5719 return false; 5720 } 5721 5722 Value = APValue(); 5723 return true; 5724 } 5725 5726 if (RD->getNumVBases()) { 5727 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; 5728 return false; 5729 } 5730 5731 const CXXDestructorDecl *DD = RD->getDestructor(); 5732 if (!DD && !RD->hasTrivialDestructor()) { 5733 Info.FFDiag(CallLoc); 5734 return false; 5735 } 5736 5737 if (!DD || DD->isTrivial() || 5738 (RD->isAnonymousStructOrUnion() && RD->isUnion())) { 5739 // A trivial destructor just ends the lifetime of the object. Check for 5740 // this case before checking for a body, because we might not bother 5741 // building a body for a trivial destructor. Note that it doesn't matter 5742 // whether the destructor is constexpr in this case; all trivial 5743 // destructors are constexpr. 5744 // 5745 // If an anonymous union would be destroyed, some enclosing destructor must 5746 // have been explicitly defined, and the anonymous union destruction should 5747 // have no effect. 5748 Value = APValue(); 5749 return true; 5750 } 5751 5752 if (!Info.CheckCallLimit(CallLoc)) 5753 return false; 5754 5755 const FunctionDecl *Definition = nullptr; 5756 const Stmt *Body = DD->getBody(Definition); 5757 5758 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) 5759 return false; 5760 5761 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr); 5762 5763 // We're now in the period of destruction of this object. 5764 unsigned BasesLeft = RD->getNumBases(); 5765 EvalInfo::EvaluatingDestructorRAII EvalObj( 5766 Info, 5767 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}); 5768 if (!EvalObj.DidInsert) { 5769 // C++2a [class.dtor]p19: 5770 // the behavior is undefined if the destructor is invoked for an object 5771 // whose lifetime has ended 5772 // (Note that formally the lifetime ends when the period of destruction 5773 // begins, even though certain uses of the object remain valid until the 5774 // period of destruction ends.) 5775 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy); 5776 return false; 5777 } 5778 5779 // FIXME: Creating an APValue just to hold a nonexistent return value is 5780 // wasteful. 5781 APValue RetVal; 5782 StmtResult Ret = {RetVal, nullptr}; 5783 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed) 5784 return false; 5785 5786 // A union destructor does not implicitly destroy its members. 5787 if (RD->isUnion()) 5788 return true; 5789 5790 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5791 5792 // We don't have a good way to iterate fields in reverse, so collect all the 5793 // fields first and then walk them backwards. 5794 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end()); 5795 for (const FieldDecl *FD : llvm::reverse(Fields)) { 5796 if (FD->isUnnamedBitfield()) 5797 continue; 5798 5799 LValue Subobject = This; 5800 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout)) 5801 return false; 5802 5803 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex()); 5804 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 5805 FD->getType())) 5806 return false; 5807 } 5808 5809 if (BasesLeft != 0) 5810 EvalObj.startedDestroyingBases(); 5811 5812 // Destroy base classes in reverse order. 5813 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { 5814 --BasesLeft; 5815 5816 QualType BaseType = Base.getType(); 5817 LValue Subobject = This; 5818 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD, 5819 BaseType->getAsCXXRecordDecl(), &Layout)) 5820 return false; 5821 5822 APValue *SubobjectValue = &Value.getStructBase(BasesLeft); 5823 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue, 5824 BaseType)) 5825 return false; 5826 } 5827 assert(BasesLeft == 0 && "NumBases was wrong?"); 5828 5829 // The period of destruction ends now. The object is gone. 5830 Value = APValue(); 5831 return true; 5832 } 5833 5834 namespace { 5835 struct DestroyObjectHandler { 5836 EvalInfo &Info; 5837 const Expr *E; 5838 const LValue &This; 5839 const AccessKinds AccessKind; 5840 5841 typedef bool result_type; 5842 bool failed() { return false; } 5843 bool found(APValue &Subobj, QualType SubobjType) { 5844 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj, 5845 SubobjType); 5846 } 5847 bool found(APSInt &Value, QualType SubobjType) { 5848 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 5849 return false; 5850 } 5851 bool found(APFloat &Value, QualType SubobjType) { 5852 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem); 5853 return false; 5854 } 5855 }; 5856 } 5857 5858 /// Perform a destructor or pseudo-destructor call on the given object, which 5859 /// might in general not be a complete object. 5860 static bool HandleDestruction(EvalInfo &Info, const Expr *E, 5861 const LValue &This, QualType ThisType) { 5862 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); 5863 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; 5864 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); 5865 } 5866 5867 /// Destroy and end the lifetime of the given complete object. 5868 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, 5869 APValue::LValueBase LVBase, APValue &Value, 5870 QualType T) { 5871 // If we've had an unmodeled side-effect, we can't rely on mutable state 5872 // (such as the object we're about to destroy) being correct. 5873 if (Info.EvalStatus.HasSideEffects) 5874 return false; 5875 5876 LValue LV; 5877 LV.set({LVBase}); 5878 return HandleDestructionImpl(Info, Loc, LV, Value, T); 5879 } 5880 5881 //===----------------------------------------------------------------------===// 5882 // Generic Evaluation 5883 //===----------------------------------------------------------------------===// 5884 namespace { 5885 5886 class BitCastBuffer { 5887 // FIXME: We're going to need bit-level granularity when we support 5888 // bit-fields. 5889 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but 5890 // we don't support a host or target where that is the case. Still, we should 5891 // use a more generic type in case we ever do. 5892 SmallVector<Optional<unsigned char>, 32> Bytes; 5893 5894 static_assert(std::numeric_limits<unsigned char>::digits >= 8, 5895 "Need at least 8 bit unsigned char"); 5896 5897 bool TargetIsLittleEndian; 5898 5899 public: 5900 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) 5901 : Bytes(Width.getQuantity()), 5902 TargetIsLittleEndian(TargetIsLittleEndian) {} 5903 5904 LLVM_NODISCARD 5905 bool readObject(CharUnits Offset, CharUnits Width, 5906 SmallVectorImpl<unsigned char> &Output) const { 5907 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) { 5908 // If a byte of an integer is uninitialized, then the whole integer is 5909 // uninitalized. 5910 if (!Bytes[I.getQuantity()]) 5911 return false; 5912 Output.push_back(*Bytes[I.getQuantity()]); 5913 } 5914 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 5915 std::reverse(Output.begin(), Output.end()); 5916 return true; 5917 } 5918 5919 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) { 5920 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian) 5921 std::reverse(Input.begin(), Input.end()); 5922 5923 size_t Index = 0; 5924 for (unsigned char Byte : Input) { 5925 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?"); 5926 Bytes[Offset.getQuantity() + Index] = Byte; 5927 ++Index; 5928 } 5929 } 5930 5931 size_t size() { return Bytes.size(); } 5932 }; 5933 5934 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current 5935 /// target would represent the value at runtime. 5936 class APValueToBufferConverter { 5937 EvalInfo &Info; 5938 BitCastBuffer Buffer; 5939 const CastExpr *BCE; 5940 5941 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, 5942 const CastExpr *BCE) 5943 : Info(Info), 5944 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), 5945 BCE(BCE) {} 5946 5947 bool visit(const APValue &Val, QualType Ty) { 5948 return visit(Val, Ty, CharUnits::fromQuantity(0)); 5949 } 5950 5951 // Write out Val with type Ty into Buffer starting at Offset. 5952 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { 5953 assert((size_t)Offset.getQuantity() <= Buffer.size()); 5954 5955 // As a special case, nullptr_t has an indeterminate value. 5956 if (Ty->isNullPtrType()) 5957 return true; 5958 5959 // Dig through Src to find the byte at SrcOffset. 5960 switch (Val.getKind()) { 5961 case APValue::Indeterminate: 5962 case APValue::None: 5963 return true; 5964 5965 case APValue::Int: 5966 return visitInt(Val.getInt(), Ty, Offset); 5967 case APValue::Float: 5968 return visitFloat(Val.getFloat(), Ty, Offset); 5969 case APValue::Array: 5970 return visitArray(Val, Ty, Offset); 5971 case APValue::Struct: 5972 return visitRecord(Val, Ty, Offset); 5973 5974 case APValue::ComplexInt: 5975 case APValue::ComplexFloat: 5976 case APValue::Vector: 5977 case APValue::FixedPoint: 5978 // FIXME: We should support these. 5979 5980 case APValue::Union: 5981 case APValue::MemberPointer: 5982 case APValue::AddrLabelDiff: { 5983 Info.FFDiag(BCE->getBeginLoc(), 5984 diag::note_constexpr_bit_cast_unsupported_type) 5985 << Ty; 5986 return false; 5987 } 5988 5989 case APValue::LValue: 5990 llvm_unreachable("LValue subobject in bit_cast?"); 5991 } 5992 llvm_unreachable("Unhandled APValue::ValueKind"); 5993 } 5994 5995 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { 5996 const RecordDecl *RD = Ty->getAsRecordDecl(); 5997 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 5998 5999 // Visit the base classes. 6000 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6001 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6002 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6003 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6004 6005 if (!visitRecord(Val.getStructBase(I), BS.getType(), 6006 Layout.getBaseClassOffset(BaseDecl) + Offset)) 6007 return false; 6008 } 6009 } 6010 6011 // Visit the fields. 6012 unsigned FieldIdx = 0; 6013 for (FieldDecl *FD : RD->fields()) { 6014 if (FD->isBitField()) { 6015 Info.FFDiag(BCE->getBeginLoc(), 6016 diag::note_constexpr_bit_cast_unsupported_bitfield); 6017 return false; 6018 } 6019 6020 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6021 6022 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 && 6023 "only bit-fields can have sub-char alignment"); 6024 CharUnits FieldOffset = 6025 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset; 6026 QualType FieldTy = FD->getType(); 6027 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset)) 6028 return false; 6029 ++FieldIdx; 6030 } 6031 6032 return true; 6033 } 6034 6035 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { 6036 const auto *CAT = 6037 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe()); 6038 if (!CAT) 6039 return false; 6040 6041 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType()); 6042 unsigned NumInitializedElts = Val.getArrayInitializedElts(); 6043 unsigned ArraySize = Val.getArraySize(); 6044 // First, initialize the initialized elements. 6045 for (unsigned I = 0; I != NumInitializedElts; ++I) { 6046 const APValue &SubObj = Val.getArrayInitializedElt(I); 6047 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) 6048 return false; 6049 } 6050 6051 // Next, initialize the rest of the array using the filler. 6052 if (Val.hasArrayFiller()) { 6053 const APValue &Filler = Val.getArrayFiller(); 6054 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { 6055 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) 6056 return false; 6057 } 6058 } 6059 6060 return true; 6061 } 6062 6063 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { 6064 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty); 6065 SmallVector<unsigned char, 8> Bytes(Width.getQuantity()); 6066 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity()); 6067 Buffer.writeObject(Offset, Bytes); 6068 return true; 6069 } 6070 6071 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { 6072 APSInt AsInt(Val.bitcastToAPInt()); 6073 return visitInt(AsInt, Ty, Offset); 6074 } 6075 6076 public: 6077 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src, 6078 const CastExpr *BCE) { 6079 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); 6080 APValueToBufferConverter Converter(Info, DstSize, BCE); 6081 if (!Converter.visit(Src, BCE->getSubExpr()->getType())) 6082 return None; 6083 return Converter.Buffer; 6084 } 6085 }; 6086 6087 /// Write an BitCastBuffer into an APValue. 6088 class BufferToAPValueConverter { 6089 EvalInfo &Info; 6090 const BitCastBuffer &Buffer; 6091 const CastExpr *BCE; 6092 6093 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, 6094 const CastExpr *BCE) 6095 : Info(Info), Buffer(Buffer), BCE(BCE) {} 6096 6097 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast 6098 // with an invalid type, so anything left is a deficiency on our part (FIXME). 6099 // Ideally this will be unreachable. 6100 llvm::NoneType unsupportedType(QualType Ty) { 6101 Info.FFDiag(BCE->getBeginLoc(), 6102 diag::note_constexpr_bit_cast_unsupported_type) 6103 << Ty; 6104 return None; 6105 } 6106 6107 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset, 6108 const EnumType *EnumSugar = nullptr) { 6109 if (T->isNullPtrType()) { 6110 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); 6111 return APValue((Expr *)nullptr, 6112 /*Offset=*/CharUnits::fromQuantity(NullValue), 6113 APValue::NoLValuePath{}, /*IsNullPtr=*/true); 6114 } 6115 6116 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T); 6117 SmallVector<uint8_t, 8> Bytes; 6118 if (!Buffer.readObject(Offset, SizeOf, Bytes)) { 6119 // If this is std::byte or unsigned char, then its okay to store an 6120 // indeterminate value. 6121 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType(); 6122 bool IsUChar = 6123 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || 6124 T->isSpecificBuiltinType(BuiltinType::Char_U)); 6125 if (!IsStdByte && !IsUChar) { 6126 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); 6127 Info.FFDiag(BCE->getExprLoc(), 6128 diag::note_constexpr_bit_cast_indet_dest) 6129 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; 6130 return None; 6131 } 6132 6133 return APValue::IndeterminateValue(); 6134 } 6135 6136 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true); 6137 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size()); 6138 6139 if (T->isIntegralOrEnumerationType()) { 6140 Val.setIsSigned(T->isSignedIntegerOrEnumerationType()); 6141 return APValue(Val); 6142 } 6143 6144 if (T->isRealFloatingType()) { 6145 const llvm::fltSemantics &Semantics = 6146 Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); 6147 return APValue(APFloat(Semantics, Val)); 6148 } 6149 6150 return unsupportedType(QualType(T, 0)); 6151 } 6152 6153 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) { 6154 const RecordDecl *RD = RTy->getAsRecordDecl(); 6155 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 6156 6157 unsigned NumBases = 0; 6158 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6159 NumBases = CXXRD->getNumBases(); 6160 6161 APValue ResultVal(APValue::UninitStruct(), NumBases, 6162 std::distance(RD->field_begin(), RD->field_end())); 6163 6164 // Visit the base classes. 6165 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 6166 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { 6167 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; 6168 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 6169 if (BaseDecl->isEmpty() || 6170 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) 6171 continue; 6172 6173 Optional<APValue> SubObj = visitType( 6174 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset); 6175 if (!SubObj) 6176 return None; 6177 ResultVal.getStructBase(I) = *SubObj; 6178 } 6179 } 6180 6181 // Visit the fields. 6182 unsigned FieldIdx = 0; 6183 for (FieldDecl *FD : RD->fields()) { 6184 // FIXME: We don't currently support bit-fields. A lot of the logic for 6185 // this is in CodeGen, so we need to factor it around. 6186 if (FD->isBitField()) { 6187 Info.FFDiag(BCE->getBeginLoc(), 6188 diag::note_constexpr_bit_cast_unsupported_bitfield); 6189 return None; 6190 } 6191 6192 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx); 6193 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0); 6194 6195 CharUnits FieldOffset = 6196 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) + 6197 Offset; 6198 QualType FieldTy = FD->getType(); 6199 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset); 6200 if (!SubObj) 6201 return None; 6202 ResultVal.getStructField(FieldIdx) = *SubObj; 6203 ++FieldIdx; 6204 } 6205 6206 return ResultVal; 6207 } 6208 6209 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) { 6210 QualType RepresentationType = Ty->getDecl()->getIntegerType(); 6211 assert(!RepresentationType.isNull() && 6212 "enum forward decl should be caught by Sema"); 6213 const BuiltinType *AsBuiltin = 6214 RepresentationType.getCanonicalType()->getAs<BuiltinType>(); 6215 assert(AsBuiltin && "non-integral enum underlying type?"); 6216 // Recurse into the underlying type. Treat std::byte transparently as 6217 // unsigned char. 6218 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); 6219 } 6220 6221 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) { 6222 size_t Size = Ty->getSize().getLimitedValue(); 6223 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); 6224 6225 APValue ArrayValue(APValue::UninitArray(), Size, Size); 6226 for (size_t I = 0; I != Size; ++I) { 6227 Optional<APValue> ElementValue = 6228 visitType(Ty->getElementType(), Offset + I * ElementWidth); 6229 if (!ElementValue) 6230 return None; 6231 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue); 6232 } 6233 6234 return ArrayValue; 6235 } 6236 6237 Optional<APValue> visit(const Type *Ty, CharUnits Offset) { 6238 return unsupportedType(QualType(Ty, 0)); 6239 } 6240 6241 Optional<APValue> visitType(QualType Ty, CharUnits Offset) { 6242 QualType Can = Ty.getCanonicalType(); 6243 6244 switch (Can->getTypeClass()) { 6245 #define TYPE(Class, Base) \ 6246 case Type::Class: \ 6247 return visit(cast<Class##Type>(Can.getTypePtr()), Offset); 6248 #define ABSTRACT_TYPE(Class, Base) 6249 #define NON_CANONICAL_TYPE(Class, Base) \ 6250 case Type::Class: \ 6251 llvm_unreachable("non-canonical type should be impossible!"); 6252 #define DEPENDENT_TYPE(Class, Base) \ 6253 case Type::Class: \ 6254 llvm_unreachable( \ 6255 "dependent types aren't supported in the constant evaluator!"); 6256 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \ 6257 case Type::Class: \ 6258 llvm_unreachable("either dependent or not canonical!"); 6259 #include "clang/AST/TypeNodes.def" 6260 } 6261 llvm_unreachable("Unhandled Type::TypeClass"); 6262 } 6263 6264 public: 6265 // Pull out a full value of type DstType. 6266 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer, 6267 const CastExpr *BCE) { 6268 BufferToAPValueConverter Converter(Info, Buffer, BCE); 6269 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); 6270 } 6271 }; 6272 6273 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, 6274 QualType Ty, EvalInfo *Info, 6275 const ASTContext &Ctx, 6276 bool CheckingDest) { 6277 Ty = Ty.getCanonicalType(); 6278 6279 auto diag = [&](int Reason) { 6280 if (Info) 6281 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type) 6282 << CheckingDest << (Reason == 4) << Reason; 6283 return false; 6284 }; 6285 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) { 6286 if (Info) 6287 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype) 6288 << NoteTy << Construct << Ty; 6289 return false; 6290 }; 6291 6292 if (Ty->isUnionType()) 6293 return diag(0); 6294 if (Ty->isPointerType()) 6295 return diag(1); 6296 if (Ty->isMemberPointerType()) 6297 return diag(2); 6298 if (Ty.isVolatileQualified()) 6299 return diag(3); 6300 6301 if (RecordDecl *Record = Ty->getAsRecordDecl()) { 6302 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) { 6303 for (CXXBaseSpecifier &BS : CXXRD->bases()) 6304 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx, 6305 CheckingDest)) 6306 return note(1, BS.getType(), BS.getBeginLoc()); 6307 } 6308 for (FieldDecl *FD : Record->fields()) { 6309 if (FD->getType()->isReferenceType()) 6310 return diag(4); 6311 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx, 6312 CheckingDest)) 6313 return note(0, FD->getType(), FD->getBeginLoc()); 6314 } 6315 } 6316 6317 if (Ty->isArrayType() && 6318 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty), 6319 Info, Ctx, CheckingDest)) 6320 return false; 6321 6322 return true; 6323 } 6324 6325 static bool checkBitCastConstexprEligibility(EvalInfo *Info, 6326 const ASTContext &Ctx, 6327 const CastExpr *BCE) { 6328 bool DestOK = checkBitCastConstexprEligibilityType( 6329 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); 6330 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( 6331 BCE->getBeginLoc(), 6332 BCE->getSubExpr()->getType(), Info, Ctx, false); 6333 return SourceOK; 6334 } 6335 6336 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, 6337 APValue &SourceValue, 6338 const CastExpr *BCE) { 6339 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && 6340 "no host or target supports non 8-bit chars"); 6341 assert(SourceValue.isLValue() && 6342 "LValueToRValueBitcast requires an lvalue operand!"); 6343 6344 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE)) 6345 return false; 6346 6347 LValue SourceLValue; 6348 APValue SourceRValue; 6349 SourceLValue.setFrom(Info.Ctx, SourceValue); 6350 if (!handleLValueToRValueConversion( 6351 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue, 6352 SourceRValue, /*WantObjectRepresentation=*/true)) 6353 return false; 6354 6355 // Read out SourceValue into a char buffer. 6356 Optional<BitCastBuffer> Buffer = 6357 APValueToBufferConverter::convert(Info, SourceRValue, BCE); 6358 if (!Buffer) 6359 return false; 6360 6361 // Write out the buffer into a new APValue. 6362 Optional<APValue> MaybeDestValue = 6363 BufferToAPValueConverter::convert(Info, *Buffer, BCE); 6364 if (!MaybeDestValue) 6365 return false; 6366 6367 DestValue = std::move(*MaybeDestValue); 6368 return true; 6369 } 6370 6371 template <class Derived> 6372 class ExprEvaluatorBase 6373 : public ConstStmtVisitor<Derived, bool> { 6374 private: 6375 Derived &getDerived() { return static_cast<Derived&>(*this); } 6376 bool DerivedSuccess(const APValue &V, const Expr *E) { 6377 return getDerived().Success(V, E); 6378 } 6379 bool DerivedZeroInitialization(const Expr *E) { 6380 return getDerived().ZeroInitialization(E); 6381 } 6382 6383 // Check whether a conditional operator with a non-constant condition is a 6384 // potential constant expression. If neither arm is a potential constant 6385 // expression, then the conditional operator is not either. 6386 template<typename ConditionalOperator> 6387 void CheckPotentialConstantConditional(const ConditionalOperator *E) { 6388 assert(Info.checkingPotentialConstantExpression()); 6389 6390 // Speculatively evaluate both arms. 6391 SmallVector<PartialDiagnosticAt, 8> Diag; 6392 { 6393 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6394 StmtVisitorTy::Visit(E->getFalseExpr()); 6395 if (Diag.empty()) 6396 return; 6397 } 6398 6399 { 6400 SpeculativeEvaluationRAII Speculate(Info, &Diag); 6401 Diag.clear(); 6402 StmtVisitorTy::Visit(E->getTrueExpr()); 6403 if (Diag.empty()) 6404 return; 6405 } 6406 6407 Error(E, diag::note_constexpr_conditional_never_const); 6408 } 6409 6410 6411 template<typename ConditionalOperator> 6412 bool HandleConditionalOperator(const ConditionalOperator *E) { 6413 bool BoolResult; 6414 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { 6415 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { 6416 CheckPotentialConstantConditional(E); 6417 return false; 6418 } 6419 if (Info.noteFailure()) { 6420 StmtVisitorTy::Visit(E->getTrueExpr()); 6421 StmtVisitorTy::Visit(E->getFalseExpr()); 6422 } 6423 return false; 6424 } 6425 6426 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr(); 6427 return StmtVisitorTy::Visit(EvalExpr); 6428 } 6429 6430 protected: 6431 EvalInfo &Info; 6432 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy; 6433 typedef ExprEvaluatorBase ExprEvaluatorBaseTy; 6434 6435 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 6436 return Info.CCEDiag(E, D); 6437 } 6438 6439 bool ZeroInitialization(const Expr *E) { return Error(E); } 6440 6441 public: 6442 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} 6443 6444 EvalInfo &getEvalInfo() { return Info; } 6445 6446 /// Report an evaluation error. This should only be called when an error is 6447 /// first discovered. When propagating an error, just return false. 6448 bool Error(const Expr *E, diag::kind D) { 6449 Info.FFDiag(E, D); 6450 return false; 6451 } 6452 bool Error(const Expr *E) { 6453 return Error(E, diag::note_invalid_subexpr_in_const_expr); 6454 } 6455 6456 bool VisitStmt(const Stmt *) { 6457 llvm_unreachable("Expression evaluator should not be called on stmts"); 6458 } 6459 bool VisitExpr(const Expr *E) { 6460 return Error(E); 6461 } 6462 6463 bool VisitConstantExpr(const ConstantExpr *E) 6464 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6465 bool VisitParenExpr(const ParenExpr *E) 6466 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6467 bool VisitUnaryExtension(const UnaryOperator *E) 6468 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6469 bool VisitUnaryPlus(const UnaryOperator *E) 6470 { return StmtVisitorTy::Visit(E->getSubExpr()); } 6471 bool VisitChooseExpr(const ChooseExpr *E) 6472 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } 6473 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) 6474 { return StmtVisitorTy::Visit(E->getResultExpr()); } 6475 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) 6476 { return StmtVisitorTy::Visit(E->getReplacement()); } 6477 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 6478 TempVersionRAII RAII(*Info.CurrentCall); 6479 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 6480 return StmtVisitorTy::Visit(E->getExpr()); 6481 } 6482 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 6483 TempVersionRAII RAII(*Info.CurrentCall); 6484 // The initializer may not have been parsed yet, or might be erroneous. 6485 if (!E->getExpr()) 6486 return Error(E); 6487 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); 6488 return StmtVisitorTy::Visit(E->getExpr()); 6489 } 6490 6491 bool VisitExprWithCleanups(const ExprWithCleanups *E) { 6492 FullExpressionRAII Scope(Info); 6493 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); 6494 } 6495 6496 // Temporaries are registered when created, so we don't care about 6497 // CXXBindTemporaryExpr. 6498 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { 6499 return StmtVisitorTy::Visit(E->getSubExpr()); 6500 } 6501 6502 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { 6503 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; 6504 return static_cast<Derived*>(this)->VisitCastExpr(E); 6505 } 6506 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { 6507 if (!Info.Ctx.getLangOpts().CPlusPlus2a) 6508 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; 6509 return static_cast<Derived*>(this)->VisitCastExpr(E); 6510 } 6511 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { 6512 return static_cast<Derived*>(this)->VisitCastExpr(E); 6513 } 6514 6515 bool VisitBinaryOperator(const BinaryOperator *E) { 6516 switch (E->getOpcode()) { 6517 default: 6518 return Error(E); 6519 6520 case BO_Comma: 6521 VisitIgnoredValue(E->getLHS()); 6522 return StmtVisitorTy::Visit(E->getRHS()); 6523 6524 case BO_PtrMemD: 6525 case BO_PtrMemI: { 6526 LValue Obj; 6527 if (!HandleMemberPointerAccess(Info, E, Obj)) 6528 return false; 6529 APValue Result; 6530 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result)) 6531 return false; 6532 return DerivedSuccess(Result, E); 6533 } 6534 } 6535 } 6536 6537 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { 6538 // Evaluate and cache the common expression. We treat it as a temporary, 6539 // even though it's not quite the same thing. 6540 LValue CommonLV; 6541 if (!Evaluate(Info.CurrentCall->createTemporary( 6542 E->getOpaqueValue(), 6543 getStorageType(Info.Ctx, E->getOpaqueValue()), false, 6544 CommonLV), 6545 Info, E->getCommon())) 6546 return false; 6547 6548 return HandleConditionalOperator(E); 6549 } 6550 6551 bool VisitConditionalOperator(const ConditionalOperator *E) { 6552 bool IsBcpCall = false; 6553 // If the condition (ignoring parens) is a __builtin_constant_p call, 6554 // the result is a constant expression if it can be folded without 6555 // side-effects. This is an important GNU extension. See GCC PR38377 6556 // for discussion. 6557 if (const CallExpr *CallCE = 6558 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts())) 6559 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 6560 IsBcpCall = true; 6561 6562 // Always assume __builtin_constant_p(...) ? ... : ... is a potential 6563 // constant expression; we can't check whether it's potentially foldable. 6564 // FIXME: We should instead treat __builtin_constant_p as non-constant if 6565 // it would return 'false' in this mode. 6566 if (Info.checkingPotentialConstantExpression() && IsBcpCall) 6567 return false; 6568 6569 FoldConstant Fold(Info, IsBcpCall); 6570 if (!HandleConditionalOperator(E)) { 6571 Fold.keepDiagnostics(); 6572 return false; 6573 } 6574 6575 return true; 6576 } 6577 6578 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 6579 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) 6580 return DerivedSuccess(*Value, E); 6581 6582 const Expr *Source = E->getSourceExpr(); 6583 if (!Source) 6584 return Error(E); 6585 if (Source == E) { // sanity checking. 6586 assert(0 && "OpaqueValueExpr recursively refers to itself"); 6587 return Error(E); 6588 } 6589 return StmtVisitorTy::Visit(Source); 6590 } 6591 6592 bool VisitCallExpr(const CallExpr *E) { 6593 APValue Result; 6594 if (!handleCallExpr(E, Result, nullptr)) 6595 return false; 6596 return DerivedSuccess(Result, E); 6597 } 6598 6599 bool handleCallExpr(const CallExpr *E, APValue &Result, 6600 const LValue *ResultSlot) { 6601 const Expr *Callee = E->getCallee()->IgnoreParens(); 6602 QualType CalleeType = Callee->getType(); 6603 6604 const FunctionDecl *FD = nullptr; 6605 LValue *This = nullptr, ThisVal; 6606 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 6607 bool HasQualifier = false; 6608 6609 // Extract function decl and 'this' pointer from the callee. 6610 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { 6611 const CXXMethodDecl *Member = nullptr; 6612 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) { 6613 // Explicit bound member calls, such as x.f() or p->g(); 6614 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) 6615 return false; 6616 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 6617 if (!Member) 6618 return Error(Callee); 6619 This = &ThisVal; 6620 HasQualifier = ME->hasQualifier(); 6621 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) { 6622 // Indirect bound member calls ('.*' or '->*'). 6623 Member = dyn_cast_or_null<CXXMethodDecl>( 6624 HandleMemberPointerAccess(Info, BE, ThisVal, false)); 6625 if (!Member) 6626 return Error(Callee); 6627 This = &ThisVal; 6628 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) { 6629 if (!Info.getLangOpts().CPlusPlus2a) 6630 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); 6631 // FIXME: If pseudo-destructor calls ever start ending the lifetime of 6632 // their callee, we should start calling HandleDestruction here. 6633 // For now, we just evaluate the object argument and discard it. 6634 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal); 6635 } else 6636 return Error(Callee); 6637 FD = Member; 6638 } else if (CalleeType->isFunctionPointerType()) { 6639 LValue Call; 6640 if (!EvaluatePointer(Callee, Call, Info)) 6641 return false; 6642 6643 if (!Call.getLValueOffset().isZero()) 6644 return Error(Callee); 6645 FD = dyn_cast_or_null<FunctionDecl>( 6646 Call.getLValueBase().dyn_cast<const ValueDecl*>()); 6647 if (!FD) 6648 return Error(Callee); 6649 // Don't call function pointers which have been cast to some other type. 6650 // Per DR (no number yet), the caller and callee can differ in noexcept. 6651 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( 6652 CalleeType->getPointeeType(), FD->getType())) { 6653 return Error(E); 6654 } 6655 6656 // Overloaded operator calls to member functions are represented as normal 6657 // calls with '*this' as the first argument. 6658 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6659 if (MD && !MD->isStatic()) { 6660 // FIXME: When selecting an implicit conversion for an overloaded 6661 // operator delete, we sometimes try to evaluate calls to conversion 6662 // operators without a 'this' parameter! 6663 if (Args.empty()) 6664 return Error(E); 6665 6666 if (!EvaluateObjectArgument(Info, Args[0], ThisVal)) 6667 return false; 6668 This = &ThisVal; 6669 Args = Args.slice(1); 6670 } else if (MD && MD->isLambdaStaticInvoker()) { 6671 // Map the static invoker for the lambda back to the call operator. 6672 // Conveniently, we don't have to slice out the 'this' argument (as is 6673 // being done for the non-static case), since a static member function 6674 // doesn't have an implicit argument passed in. 6675 const CXXRecordDecl *ClosureClass = MD->getParent(); 6676 assert( 6677 ClosureClass->captures_begin() == ClosureClass->captures_end() && 6678 "Number of captures must be zero for conversion to function-ptr"); 6679 6680 const CXXMethodDecl *LambdaCallOp = 6681 ClosureClass->getLambdaCallOperator(); 6682 6683 // Set 'FD', the function that will be called below, to the call 6684 // operator. If the closure object represents a generic lambda, find 6685 // the corresponding specialization of the call operator. 6686 6687 if (ClosureClass->isGenericLambda()) { 6688 assert(MD->isFunctionTemplateSpecialization() && 6689 "A generic lambda's static-invoker function must be a " 6690 "template specialization"); 6691 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 6692 FunctionTemplateDecl *CallOpTemplate = 6693 LambdaCallOp->getDescribedFunctionTemplate(); 6694 void *InsertPos = nullptr; 6695 FunctionDecl *CorrespondingCallOpSpecialization = 6696 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 6697 assert(CorrespondingCallOpSpecialization && 6698 "We must always have a function call operator specialization " 6699 "that corresponds to our static invoker specialization"); 6700 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 6701 } else 6702 FD = LambdaCallOp; 6703 } 6704 } else 6705 return Error(E); 6706 6707 SmallVector<QualType, 4> CovariantAdjustmentPath; 6708 if (This) { 6709 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD); 6710 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) { 6711 // Perform virtual dispatch, if necessary. 6712 FD = HandleVirtualDispatch(Info, E, *This, NamedMember, 6713 CovariantAdjustmentPath); 6714 if (!FD) 6715 return false; 6716 } else { 6717 // Check that the 'this' pointer points to an object of the right type. 6718 // FIXME: If this is an assignment operator call, we may need to change 6719 // the active union member before we check this. 6720 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember)) 6721 return false; 6722 } 6723 } 6724 6725 // Destructor calls are different enough that they have their own codepath. 6726 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) { 6727 assert(This && "no 'this' pointer for destructor call"); 6728 return HandleDestruction(Info, E, *This, 6729 Info.Ctx.getRecordType(DD->getParent())); 6730 } 6731 6732 const FunctionDecl *Definition = nullptr; 6733 Stmt *Body = FD->getBody(Definition); 6734 6735 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || 6736 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info, 6737 Result, ResultSlot)) 6738 return false; 6739 6740 if (!CovariantAdjustmentPath.empty() && 6741 !HandleCovariantReturnAdjustment(Info, E, Result, 6742 CovariantAdjustmentPath)) 6743 return false; 6744 6745 return true; 6746 } 6747 6748 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 6749 return StmtVisitorTy::Visit(E->getInitializer()); 6750 } 6751 bool VisitInitListExpr(const InitListExpr *E) { 6752 if (E->getNumInits() == 0) 6753 return DerivedZeroInitialization(E); 6754 if (E->getNumInits() == 1) 6755 return StmtVisitorTy::Visit(E->getInit(0)); 6756 return Error(E); 6757 } 6758 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { 6759 return DerivedZeroInitialization(E); 6760 } 6761 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { 6762 return DerivedZeroInitialization(E); 6763 } 6764 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { 6765 return DerivedZeroInitialization(E); 6766 } 6767 6768 /// A member expression where the object is a prvalue is itself a prvalue. 6769 bool VisitMemberExpr(const MemberExpr *E) { 6770 assert(!Info.Ctx.getLangOpts().CPlusPlus11 && 6771 "missing temporary materialization conversion"); 6772 assert(!E->isArrow() && "missing call to bound member function?"); 6773 6774 APValue Val; 6775 if (!Evaluate(Val, Info, E->getBase())) 6776 return false; 6777 6778 QualType BaseTy = E->getBase()->getType(); 6779 6780 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 6781 if (!FD) return Error(E); 6782 assert(!FD->getType()->isReferenceType() && "prvalue reference?"); 6783 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() == 6784 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 6785 6786 // Note: there is no lvalue base here. But this case should only ever 6787 // happen in C or in C++98, where we cannot be evaluating a constexpr 6788 // constructor, which is the only case the base matters. 6789 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy); 6790 SubobjectDesignator Designator(BaseTy); 6791 Designator.addDeclUnchecked(FD); 6792 6793 APValue Result; 6794 return extractSubobject(Info, E, Obj, Designator, Result) && 6795 DerivedSuccess(Result, E); 6796 } 6797 6798 bool VisitCastExpr(const CastExpr *E) { 6799 switch (E->getCastKind()) { 6800 default: 6801 break; 6802 6803 case CK_AtomicToNonAtomic: { 6804 APValue AtomicVal; 6805 // This does not need to be done in place even for class/array types: 6806 // atomic-to-non-atomic conversion implies copying the object 6807 // representation. 6808 if (!Evaluate(AtomicVal, Info, E->getSubExpr())) 6809 return false; 6810 return DerivedSuccess(AtomicVal, E); 6811 } 6812 6813 case CK_NoOp: 6814 case CK_UserDefinedConversion: 6815 return StmtVisitorTy::Visit(E->getSubExpr()); 6816 6817 case CK_LValueToRValue: { 6818 LValue LVal; 6819 if (!EvaluateLValue(E->getSubExpr(), LVal, Info)) 6820 return false; 6821 APValue RVal; 6822 // Note, we use the subexpression's type in order to retain cv-qualifiers. 6823 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 6824 LVal, RVal)) 6825 return false; 6826 return DerivedSuccess(RVal, E); 6827 } 6828 case CK_LValueToRValueBitCast: { 6829 APValue DestValue, SourceValue; 6830 if (!Evaluate(SourceValue, Info, E->getSubExpr())) 6831 return false; 6832 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E)) 6833 return false; 6834 return DerivedSuccess(DestValue, E); 6835 } 6836 } 6837 6838 return Error(E); 6839 } 6840 6841 bool VisitUnaryPostInc(const UnaryOperator *UO) { 6842 return VisitUnaryPostIncDec(UO); 6843 } 6844 bool VisitUnaryPostDec(const UnaryOperator *UO) { 6845 return VisitUnaryPostIncDec(UO); 6846 } 6847 bool VisitUnaryPostIncDec(const UnaryOperator *UO) { 6848 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 6849 return Error(UO); 6850 6851 LValue LVal; 6852 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info)) 6853 return false; 6854 APValue RVal; 6855 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(), 6856 UO->isIncrementOp(), &RVal)) 6857 return false; 6858 return DerivedSuccess(RVal, UO); 6859 } 6860 6861 bool VisitStmtExpr(const StmtExpr *E) { 6862 // We will have checked the full-expressions inside the statement expression 6863 // when they were completed, and don't need to check them again now. 6864 if (Info.checkingForUndefinedBehavior()) 6865 return Error(E); 6866 6867 const CompoundStmt *CS = E->getSubStmt(); 6868 if (CS->body_empty()) 6869 return true; 6870 6871 BlockScopeRAII Scope(Info); 6872 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 6873 BE = CS->body_end(); 6874 /**/; ++BI) { 6875 if (BI + 1 == BE) { 6876 const Expr *FinalExpr = dyn_cast<Expr>(*BI); 6877 if (!FinalExpr) { 6878 Info.FFDiag((*BI)->getBeginLoc(), 6879 diag::note_constexpr_stmt_expr_unsupported); 6880 return false; 6881 } 6882 return this->Visit(FinalExpr) && Scope.destroy(); 6883 } 6884 6885 APValue ReturnValue; 6886 StmtResult Result = { ReturnValue, nullptr }; 6887 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); 6888 if (ESR != ESR_Succeeded) { 6889 // FIXME: If the statement-expression terminated due to 'return', 6890 // 'break', or 'continue', it would be nice to propagate that to 6891 // the outer statement evaluation rather than bailing out. 6892 if (ESR != ESR_Failed) 6893 Info.FFDiag((*BI)->getBeginLoc(), 6894 diag::note_constexpr_stmt_expr_unsupported); 6895 return false; 6896 } 6897 } 6898 6899 llvm_unreachable("Return from function from the loop above."); 6900 } 6901 6902 /// Visit a value which is evaluated, but whose value is ignored. 6903 void VisitIgnoredValue(const Expr *E) { 6904 EvaluateIgnoredValue(Info, E); 6905 } 6906 6907 /// Potentially visit a MemberExpr's base expression. 6908 void VisitIgnoredBaseExpression(const Expr *E) { 6909 // While MSVC doesn't evaluate the base expression, it does diagnose the 6910 // presence of side-effecting behavior. 6911 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) 6912 return; 6913 VisitIgnoredValue(E); 6914 } 6915 }; 6916 6917 } // namespace 6918 6919 //===----------------------------------------------------------------------===// 6920 // Common base class for lvalue and temporary evaluation. 6921 //===----------------------------------------------------------------------===// 6922 namespace { 6923 template<class Derived> 6924 class LValueExprEvaluatorBase 6925 : public ExprEvaluatorBase<Derived> { 6926 protected: 6927 LValue &Result; 6928 bool InvalidBaseOK; 6929 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy; 6930 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy; 6931 6932 bool Success(APValue::LValueBase B) { 6933 Result.set(B); 6934 return true; 6935 } 6936 6937 bool evaluatePointer(const Expr *E, LValue &Result) { 6938 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); 6939 } 6940 6941 public: 6942 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) 6943 : ExprEvaluatorBaseTy(Info), Result(Result), 6944 InvalidBaseOK(InvalidBaseOK) {} 6945 6946 bool Success(const APValue &V, const Expr *E) { 6947 Result.setFrom(this->Info.Ctx, V); 6948 return true; 6949 } 6950 6951 bool VisitMemberExpr(const MemberExpr *E) { 6952 // Handle non-static data members. 6953 QualType BaseTy; 6954 bool EvalOK; 6955 if (E->isArrow()) { 6956 EvalOK = evaluatePointer(E->getBase(), Result); 6957 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType(); 6958 } else if (E->getBase()->isRValue()) { 6959 assert(E->getBase()->getType()->isRecordType()); 6960 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info); 6961 BaseTy = E->getBase()->getType(); 6962 } else { 6963 EvalOK = this->Visit(E->getBase()); 6964 BaseTy = E->getBase()->getType(); 6965 } 6966 if (!EvalOK) { 6967 if (!InvalidBaseOK) 6968 return false; 6969 Result.setInvalid(E); 6970 return true; 6971 } 6972 6973 const ValueDecl *MD = E->getMemberDecl(); 6974 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 6975 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() == 6976 FD->getParent()->getCanonicalDecl() && "record / field mismatch"); 6977 (void)BaseTy; 6978 if (!HandleLValueMember(this->Info, E, Result, FD)) 6979 return false; 6980 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) { 6981 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) 6982 return false; 6983 } else 6984 return this->Error(E); 6985 6986 if (MD->getType()->isReferenceType()) { 6987 APValue RefValue; 6988 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result, 6989 RefValue)) 6990 return false; 6991 return Success(RefValue, E); 6992 } 6993 return true; 6994 } 6995 6996 bool VisitBinaryOperator(const BinaryOperator *E) { 6997 switch (E->getOpcode()) { 6998 default: 6999 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7000 7001 case BO_PtrMemD: 7002 case BO_PtrMemI: 7003 return HandleMemberPointerAccess(this->Info, E, Result); 7004 } 7005 } 7006 7007 bool VisitCastExpr(const CastExpr *E) { 7008 switch (E->getCastKind()) { 7009 default: 7010 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7011 7012 case CK_DerivedToBase: 7013 case CK_UncheckedDerivedToBase: 7014 if (!this->Visit(E->getSubExpr())) 7015 return false; 7016 7017 // Now figure out the necessary offset to add to the base LV to get from 7018 // the derived class to the base class. 7019 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(), 7020 Result); 7021 } 7022 } 7023 }; 7024 } 7025 7026 //===----------------------------------------------------------------------===// 7027 // LValue Evaluation 7028 // 7029 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11), 7030 // function designators (in C), decl references to void objects (in C), and 7031 // temporaries (if building with -Wno-address-of-temporary). 7032 // 7033 // LValue evaluation produces values comprising a base expression of one of the 7034 // following types: 7035 // - Declarations 7036 // * VarDecl 7037 // * FunctionDecl 7038 // - Literals 7039 // * CompoundLiteralExpr in C (and in global scope in C++) 7040 // * StringLiteral 7041 // * PredefinedExpr 7042 // * ObjCStringLiteralExpr 7043 // * ObjCEncodeExpr 7044 // * AddrLabelExpr 7045 // * BlockExpr 7046 // * CallExpr for a MakeStringConstant builtin 7047 // - typeid(T) expressions, as TypeInfoLValues 7048 // - Locals and temporaries 7049 // * MaterializeTemporaryExpr 7050 // * Any Expr, with a CallIndex indicating the function in which the temporary 7051 // was evaluated, for cases where the MaterializeTemporaryExpr is missing 7052 // from the AST (FIXME). 7053 // * A MaterializeTemporaryExpr that has static storage duration, with no 7054 // CallIndex, for a lifetime-extended temporary. 7055 // plus an offset in bytes. 7056 //===----------------------------------------------------------------------===// 7057 namespace { 7058 class LValueExprEvaluator 7059 : public LValueExprEvaluatorBase<LValueExprEvaluator> { 7060 public: 7061 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : 7062 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} 7063 7064 bool VisitVarDecl(const Expr *E, const VarDecl *VD); 7065 bool VisitUnaryPreIncDec(const UnaryOperator *UO); 7066 7067 bool VisitDeclRefExpr(const DeclRefExpr *E); 7068 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } 7069 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 7070 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 7071 bool VisitMemberExpr(const MemberExpr *E); 7072 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } 7073 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } 7074 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); 7075 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); 7076 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); 7077 bool VisitUnaryDeref(const UnaryOperator *E); 7078 bool VisitUnaryReal(const UnaryOperator *E); 7079 bool VisitUnaryImag(const UnaryOperator *E); 7080 bool VisitUnaryPreInc(const UnaryOperator *UO) { 7081 return VisitUnaryPreIncDec(UO); 7082 } 7083 bool VisitUnaryPreDec(const UnaryOperator *UO) { 7084 return VisitUnaryPreIncDec(UO); 7085 } 7086 bool VisitBinAssign(const BinaryOperator *BO); 7087 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); 7088 7089 bool VisitCastExpr(const CastExpr *E) { 7090 switch (E->getCastKind()) { 7091 default: 7092 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 7093 7094 case CK_LValueBitCast: 7095 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7096 if (!Visit(E->getSubExpr())) 7097 return false; 7098 Result.Designator.setInvalid(); 7099 return true; 7100 7101 case CK_BaseToDerived: 7102 if (!Visit(E->getSubExpr())) 7103 return false; 7104 return HandleBaseToDerivedCast(Info, E, Result); 7105 7106 case CK_Dynamic: 7107 if (!Visit(E->getSubExpr())) 7108 return false; 7109 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7110 } 7111 } 7112 }; 7113 } // end anonymous namespace 7114 7115 /// Evaluate an expression as an lvalue. This can be legitimately called on 7116 /// expressions which are not glvalues, in three cases: 7117 /// * function designators in C, and 7118 /// * "extern void" objects 7119 /// * @selector() expressions in Objective-C 7120 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, 7121 bool InvalidBaseOK) { 7122 assert(E->isGLValue() || E->getType()->isFunctionType() || 7123 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E)); 7124 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7125 } 7126 7127 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { 7128 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl())) 7129 return Success(FD); 7130 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 7131 return VisitVarDecl(E, VD); 7132 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl())) 7133 return Visit(BD->getBinding()); 7134 return Error(E); 7135 } 7136 7137 7138 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { 7139 7140 // If we are within a lambda's call operator, check whether the 'VD' referred 7141 // to within 'E' actually represents a lambda-capture that maps to a 7142 // data-member/field within the closure object, and if so, evaluate to the 7143 // field or what the field refers to. 7144 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) && 7145 isa<DeclRefExpr>(E) && 7146 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) { 7147 // We don't always have a complete capture-map when checking or inferring if 7148 // the function call operator meets the requirements of a constexpr function 7149 // - but we don't need to evaluate the captures to determine constexprness 7150 // (dcl.constexpr C++17). 7151 if (Info.checkingPotentialConstantExpression()) 7152 return false; 7153 7154 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) { 7155 // Start with 'Result' referring to the complete closure object... 7156 Result = *Info.CurrentCall->This; 7157 // ... then update it to refer to the field of the closure object 7158 // that represents the capture. 7159 if (!HandleLValueMember(Info, E, Result, FD)) 7160 return false; 7161 // And if the field is of reference type, update 'Result' to refer to what 7162 // the field refers to. 7163 if (FD->getType()->isReferenceType()) { 7164 APValue RVal; 7165 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, 7166 RVal)) 7167 return false; 7168 Result.setFrom(Info.Ctx, RVal); 7169 } 7170 return true; 7171 } 7172 } 7173 CallStackFrame *Frame = nullptr; 7174 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) { 7175 // Only if a local variable was declared in the function currently being 7176 // evaluated, do we expect to be able to find its value in the current 7177 // frame. (Otherwise it was likely declared in an enclosing context and 7178 // could either have a valid evaluatable value (for e.g. a constexpr 7179 // variable) or be ill-formed (and trigger an appropriate evaluation 7180 // diagnostic)). 7181 if (Info.CurrentCall->Callee && 7182 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { 7183 Frame = Info.CurrentCall; 7184 } 7185 } 7186 7187 if (!VD->getType()->isReferenceType()) { 7188 if (Frame) { 7189 Result.set({VD, Frame->Index, 7190 Info.CurrentCall->getCurrentTemporaryVersion(VD)}); 7191 return true; 7192 } 7193 return Success(VD); 7194 } 7195 7196 APValue *V; 7197 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr)) 7198 return false; 7199 if (!V->hasValue()) { 7200 // FIXME: Is it possible for V to be indeterminate here? If so, we should 7201 // adjust the diagnostic to say that. 7202 if (!Info.checkingPotentialConstantExpression()) 7203 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference); 7204 return false; 7205 } 7206 return Success(*V, E); 7207 } 7208 7209 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( 7210 const MaterializeTemporaryExpr *E) { 7211 // Walk through the expression to find the materialized temporary itself. 7212 SmallVector<const Expr *, 2> CommaLHSs; 7213 SmallVector<SubobjectAdjustment, 2> Adjustments; 7214 const Expr *Inner = E->GetTemporaryExpr()-> 7215 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 7216 7217 // If we passed any comma operators, evaluate their LHSs. 7218 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I) 7219 if (!EvaluateIgnoredValue(Info, CommaLHSs[I])) 7220 return false; 7221 7222 // A materialized temporary with static storage duration can appear within the 7223 // result of a constant expression evaluation, so we need to preserve its 7224 // value for use outside this evaluation. 7225 APValue *Value; 7226 if (E->getStorageDuration() == SD_Static) { 7227 Value = Info.Ctx.getMaterializedTemporaryValue(E, true); 7228 *Value = APValue(); 7229 Result.set(E); 7230 } else { 7231 Value = &Info.CurrentCall->createTemporary( 7232 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result); 7233 } 7234 7235 QualType Type = Inner->getType(); 7236 7237 // Materialize the temporary itself. 7238 if (!EvaluateInPlace(*Value, Info, Result, Inner)) { 7239 *Value = APValue(); 7240 return false; 7241 } 7242 7243 // Adjust our lvalue to refer to the desired subobject. 7244 for (unsigned I = Adjustments.size(); I != 0; /**/) { 7245 --I; 7246 switch (Adjustments[I].Kind) { 7247 case SubobjectAdjustment::DerivedToBaseAdjustment: 7248 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath, 7249 Type, Result)) 7250 return false; 7251 Type = Adjustments[I].DerivedToBase.BasePath->getType(); 7252 break; 7253 7254 case SubobjectAdjustment::FieldAdjustment: 7255 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field)) 7256 return false; 7257 Type = Adjustments[I].Field->getType(); 7258 break; 7259 7260 case SubobjectAdjustment::MemberPointerAdjustment: 7261 if (!HandleMemberPointerAccess(this->Info, Type, Result, 7262 Adjustments[I].Ptr.RHS)) 7263 return false; 7264 Type = Adjustments[I].Ptr.MPT->getPointeeType(); 7265 break; 7266 } 7267 } 7268 7269 return true; 7270 } 7271 7272 bool 7273 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 7274 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && 7275 "lvalue compound literal in c++?"); 7276 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can 7277 // only see this when folding in C, so there's no standard to follow here. 7278 return Success(E); 7279 } 7280 7281 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 7282 TypeInfoLValue TypeInfo; 7283 7284 if (!E->isPotentiallyEvaluated()) { 7285 if (E->isTypeOperand()) 7286 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr()); 7287 else 7288 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr()); 7289 } else { 7290 if (!Info.Ctx.getLangOpts().CPlusPlus2a) { 7291 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) 7292 << E->getExprOperand()->getType() 7293 << E->getExprOperand()->getSourceRange(); 7294 } 7295 7296 if (!Visit(E->getExprOperand())) 7297 return false; 7298 7299 Optional<DynamicType> DynType = 7300 ComputeDynamicType(Info, E, Result, AK_TypeId); 7301 if (!DynType) 7302 return false; 7303 7304 TypeInfo = 7305 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr()); 7306 } 7307 7308 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); 7309 } 7310 7311 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 7312 return Success(E); 7313 } 7314 7315 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { 7316 // Handle static data members. 7317 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) { 7318 VisitIgnoredBaseExpression(E->getBase()); 7319 return VisitVarDecl(E, VD); 7320 } 7321 7322 // Handle static member functions. 7323 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) { 7324 if (MD->isStatic()) { 7325 VisitIgnoredBaseExpression(E->getBase()); 7326 return Success(MD); 7327 } 7328 } 7329 7330 // Handle non-static data members. 7331 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); 7332 } 7333 7334 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 7335 // FIXME: Deal with vectors as array subscript bases. 7336 if (E->getBase()->getType()->isVectorType()) 7337 return Error(E); 7338 7339 bool Success = true; 7340 if (!evaluatePointer(E->getBase(), Result)) { 7341 if (!Info.noteFailure()) 7342 return false; 7343 Success = false; 7344 } 7345 7346 APSInt Index; 7347 if (!EvaluateInteger(E->getIdx(), Index, Info)) 7348 return false; 7349 7350 return Success && 7351 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); 7352 } 7353 7354 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { 7355 return evaluatePointer(E->getSubExpr(), Result); 7356 } 7357 7358 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 7359 if (!Visit(E->getSubExpr())) 7360 return false; 7361 // __real is a no-op on scalar lvalues. 7362 if (E->getSubExpr()->getType()->isAnyComplexType()) 7363 HandleLValueComplexElement(Info, E, Result, E->getType(), false); 7364 return true; 7365 } 7366 7367 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 7368 assert(E->getSubExpr()->getType()->isAnyComplexType() && 7369 "lvalue __imag__ on scalar?"); 7370 if (!Visit(E->getSubExpr())) 7371 return false; 7372 HandleLValueComplexElement(Info, E, Result, E->getType(), true); 7373 return true; 7374 } 7375 7376 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { 7377 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7378 return Error(UO); 7379 7380 if (!this->Visit(UO->getSubExpr())) 7381 return false; 7382 7383 return handleIncDec( 7384 this->Info, UO, Result, UO->getSubExpr()->getType(), 7385 UO->isIncrementOp(), nullptr); 7386 } 7387 7388 bool LValueExprEvaluator::VisitCompoundAssignOperator( 7389 const CompoundAssignOperator *CAO) { 7390 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7391 return Error(CAO); 7392 7393 APValue RHS; 7394 7395 // The overall lvalue result is the result of evaluating the LHS. 7396 if (!this->Visit(CAO->getLHS())) { 7397 if (Info.noteFailure()) 7398 Evaluate(RHS, this->Info, CAO->getRHS()); 7399 return false; 7400 } 7401 7402 if (!Evaluate(RHS, this->Info, CAO->getRHS())) 7403 return false; 7404 7405 return handleCompoundAssignment( 7406 this->Info, CAO, 7407 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), 7408 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); 7409 } 7410 7411 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { 7412 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) 7413 return Error(E); 7414 7415 APValue NewVal; 7416 7417 if (!this->Visit(E->getLHS())) { 7418 if (Info.noteFailure()) 7419 Evaluate(NewVal, this->Info, E->getRHS()); 7420 return false; 7421 } 7422 7423 if (!Evaluate(NewVal, this->Info, E->getRHS())) 7424 return false; 7425 7426 if (Info.getLangOpts().CPlusPlus2a && 7427 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result)) 7428 return false; 7429 7430 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(), 7431 NewVal); 7432 } 7433 7434 //===----------------------------------------------------------------------===// 7435 // Pointer Evaluation 7436 //===----------------------------------------------------------------------===// 7437 7438 /// Attempts to compute the number of bytes available at the pointer 7439 /// returned by a function with the alloc_size attribute. Returns true if we 7440 /// were successful. Places an unsigned number into `Result`. 7441 /// 7442 /// This expects the given CallExpr to be a call to a function with an 7443 /// alloc_size attribute. 7444 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 7445 const CallExpr *Call, 7446 llvm::APInt &Result) { 7447 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); 7448 7449 assert(AllocSize && AllocSize->getElemSizeParam().isValid()); 7450 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); 7451 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType()); 7452 if (Call->getNumArgs() <= SizeArgNo) 7453 return false; 7454 7455 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { 7456 Expr::EvalResult ExprResult; 7457 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) 7458 return false; 7459 Into = ExprResult.Val.getInt(); 7460 if (Into.isNegative() || !Into.isIntN(BitsInSizeT)) 7461 return false; 7462 Into = Into.zextOrSelf(BitsInSizeT); 7463 return true; 7464 }; 7465 7466 APSInt SizeOfElem; 7467 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem)) 7468 return false; 7469 7470 if (!AllocSize->getNumElemsParam().isValid()) { 7471 Result = std::move(SizeOfElem); 7472 return true; 7473 } 7474 7475 APSInt NumberOfElems; 7476 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex(); 7477 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems)) 7478 return false; 7479 7480 bool Overflow; 7481 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow); 7482 if (Overflow) 7483 return false; 7484 7485 Result = std::move(BytesAvailable); 7486 return true; 7487 } 7488 7489 /// Convenience function. LVal's base must be a call to an alloc_size 7490 /// function. 7491 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, 7492 const LValue &LVal, 7493 llvm::APInt &Result) { 7494 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && 7495 "Can't get the size of a non alloc_size function"); 7496 const auto *Base = LVal.getLValueBase().get<const Expr *>(); 7497 const CallExpr *CE = tryUnwrapAllocSizeCall(Base); 7498 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); 7499 } 7500 7501 /// Attempts to evaluate the given LValueBase as the result of a call to 7502 /// a function with the alloc_size attribute. If it was possible to do so, this 7503 /// function will return true, make Result's Base point to said function call, 7504 /// and mark Result's Base as invalid. 7505 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, 7506 LValue &Result) { 7507 if (Base.isNull()) 7508 return false; 7509 7510 // Because we do no form of static analysis, we only support const variables. 7511 // 7512 // Additionally, we can't support parameters, nor can we support static 7513 // variables (in the latter case, use-before-assign isn't UB; in the former, 7514 // we have no clue what they'll be assigned to). 7515 const auto *VD = 7516 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>()); 7517 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) 7518 return false; 7519 7520 const Expr *Init = VD->getAnyInitializer(); 7521 if (!Init) 7522 return false; 7523 7524 const Expr *E = Init->IgnoreParens(); 7525 if (!tryUnwrapAllocSizeCall(E)) 7526 return false; 7527 7528 // Store E instead of E unwrapped so that the type of the LValue's base is 7529 // what the user wanted. 7530 Result.setInvalid(E); 7531 7532 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType(); 7533 Result.addUnsizedArray(Info, E, Pointee); 7534 return true; 7535 } 7536 7537 namespace { 7538 class PointerExprEvaluator 7539 : public ExprEvaluatorBase<PointerExprEvaluator> { 7540 LValue &Result; 7541 bool InvalidBaseOK; 7542 7543 bool Success(const Expr *E) { 7544 Result.set(E); 7545 return true; 7546 } 7547 7548 bool evaluateLValue(const Expr *E, LValue &Result) { 7549 return EvaluateLValue(E, Result, Info, InvalidBaseOK); 7550 } 7551 7552 bool evaluatePointer(const Expr *E, LValue &Result) { 7553 return EvaluatePointer(E, Result, Info, InvalidBaseOK); 7554 } 7555 7556 bool visitNonBuiltinCallExpr(const CallExpr *E); 7557 public: 7558 7559 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) 7560 : ExprEvaluatorBaseTy(info), Result(Result), 7561 InvalidBaseOK(InvalidBaseOK) {} 7562 7563 bool Success(const APValue &V, const Expr *E) { 7564 Result.setFrom(Info.Ctx, V); 7565 return true; 7566 } 7567 bool ZeroInitialization(const Expr *E) { 7568 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType()); 7569 Result.setNull(E->getType(), TargetVal); 7570 return true; 7571 } 7572 7573 bool VisitBinaryOperator(const BinaryOperator *E); 7574 bool VisitCastExpr(const CastExpr* E); 7575 bool VisitUnaryAddrOf(const UnaryOperator *E); 7576 bool VisitObjCStringLiteral(const ObjCStringLiteral *E) 7577 { return Success(E); } 7578 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 7579 if (E->isExpressibleAsConstantInitializer()) 7580 return Success(E); 7581 if (Info.noteFailure()) 7582 EvaluateIgnoredValue(Info, E->getSubExpr()); 7583 return Error(E); 7584 } 7585 bool VisitAddrLabelExpr(const AddrLabelExpr *E) 7586 { return Success(E); } 7587 bool VisitCallExpr(const CallExpr *E); 7588 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 7589 bool VisitBlockExpr(const BlockExpr *E) { 7590 if (!E->getBlockDecl()->hasCaptures()) 7591 return Success(E); 7592 return Error(E); 7593 } 7594 bool VisitCXXThisExpr(const CXXThisExpr *E) { 7595 // Can't look at 'this' when checking a potential constant expression. 7596 if (Info.checkingPotentialConstantExpression()) 7597 return false; 7598 if (!Info.CurrentCall->This) { 7599 if (Info.getLangOpts().CPlusPlus11) 7600 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit(); 7601 else 7602 Info.FFDiag(E); 7603 return false; 7604 } 7605 Result = *Info.CurrentCall->This; 7606 // If we are inside a lambda's call operator, the 'this' expression refers 7607 // to the enclosing '*this' object (either by value or reference) which is 7608 // either copied into the closure object's field that represents the '*this' 7609 // or refers to '*this'. 7610 if (isLambdaCallOperator(Info.CurrentCall->Callee)) { 7611 // Update 'Result' to refer to the data member/field of the closure object 7612 // that represents the '*this' capture. 7613 if (!HandleLValueMember(Info, E, Result, 7614 Info.CurrentCall->LambdaThisCaptureField)) 7615 return false; 7616 // If we captured '*this' by reference, replace the field with its referent. 7617 if (Info.CurrentCall->LambdaThisCaptureField->getType() 7618 ->isPointerType()) { 7619 APValue RVal; 7620 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result, 7621 RVal)) 7622 return false; 7623 7624 Result.setFrom(Info.Ctx, RVal); 7625 } 7626 } 7627 return true; 7628 } 7629 7630 bool VisitCXXNewExpr(const CXXNewExpr *E); 7631 7632 bool VisitSourceLocExpr(const SourceLocExpr *E) { 7633 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); 7634 APValue LValResult = E->EvaluateInContext( 7635 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 7636 Result.setFrom(Info.Ctx, LValResult); 7637 return true; 7638 } 7639 7640 // FIXME: Missing: @protocol, @selector 7641 }; 7642 } // end anonymous namespace 7643 7644 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, 7645 bool InvalidBaseOK) { 7646 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 7647 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); 7648 } 7649 7650 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 7651 if (E->getOpcode() != BO_Add && 7652 E->getOpcode() != BO_Sub) 7653 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 7654 7655 const Expr *PExp = E->getLHS(); 7656 const Expr *IExp = E->getRHS(); 7657 if (IExp->getType()->isPointerType()) 7658 std::swap(PExp, IExp); 7659 7660 bool EvalPtrOK = evaluatePointer(PExp, Result); 7661 if (!EvalPtrOK && !Info.noteFailure()) 7662 return false; 7663 7664 llvm::APSInt Offset; 7665 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK) 7666 return false; 7667 7668 if (E->getOpcode() == BO_Sub) 7669 negateAsSigned(Offset); 7670 7671 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType(); 7672 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); 7673 } 7674 7675 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 7676 return evaluateLValue(E->getSubExpr(), Result); 7677 } 7678 7679 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 7680 const Expr *SubExpr = E->getSubExpr(); 7681 7682 switch (E->getCastKind()) { 7683 default: 7684 break; 7685 case CK_BitCast: 7686 case CK_CPointerToObjCPointerCast: 7687 case CK_BlockPointerToObjCPointerCast: 7688 case CK_AnyPointerToBlockPointerCast: 7689 case CK_AddressSpaceConversion: 7690 if (!Visit(SubExpr)) 7691 return false; 7692 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are 7693 // permitted in constant expressions in C++11. Bitcasts from cv void* are 7694 // also static_casts, but we disallow them as a resolution to DR1312. 7695 if (!E->getType()->isVoidPointerType()) { 7696 Result.Designator.setInvalid(); 7697 if (SubExpr->getType()->isVoidPointerType()) 7698 CCEDiag(E, diag::note_constexpr_invalid_cast) 7699 << 3 << SubExpr->getType(); 7700 else 7701 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7702 } 7703 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr) 7704 ZeroInitialization(E); 7705 return true; 7706 7707 case CK_DerivedToBase: 7708 case CK_UncheckedDerivedToBase: 7709 if (!evaluatePointer(E->getSubExpr(), Result)) 7710 return false; 7711 if (!Result.Base && Result.Offset.isZero()) 7712 return true; 7713 7714 // Now figure out the necessary offset to add to the base LV to get from 7715 // the derived class to the base class. 7716 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> 7717 castAs<PointerType>()->getPointeeType(), 7718 Result); 7719 7720 case CK_BaseToDerived: 7721 if (!Visit(E->getSubExpr())) 7722 return false; 7723 if (!Result.Base && Result.Offset.isZero()) 7724 return true; 7725 return HandleBaseToDerivedCast(Info, E, Result); 7726 7727 case CK_Dynamic: 7728 if (!Visit(E->getSubExpr())) 7729 return false; 7730 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result); 7731 7732 case CK_NullToPointer: 7733 VisitIgnoredValue(E->getSubExpr()); 7734 return ZeroInitialization(E); 7735 7736 case CK_IntegralToPointer: { 7737 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 7738 7739 APValue Value; 7740 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info)) 7741 break; 7742 7743 if (Value.isInt()) { 7744 unsigned Size = Info.Ctx.getTypeSize(E->getType()); 7745 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); 7746 Result.Base = (Expr*)nullptr; 7747 Result.InvalidBase = false; 7748 Result.Offset = CharUnits::fromQuantity(N); 7749 Result.Designator.setInvalid(); 7750 Result.IsNullPtr = false; 7751 return true; 7752 } else { 7753 // Cast is of an lvalue, no need to change value. 7754 Result.setFrom(Info.Ctx, Value); 7755 return true; 7756 } 7757 } 7758 7759 case CK_ArrayToPointerDecay: { 7760 if (SubExpr->isGLValue()) { 7761 if (!evaluateLValue(SubExpr, Result)) 7762 return false; 7763 } else { 7764 APValue &Value = Info.CurrentCall->createTemporary( 7765 SubExpr, SubExpr->getType(), false, Result); 7766 if (!EvaluateInPlace(Value, Info, Result, SubExpr)) 7767 return false; 7768 } 7769 // The result is a pointer to the first element of the array. 7770 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType()); 7771 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 7772 Result.addArray(Info, E, CAT); 7773 else 7774 Result.addUnsizedArray(Info, E, AT->getElementType()); 7775 return true; 7776 } 7777 7778 case CK_FunctionToPointerDecay: 7779 return evaluateLValue(SubExpr, Result); 7780 7781 case CK_LValueToRValue: { 7782 LValue LVal; 7783 if (!evaluateLValue(E->getSubExpr(), LVal)) 7784 return false; 7785 7786 APValue RVal; 7787 // Note, we use the subexpression's type in order to retain cv-qualifiers. 7788 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(), 7789 LVal, RVal)) 7790 return InvalidBaseOK && 7791 evaluateLValueAsAllocSize(Info, LVal.Base, Result); 7792 return Success(RVal, E); 7793 } 7794 } 7795 7796 return ExprEvaluatorBaseTy::VisitCastExpr(E); 7797 } 7798 7799 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T, 7800 UnaryExprOrTypeTrait ExprKind) { 7801 // C++ [expr.alignof]p3: 7802 // When alignof is applied to a reference type, the result is the 7803 // alignment of the referenced type. 7804 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) 7805 T = Ref->getPointeeType(); 7806 7807 if (T.getQualifiers().hasUnaligned()) 7808 return CharUnits::One(); 7809 7810 const bool AlignOfReturnsPreferred = 7811 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 7812 7813 // __alignof is defined to return the preferred alignment. 7814 // Before 8, clang returned the preferred alignment for alignof and _Alignof 7815 // as well. 7816 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 7817 return Info.Ctx.toCharUnitsFromBits( 7818 Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); 7819 // alignof and _Alignof are defined to return the ABI alignment. 7820 else if (ExprKind == UETT_AlignOf) 7821 return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); 7822 else 7823 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); 7824 } 7825 7826 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, 7827 UnaryExprOrTypeTrait ExprKind) { 7828 E = E->IgnoreParens(); 7829 7830 // The kinds of expressions that we have special-case logic here for 7831 // should be kept up to date with the special checks for those 7832 // expressions in Sema. 7833 7834 // alignof decl is always accepted, even if it doesn't make sense: we default 7835 // to 1 in those cases. 7836 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 7837 return Info.Ctx.getDeclAlign(DRE->getDecl(), 7838 /*RefAsPointee*/true); 7839 7840 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 7841 return Info.Ctx.getDeclAlign(ME->getMemberDecl(), 7842 /*RefAsPointee*/true); 7843 7844 return GetAlignOfType(Info, E->getType(), ExprKind); 7845 } 7846 7847 // To be clear: this happily visits unsupported builtins. Better name welcomed. 7848 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { 7849 if (ExprEvaluatorBaseTy::VisitCallExpr(E)) 7850 return true; 7851 7852 if (!(InvalidBaseOK && getAllocSizeAttr(E))) 7853 return false; 7854 7855 Result.setInvalid(E); 7856 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType(); 7857 Result.addUnsizedArray(Info, E, PointeeTy); 7858 return true; 7859 } 7860 7861 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { 7862 if (IsStringLiteralCall(E)) 7863 return Success(E); 7864 7865 if (unsigned BuiltinOp = E->getBuiltinCallee()) 7866 return VisitBuiltinCallExpr(E, BuiltinOp); 7867 7868 return visitNonBuiltinCallExpr(E); 7869 } 7870 7871 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 7872 unsigned BuiltinOp) { 7873 switch (BuiltinOp) { 7874 case Builtin::BI__builtin_addressof: 7875 return evaluateLValue(E->getArg(0), Result); 7876 case Builtin::BI__builtin_assume_aligned: { 7877 // We need to be very careful here because: if the pointer does not have the 7878 // asserted alignment, then the behavior is undefined, and undefined 7879 // behavior is non-constant. 7880 if (!evaluatePointer(E->getArg(0), Result)) 7881 return false; 7882 7883 LValue OffsetResult(Result); 7884 APSInt Alignment; 7885 if (!EvaluateInteger(E->getArg(1), Alignment, Info)) 7886 return false; 7887 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue()); 7888 7889 if (E->getNumArgs() > 2) { 7890 APSInt Offset; 7891 if (!EvaluateInteger(E->getArg(2), Offset, Info)) 7892 return false; 7893 7894 int64_t AdditionalOffset = -Offset.getZExtValue(); 7895 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset); 7896 } 7897 7898 // If there is a base object, then it must have the correct alignment. 7899 if (OffsetResult.Base) { 7900 CharUnits BaseAlignment; 7901 if (const ValueDecl *VD = 7902 OffsetResult.Base.dyn_cast<const ValueDecl*>()) { 7903 BaseAlignment = Info.Ctx.getDeclAlign(VD); 7904 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) { 7905 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf); 7906 } else { 7907 BaseAlignment = GetAlignOfType( 7908 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf); 7909 } 7910 7911 if (BaseAlignment < Align) { 7912 Result.Designator.setInvalid(); 7913 // FIXME: Add support to Diagnostic for long / long long. 7914 CCEDiag(E->getArg(0), 7915 diag::note_constexpr_baa_insufficient_alignment) << 0 7916 << (unsigned)BaseAlignment.getQuantity() 7917 << (unsigned)Align.getQuantity(); 7918 return false; 7919 } 7920 } 7921 7922 // The offset must also have the correct alignment. 7923 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) { 7924 Result.Designator.setInvalid(); 7925 7926 (OffsetResult.Base 7927 ? CCEDiag(E->getArg(0), 7928 diag::note_constexpr_baa_insufficient_alignment) << 1 7929 : CCEDiag(E->getArg(0), 7930 diag::note_constexpr_baa_value_insufficient_alignment)) 7931 << (int)OffsetResult.Offset.getQuantity() 7932 << (unsigned)Align.getQuantity(); 7933 return false; 7934 } 7935 7936 return true; 7937 } 7938 case Builtin::BI__builtin_launder: 7939 return evaluatePointer(E->getArg(0), Result); 7940 case Builtin::BIstrchr: 7941 case Builtin::BIwcschr: 7942 case Builtin::BImemchr: 7943 case Builtin::BIwmemchr: 7944 if (Info.getLangOpts().CPlusPlus11) 7945 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 7946 << /*isConstexpr*/0 << /*isConstructor*/0 7947 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 7948 else 7949 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 7950 LLVM_FALLTHROUGH; 7951 case Builtin::BI__builtin_strchr: 7952 case Builtin::BI__builtin_wcschr: 7953 case Builtin::BI__builtin_memchr: 7954 case Builtin::BI__builtin_char_memchr: 7955 case Builtin::BI__builtin_wmemchr: { 7956 if (!Visit(E->getArg(0))) 7957 return false; 7958 APSInt Desired; 7959 if (!EvaluateInteger(E->getArg(1), Desired, Info)) 7960 return false; 7961 uint64_t MaxLength = uint64_t(-1); 7962 if (BuiltinOp != Builtin::BIstrchr && 7963 BuiltinOp != Builtin::BIwcschr && 7964 BuiltinOp != Builtin::BI__builtin_strchr && 7965 BuiltinOp != Builtin::BI__builtin_wcschr) { 7966 APSInt N; 7967 if (!EvaluateInteger(E->getArg(2), N, Info)) 7968 return false; 7969 MaxLength = N.getExtValue(); 7970 } 7971 // We cannot find the value if there are no candidates to match against. 7972 if (MaxLength == 0u) 7973 return ZeroInitialization(E); 7974 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) || 7975 Result.Designator.Invalid) 7976 return false; 7977 QualType CharTy = Result.Designator.getType(Info.Ctx); 7978 bool IsRawByte = BuiltinOp == Builtin::BImemchr || 7979 BuiltinOp == Builtin::BI__builtin_memchr; 7980 assert(IsRawByte || 7981 Info.Ctx.hasSameUnqualifiedType( 7982 CharTy, E->getArg(0)->getType()->getPointeeType())); 7983 // Pointers to const void may point to objects of incomplete type. 7984 if (IsRawByte && CharTy->isIncompleteType()) { 7985 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; 7986 return false; 7987 } 7988 // Give up on byte-oriented matching against multibyte elements. 7989 // FIXME: We can compare the bytes in the correct order. 7990 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One()) 7991 return false; 7992 // Figure out what value we're actually looking for (after converting to 7993 // the corresponding unsigned type if necessary). 7994 uint64_t DesiredVal; 7995 bool StopAtNull = false; 7996 switch (BuiltinOp) { 7997 case Builtin::BIstrchr: 7998 case Builtin::BI__builtin_strchr: 7999 // strchr compares directly to the passed integer, and therefore 8000 // always fails if given an int that is not a char. 8001 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy, 8002 E->getArg(1)->getType(), 8003 Desired), 8004 Desired)) 8005 return ZeroInitialization(E); 8006 StopAtNull = true; 8007 LLVM_FALLTHROUGH; 8008 case Builtin::BImemchr: 8009 case Builtin::BI__builtin_memchr: 8010 case Builtin::BI__builtin_char_memchr: 8011 // memchr compares by converting both sides to unsigned char. That's also 8012 // correct for strchr if we get this far (to cope with plain char being 8013 // unsigned in the strchr case). 8014 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue(); 8015 break; 8016 8017 case Builtin::BIwcschr: 8018 case Builtin::BI__builtin_wcschr: 8019 StopAtNull = true; 8020 LLVM_FALLTHROUGH; 8021 case Builtin::BIwmemchr: 8022 case Builtin::BI__builtin_wmemchr: 8023 // wcschr and wmemchr are given a wchar_t to look for. Just use it. 8024 DesiredVal = Desired.getZExtValue(); 8025 break; 8026 } 8027 8028 for (; MaxLength; --MaxLength) { 8029 APValue Char; 8030 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) || 8031 !Char.isInt()) 8032 return false; 8033 if (Char.getInt().getZExtValue() == DesiredVal) 8034 return true; 8035 if (StopAtNull && !Char.getInt()) 8036 break; 8037 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1)) 8038 return false; 8039 } 8040 // Not found: return nullptr. 8041 return ZeroInitialization(E); 8042 } 8043 8044 case Builtin::BImemcpy: 8045 case Builtin::BImemmove: 8046 case Builtin::BIwmemcpy: 8047 case Builtin::BIwmemmove: 8048 if (Info.getLangOpts().CPlusPlus11) 8049 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 8050 << /*isConstexpr*/0 << /*isConstructor*/0 8051 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 8052 else 8053 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 8054 LLVM_FALLTHROUGH; 8055 case Builtin::BI__builtin_memcpy: 8056 case Builtin::BI__builtin_memmove: 8057 case Builtin::BI__builtin_wmemcpy: 8058 case Builtin::BI__builtin_wmemmove: { 8059 bool WChar = BuiltinOp == Builtin::BIwmemcpy || 8060 BuiltinOp == Builtin::BIwmemmove || 8061 BuiltinOp == Builtin::BI__builtin_wmemcpy || 8062 BuiltinOp == Builtin::BI__builtin_wmemmove; 8063 bool Move = BuiltinOp == Builtin::BImemmove || 8064 BuiltinOp == Builtin::BIwmemmove || 8065 BuiltinOp == Builtin::BI__builtin_memmove || 8066 BuiltinOp == Builtin::BI__builtin_wmemmove; 8067 8068 // The result of mem* is the first argument. 8069 if (!Visit(E->getArg(0))) 8070 return false; 8071 LValue Dest = Result; 8072 8073 LValue Src; 8074 if (!EvaluatePointer(E->getArg(1), Src, Info)) 8075 return false; 8076 8077 APSInt N; 8078 if (!EvaluateInteger(E->getArg(2), N, Info)) 8079 return false; 8080 assert(!N.isSigned() && "memcpy and friends take an unsigned size"); 8081 8082 // If the size is zero, we treat this as always being a valid no-op. 8083 // (Even if one of the src and dest pointers is null.) 8084 if (!N) 8085 return true; 8086 8087 // Otherwise, if either of the operands is null, we can't proceed. Don't 8088 // try to determine the type of the copied objects, because there aren't 8089 // any. 8090 if (!Src.Base || !Dest.Base) { 8091 APValue Val; 8092 (!Src.Base ? Src : Dest).moveInto(Val); 8093 Info.FFDiag(E, diag::note_constexpr_memcpy_null) 8094 << Move << WChar << !!Src.Base 8095 << Val.getAsString(Info.Ctx, E->getArg(0)->getType()); 8096 return false; 8097 } 8098 if (Src.Designator.Invalid || Dest.Designator.Invalid) 8099 return false; 8100 8101 // We require that Src and Dest are both pointers to arrays of 8102 // trivially-copyable type. (For the wide version, the designator will be 8103 // invalid if the designated object is not a wchar_t.) 8104 QualType T = Dest.Designator.getType(Info.Ctx); 8105 QualType SrcT = Src.Designator.getType(Info.Ctx); 8106 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) { 8107 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T; 8108 return false; 8109 } 8110 if (T->isIncompleteType()) { 8111 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T; 8112 return false; 8113 } 8114 if (!T.isTriviallyCopyableType(Info.Ctx)) { 8115 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T; 8116 return false; 8117 } 8118 8119 // Figure out how many T's we're copying. 8120 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity(); 8121 if (!WChar) { 8122 uint64_t Remainder; 8123 llvm::APInt OrigN = N; 8124 llvm::APInt::udivrem(OrigN, TSize, N, Remainder); 8125 if (Remainder) { 8126 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8127 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false) 8128 << (unsigned)TSize; 8129 return false; 8130 } 8131 } 8132 8133 // Check that the copying will remain within the arrays, just so that we 8134 // can give a more meaningful diagnostic. This implicitly also checks that 8135 // N fits into 64 bits. 8136 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second; 8137 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second; 8138 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { 8139 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) 8140 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T 8141 << N.toString(10, /*Signed*/false); 8142 return false; 8143 } 8144 uint64_t NElems = N.getZExtValue(); 8145 uint64_t NBytes = NElems * TSize; 8146 8147 // Check for overlap. 8148 int Direction = 1; 8149 if (HasSameBase(Src, Dest)) { 8150 uint64_t SrcOffset = Src.getLValueOffset().getQuantity(); 8151 uint64_t DestOffset = Dest.getLValueOffset().getQuantity(); 8152 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) { 8153 // Dest is inside the source region. 8154 if (!Move) { 8155 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8156 return false; 8157 } 8158 // For memmove and friends, copy backwards. 8159 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) || 8160 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1)) 8161 return false; 8162 Direction = -1; 8163 } else if (!Move && SrcOffset >= DestOffset && 8164 SrcOffset - DestOffset < NBytes) { 8165 // Src is inside the destination region for memcpy: invalid. 8166 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar; 8167 return false; 8168 } 8169 } 8170 8171 while (true) { 8172 APValue Val; 8173 // FIXME: Set WantObjectRepresentation to true if we're copying a 8174 // char-like type? 8175 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) || 8176 !handleAssignment(Info, E, Dest, T, Val)) 8177 return false; 8178 // Do not iterate past the last element; if we're copying backwards, that 8179 // might take us off the start of the array. 8180 if (--NElems == 0) 8181 return true; 8182 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) || 8183 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction)) 8184 return false; 8185 } 8186 } 8187 8188 default: 8189 return visitNonBuiltinCallExpr(E); 8190 } 8191 } 8192 8193 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 8194 APValue &Result, const InitListExpr *ILE, 8195 QualType AllocType); 8196 8197 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { 8198 if (!Info.getLangOpts().CPlusPlus2a) 8199 Info.CCEDiag(E, diag::note_constexpr_new); 8200 8201 // We cannot speculatively evaluate a delete expression. 8202 if (Info.SpeculativeEvaluationDepth) 8203 return false; 8204 8205 FunctionDecl *OperatorNew = E->getOperatorNew(); 8206 if (!OperatorNew->isReplaceableGlobalAllocationFunction()) { 8207 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 8208 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew; 8209 return false; 8210 } 8211 8212 bool IsNothrow = false; 8213 if (E->getNumPlacementArgs()) { 8214 // The only new-placement list we support is of the form (std::nothrow). 8215 // 8216 // FIXME: There is no restriction on this, but it's not clear that any 8217 // other form makes any sense. We get here for cases such as: 8218 // 8219 // new (std::align_val_t{N}) X(int) 8220 // 8221 // (which should presumably be valid only if N is a multiple of 8222 // alignof(int), and in any case can't be deallocated unless N is 8223 // alignof(X) and X has new-extended alignment). 8224 if (E->getNumPlacementArgs() != 1 || 8225 !E->getPlacementArg(0)->getType()->isNothrowT()) 8226 return Error(E, diag::note_constexpr_new_placement); 8227 8228 LValue Nothrow; 8229 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info)) 8230 return false; 8231 IsNothrow = true; 8232 } 8233 8234 const Expr *Init = E->getInitializer(); 8235 const InitListExpr *ResizedArrayILE = nullptr; 8236 8237 QualType AllocType = E->getAllocatedType(); 8238 if (Optional<const Expr*> ArraySize = E->getArraySize()) { 8239 const Expr *Stripped = *ArraySize; 8240 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 8241 Stripped = ICE->getSubExpr()) 8242 if (ICE->getCastKind() != CK_NoOp && 8243 ICE->getCastKind() != CK_IntegralCast) 8244 break; 8245 8246 llvm::APSInt ArrayBound; 8247 if (!EvaluateInteger(Stripped, ArrayBound, Info)) 8248 return false; 8249 8250 // C++ [expr.new]p9: 8251 // The expression is erroneous if: 8252 // -- [...] its value before converting to size_t [or] applying the 8253 // second standard conversion sequence is less than zero 8254 if (ArrayBound.isSigned() && ArrayBound.isNegative()) { 8255 if (IsNothrow) 8256 return ZeroInitialization(E); 8257 8258 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative) 8259 << ArrayBound << (*ArraySize)->getSourceRange(); 8260 return false; 8261 } 8262 8263 // -- its value is such that the size of the allocated object would 8264 // exceed the implementation-defined limit 8265 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType, 8266 ArrayBound) > 8267 ConstantArrayType::getMaxSizeBits(Info.Ctx)) { 8268 if (IsNothrow) 8269 return ZeroInitialization(E); 8270 8271 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) 8272 << ArrayBound << (*ArraySize)->getSourceRange(); 8273 return false; 8274 } 8275 8276 // -- the new-initializer is a braced-init-list and the number of 8277 // array elements for which initializers are provided [...] 8278 // exceeds the number of elements to initialize 8279 if (Init) { 8280 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType()); 8281 assert(CAT && "unexpected type for array initializer"); 8282 8283 unsigned Bits = 8284 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth()); 8285 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits); 8286 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits); 8287 if (InitBound.ugt(AllocBound)) { 8288 if (IsNothrow) 8289 return ZeroInitialization(E); 8290 8291 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small) 8292 << AllocBound.toString(10, /*Signed=*/false) 8293 << InitBound.toString(10, /*Signed=*/false) 8294 << (*ArraySize)->getSourceRange(); 8295 return false; 8296 } 8297 8298 // If the sizes differ, we must have an initializer list, and we need 8299 // special handling for this case when we initialize. 8300 if (InitBound != AllocBound) 8301 ResizedArrayILE = cast<InitListExpr>(Init); 8302 } 8303 8304 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, 8305 ArrayType::Normal, 0); 8306 } else { 8307 assert(!AllocType->isArrayType() && 8308 "array allocation with non-array new"); 8309 } 8310 8311 // Perform the allocation and obtain a pointer to the resulting object. 8312 APValue *Val = Info.createHeapAlloc(E, AllocType, Result); 8313 if (!Val) 8314 return false; 8315 8316 if (ResizedArrayILE) { 8317 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE, 8318 AllocType)) 8319 return false; 8320 } else if (Init) { 8321 if (!EvaluateInPlace(*Val, Info, Result, Init)) 8322 return false; 8323 } else { 8324 *Val = getDefaultInitValue(AllocType); 8325 } 8326 8327 // Array new returns a pointer to the first element, not a pointer to the 8328 // array. 8329 if (auto *AT = AllocType->getAsArrayTypeUnsafe()) 8330 Result.addArray(Info, E, cast<ConstantArrayType>(AT)); 8331 8332 return true; 8333 } 8334 //===----------------------------------------------------------------------===// 8335 // Member Pointer Evaluation 8336 //===----------------------------------------------------------------------===// 8337 8338 namespace { 8339 class MemberPointerExprEvaluator 8340 : public ExprEvaluatorBase<MemberPointerExprEvaluator> { 8341 MemberPtr &Result; 8342 8343 bool Success(const ValueDecl *D) { 8344 Result = MemberPtr(D); 8345 return true; 8346 } 8347 public: 8348 8349 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) 8350 : ExprEvaluatorBaseTy(Info), Result(Result) {} 8351 8352 bool Success(const APValue &V, const Expr *E) { 8353 Result.setFrom(V); 8354 return true; 8355 } 8356 bool ZeroInitialization(const Expr *E) { 8357 return Success((const ValueDecl*)nullptr); 8358 } 8359 8360 bool VisitCastExpr(const CastExpr *E); 8361 bool VisitUnaryAddrOf(const UnaryOperator *E); 8362 }; 8363 } // end anonymous namespace 8364 8365 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, 8366 EvalInfo &Info) { 8367 assert(E->isRValue() && E->getType()->isMemberPointerType()); 8368 return MemberPointerExprEvaluator(Info, Result).Visit(E); 8369 } 8370 8371 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { 8372 switch (E->getCastKind()) { 8373 default: 8374 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8375 8376 case CK_NullToMemberPointer: 8377 VisitIgnoredValue(E->getSubExpr()); 8378 return ZeroInitialization(E); 8379 8380 case CK_BaseToDerivedMemberPointer: { 8381 if (!Visit(E->getSubExpr())) 8382 return false; 8383 if (E->path_empty()) 8384 return true; 8385 // Base-to-derived member pointer casts store the path in derived-to-base 8386 // order, so iterate backwards. The CXXBaseSpecifier also provides us with 8387 // the wrong end of the derived->base arc, so stagger the path by one class. 8388 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter; 8389 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); 8390 PathI != PathE; ++PathI) { 8391 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 8392 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); 8393 if (!Result.castToDerived(Derived)) 8394 return Error(E); 8395 } 8396 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass(); 8397 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) 8398 return Error(E); 8399 return true; 8400 } 8401 8402 case CK_DerivedToBaseMemberPointer: 8403 if (!Visit(E->getSubExpr())) 8404 return false; 8405 for (CastExpr::path_const_iterator PathI = E->path_begin(), 8406 PathE = E->path_end(); PathI != PathE; ++PathI) { 8407 assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); 8408 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 8409 if (!Result.castToBase(Base)) 8410 return Error(E); 8411 } 8412 return true; 8413 } 8414 } 8415 8416 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { 8417 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 8418 // member can be formed. 8419 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl()); 8420 } 8421 8422 //===----------------------------------------------------------------------===// 8423 // Record Evaluation 8424 //===----------------------------------------------------------------------===// 8425 8426 namespace { 8427 class RecordExprEvaluator 8428 : public ExprEvaluatorBase<RecordExprEvaluator> { 8429 const LValue &This; 8430 APValue &Result; 8431 public: 8432 8433 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) 8434 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} 8435 8436 bool Success(const APValue &V, const Expr *E) { 8437 Result = V; 8438 return true; 8439 } 8440 bool ZeroInitialization(const Expr *E) { 8441 return ZeroInitialization(E, E->getType()); 8442 } 8443 bool ZeroInitialization(const Expr *E, QualType T); 8444 8445 bool VisitCallExpr(const CallExpr *E) { 8446 return handleCallExpr(E, Result, &This); 8447 } 8448 bool VisitCastExpr(const CastExpr *E); 8449 bool VisitInitListExpr(const InitListExpr *E); 8450 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 8451 return VisitCXXConstructExpr(E, E->getType()); 8452 } 8453 bool VisitLambdaExpr(const LambdaExpr *E); 8454 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); 8455 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); 8456 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); 8457 bool VisitBinCmp(const BinaryOperator *E); 8458 }; 8459 } 8460 8461 /// Perform zero-initialization on an object of non-union class type. 8462 /// C++11 [dcl.init]p5: 8463 /// To zero-initialize an object or reference of type T means: 8464 /// [...] 8465 /// -- if T is a (possibly cv-qualified) non-union class type, 8466 /// each non-static data member and each base-class subobject is 8467 /// zero-initialized 8468 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, 8469 const RecordDecl *RD, 8470 const LValue &This, APValue &Result) { 8471 assert(!RD->isUnion() && "Expected non-union class type"); 8472 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 8473 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, 8474 std::distance(RD->field_begin(), RD->field_end())); 8475 8476 if (RD->isInvalidDecl()) return false; 8477 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 8478 8479 if (CD) { 8480 unsigned Index = 0; 8481 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), 8482 End = CD->bases_end(); I != End; ++I, ++Index) { 8483 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 8484 LValue Subobject = This; 8485 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) 8486 return false; 8487 if (!HandleClassZeroInitialization(Info, E, Base, Subobject, 8488 Result.getStructBase(Index))) 8489 return false; 8490 } 8491 } 8492 8493 for (const auto *I : RD->fields()) { 8494 // -- if T is a reference type, no initialization is performed. 8495 if (I->getType()->isReferenceType()) 8496 continue; 8497 8498 LValue Subobject = This; 8499 if (!HandleLValueMember(Info, E, Subobject, I, &Layout)) 8500 return false; 8501 8502 ImplicitValueInitExpr VIE(I->getType()); 8503 if (!EvaluateInPlace( 8504 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) 8505 return false; 8506 } 8507 8508 return true; 8509 } 8510 8511 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { 8512 const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); 8513 if (RD->isInvalidDecl()) return false; 8514 if (RD->isUnion()) { 8515 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 8516 // object's first non-static named data member is zero-initialized 8517 RecordDecl::field_iterator I = RD->field_begin(); 8518 if (I == RD->field_end()) { 8519 Result = APValue((const FieldDecl*)nullptr); 8520 return true; 8521 } 8522 8523 LValue Subobject = This; 8524 if (!HandleLValueMember(Info, E, Subobject, *I)) 8525 return false; 8526 Result = APValue(*I); 8527 ImplicitValueInitExpr VIE(I->getType()); 8528 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE); 8529 } 8530 8531 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) { 8532 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD; 8533 return false; 8534 } 8535 8536 return HandleClassZeroInitialization(Info, E, RD, This, Result); 8537 } 8538 8539 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { 8540 switch (E->getCastKind()) { 8541 default: 8542 return ExprEvaluatorBaseTy::VisitCastExpr(E); 8543 8544 case CK_ConstructorConversion: 8545 return Visit(E->getSubExpr()); 8546 8547 case CK_DerivedToBase: 8548 case CK_UncheckedDerivedToBase: { 8549 APValue DerivedObject; 8550 if (!Evaluate(DerivedObject, Info, E->getSubExpr())) 8551 return false; 8552 if (!DerivedObject.isStruct()) 8553 return Error(E->getSubExpr()); 8554 8555 // Derived-to-base rvalue conversion: just slice off the derived part. 8556 APValue *Value = &DerivedObject; 8557 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); 8558 for (CastExpr::path_const_iterator PathI = E->path_begin(), 8559 PathE = E->path_end(); PathI != PathE; ++PathI) { 8560 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); 8561 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); 8562 Value = &Value->getStructBase(getBaseIndex(RD, Base)); 8563 RD = Base; 8564 } 8565 Result = *Value; 8566 return true; 8567 } 8568 } 8569 } 8570 8571 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 8572 if (E->isTransparent()) 8573 return Visit(E->getInit(0)); 8574 8575 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl(); 8576 if (RD->isInvalidDecl()) return false; 8577 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); 8578 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 8579 8580 EvalInfo::EvaluatingConstructorRAII EvalObj( 8581 Info, 8582 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries}, 8583 CXXRD && CXXRD->getNumBases()); 8584 8585 if (RD->isUnion()) { 8586 const FieldDecl *Field = E->getInitializedFieldInUnion(); 8587 Result = APValue(Field); 8588 if (!Field) 8589 return true; 8590 8591 // If the initializer list for a union does not contain any elements, the 8592 // first element of the union is value-initialized. 8593 // FIXME: The element should be initialized from an initializer list. 8594 // Is this difference ever observable for initializer lists which 8595 // we don't build? 8596 ImplicitValueInitExpr VIE(Field->getType()); 8597 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; 8598 8599 LValue Subobject = This; 8600 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) 8601 return false; 8602 8603 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 8604 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 8605 isa<CXXDefaultInitExpr>(InitExpr)); 8606 8607 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr); 8608 } 8609 8610 if (!Result.hasValue()) 8611 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0, 8612 std::distance(RD->field_begin(), RD->field_end())); 8613 unsigned ElementNo = 0; 8614 bool Success = true; 8615 8616 // Initialize base classes. 8617 if (CXXRD && CXXRD->getNumBases()) { 8618 for (const auto &Base : CXXRD->bases()) { 8619 assert(ElementNo < E->getNumInits() && "missing init for base class"); 8620 const Expr *Init = E->getInit(ElementNo); 8621 8622 LValue Subobject = This; 8623 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) 8624 return false; 8625 8626 APValue &FieldVal = Result.getStructBase(ElementNo); 8627 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) { 8628 if (!Info.noteFailure()) 8629 return false; 8630 Success = false; 8631 } 8632 ++ElementNo; 8633 } 8634 8635 EvalObj.finishedConstructingBases(); 8636 } 8637 8638 // Initialize members. 8639 for (const auto *Field : RD->fields()) { 8640 // Anonymous bit-fields are not considered members of the class for 8641 // purposes of aggregate initialization. 8642 if (Field->isUnnamedBitfield()) 8643 continue; 8644 8645 LValue Subobject = This; 8646 8647 bool HaveInit = ElementNo < E->getNumInits(); 8648 8649 // FIXME: Diagnostics here should point to the end of the initializer 8650 // list, not the start. 8651 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, 8652 Subobject, Field, &Layout)) 8653 return false; 8654 8655 // Perform an implicit value-initialization for members beyond the end of 8656 // the initializer list. 8657 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); 8658 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; 8659 8660 // Temporarily override This, in case there's a CXXDefaultInitExpr in here. 8661 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, 8662 isa<CXXDefaultInitExpr>(Init)); 8663 8664 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 8665 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || 8666 (Field->isBitField() && !truncateBitfieldValue(Info, Init, 8667 FieldVal, Field))) { 8668 if (!Info.noteFailure()) 8669 return false; 8670 Success = false; 8671 } 8672 } 8673 8674 return Success; 8675 } 8676 8677 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 8678 QualType T) { 8679 // Note that E's type is not necessarily the type of our class here; we might 8680 // be initializing an array element instead. 8681 const CXXConstructorDecl *FD = E->getConstructor(); 8682 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; 8683 8684 bool ZeroInit = E->requiresZeroInitialization(); 8685 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { 8686 // If we've already performed zero-initialization, we're already done. 8687 if (Result.hasValue()) 8688 return true; 8689 8690 if (ZeroInit) 8691 return ZeroInitialization(E, T); 8692 8693 Result = getDefaultInitValue(T); 8694 return true; 8695 } 8696 8697 const FunctionDecl *Definition = nullptr; 8698 auto Body = FD->getBody(Definition); 8699 8700 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 8701 return false; 8702 8703 // Avoid materializing a temporary for an elidable copy/move constructor. 8704 if (E->isElidable() && !ZeroInit) 8705 if (const MaterializeTemporaryExpr *ME 8706 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0))) 8707 return Visit(ME->GetTemporaryExpr()); 8708 8709 if (ZeroInit && !ZeroInitialization(E, T)) 8710 return false; 8711 8712 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); 8713 return HandleConstructorCall(E, This, Args, 8714 cast<CXXConstructorDecl>(Definition), Info, 8715 Result); 8716 } 8717 8718 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( 8719 const CXXInheritedCtorInitExpr *E) { 8720 if (!Info.CurrentCall) { 8721 assert(Info.checkingPotentialConstantExpression()); 8722 return false; 8723 } 8724 8725 const CXXConstructorDecl *FD = E->getConstructor(); 8726 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) 8727 return false; 8728 8729 const FunctionDecl *Definition = nullptr; 8730 auto Body = FD->getBody(Definition); 8731 8732 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) 8733 return false; 8734 8735 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments, 8736 cast<CXXConstructorDecl>(Definition), Info, 8737 Result); 8738 } 8739 8740 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( 8741 const CXXStdInitializerListExpr *E) { 8742 const ConstantArrayType *ArrayType = 8743 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); 8744 8745 LValue Array; 8746 if (!EvaluateLValue(E->getSubExpr(), Array, Info)) 8747 return false; 8748 8749 // Get a pointer to the first element of the array. 8750 Array.addArray(Info, E, ArrayType); 8751 8752 // FIXME: Perform the checks on the field types in SemaInit. 8753 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl(); 8754 RecordDecl::field_iterator Field = Record->field_begin(); 8755 if (Field == Record->field_end()) 8756 return Error(E); 8757 8758 // Start pointer. 8759 if (!Field->getType()->isPointerType() || 8760 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 8761 ArrayType->getElementType())) 8762 return Error(E); 8763 8764 // FIXME: What if the initializer_list type has base classes, etc? 8765 Result = APValue(APValue::UninitStruct(), 0, 2); 8766 Array.moveInto(Result.getStructField(0)); 8767 8768 if (++Field == Record->field_end()) 8769 return Error(E); 8770 8771 if (Field->getType()->isPointerType() && 8772 Info.Ctx.hasSameType(Field->getType()->getPointeeType(), 8773 ArrayType->getElementType())) { 8774 // End pointer. 8775 if (!HandleLValueArrayAdjustment(Info, E, Array, 8776 ArrayType->getElementType(), 8777 ArrayType->getSize().getZExtValue())) 8778 return false; 8779 Array.moveInto(Result.getStructField(1)); 8780 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) 8781 // Length. 8782 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize())); 8783 else 8784 return Error(E); 8785 8786 if (++Field != Record->field_end()) 8787 return Error(E); 8788 8789 return true; 8790 } 8791 8792 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { 8793 const CXXRecordDecl *ClosureClass = E->getLambdaClass(); 8794 if (ClosureClass->isInvalidDecl()) 8795 return false; 8796 8797 const size_t NumFields = 8798 std::distance(ClosureClass->field_begin(), ClosureClass->field_end()); 8799 8800 assert(NumFields == (size_t)std::distance(E->capture_init_begin(), 8801 E->capture_init_end()) && 8802 "The number of lambda capture initializers should equal the number of " 8803 "fields within the closure type"); 8804 8805 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); 8806 // Iterate through all the lambda's closure object's fields and initialize 8807 // them. 8808 auto *CaptureInitIt = E->capture_init_begin(); 8809 const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); 8810 bool Success = true; 8811 for (const auto *Field : ClosureClass->fields()) { 8812 assert(CaptureInitIt != E->capture_init_end()); 8813 // Get the initializer for this field 8814 Expr *const CurFieldInit = *CaptureInitIt++; 8815 8816 // If there is no initializer, either this is a VLA or an error has 8817 // occurred. 8818 if (!CurFieldInit) 8819 return Error(E); 8820 8821 APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); 8822 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) { 8823 if (!Info.keepEvaluatingAfterFailure()) 8824 return false; 8825 Success = false; 8826 } 8827 ++CaptureIt; 8828 } 8829 return Success; 8830 } 8831 8832 static bool EvaluateRecord(const Expr *E, const LValue &This, 8833 APValue &Result, EvalInfo &Info) { 8834 assert(E->isRValue() && E->getType()->isRecordType() && 8835 "can't evaluate expression as a record rvalue"); 8836 return RecordExprEvaluator(Info, This, Result).Visit(E); 8837 } 8838 8839 //===----------------------------------------------------------------------===// 8840 // Temporary Evaluation 8841 // 8842 // Temporaries are represented in the AST as rvalues, but generally behave like 8843 // lvalues. The full-object of which the temporary is a subobject is implicitly 8844 // materialized so that a reference can bind to it. 8845 //===----------------------------------------------------------------------===// 8846 namespace { 8847 class TemporaryExprEvaluator 8848 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> { 8849 public: 8850 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : 8851 LValueExprEvaluatorBaseTy(Info, Result, false) {} 8852 8853 /// Visit an expression which constructs the value of this temporary. 8854 bool VisitConstructExpr(const Expr *E) { 8855 APValue &Value = 8856 Info.CurrentCall->createTemporary(E, E->getType(), false, Result); 8857 return EvaluateInPlace(Value, Info, Result, E); 8858 } 8859 8860 bool VisitCastExpr(const CastExpr *E) { 8861 switch (E->getCastKind()) { 8862 default: 8863 return LValueExprEvaluatorBaseTy::VisitCastExpr(E); 8864 8865 case CK_ConstructorConversion: 8866 return VisitConstructExpr(E->getSubExpr()); 8867 } 8868 } 8869 bool VisitInitListExpr(const InitListExpr *E) { 8870 return VisitConstructExpr(E); 8871 } 8872 bool VisitCXXConstructExpr(const CXXConstructExpr *E) { 8873 return VisitConstructExpr(E); 8874 } 8875 bool VisitCallExpr(const CallExpr *E) { 8876 return VisitConstructExpr(E); 8877 } 8878 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { 8879 return VisitConstructExpr(E); 8880 } 8881 bool VisitLambdaExpr(const LambdaExpr *E) { 8882 return VisitConstructExpr(E); 8883 } 8884 }; 8885 } // end anonymous namespace 8886 8887 /// Evaluate an expression of record type as a temporary. 8888 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { 8889 assert(E->isRValue() && E->getType()->isRecordType()); 8890 return TemporaryExprEvaluator(Info, Result).Visit(E); 8891 } 8892 8893 //===----------------------------------------------------------------------===// 8894 // Vector Evaluation 8895 //===----------------------------------------------------------------------===// 8896 8897 namespace { 8898 class VectorExprEvaluator 8899 : public ExprEvaluatorBase<VectorExprEvaluator> { 8900 APValue &Result; 8901 public: 8902 8903 VectorExprEvaluator(EvalInfo &info, APValue &Result) 8904 : ExprEvaluatorBaseTy(info), Result(Result) {} 8905 8906 bool Success(ArrayRef<APValue> V, const Expr *E) { 8907 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements()); 8908 // FIXME: remove this APValue copy. 8909 Result = APValue(V.data(), V.size()); 8910 return true; 8911 } 8912 bool Success(const APValue &V, const Expr *E) { 8913 assert(V.isVector()); 8914 Result = V; 8915 return true; 8916 } 8917 bool ZeroInitialization(const Expr *E); 8918 8919 bool VisitUnaryReal(const UnaryOperator *E) 8920 { return Visit(E->getSubExpr()); } 8921 bool VisitCastExpr(const CastExpr* E); 8922 bool VisitInitListExpr(const InitListExpr *E); 8923 bool VisitUnaryImag(const UnaryOperator *E); 8924 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div, 8925 // binary comparisons, binary and/or/xor, 8926 // shufflevector, ExtVectorElementExpr 8927 }; 8928 } // end anonymous namespace 8929 8930 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { 8931 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue"); 8932 return VectorExprEvaluator(Info, Result).Visit(E); 8933 } 8934 8935 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { 8936 const VectorType *VTy = E->getType()->castAs<VectorType>(); 8937 unsigned NElts = VTy->getNumElements(); 8938 8939 const Expr *SE = E->getSubExpr(); 8940 QualType SETy = SE->getType(); 8941 8942 switch (E->getCastKind()) { 8943 case CK_VectorSplat: { 8944 APValue Val = APValue(); 8945 if (SETy->isIntegerType()) { 8946 APSInt IntResult; 8947 if (!EvaluateInteger(SE, IntResult, Info)) 8948 return false; 8949 Val = APValue(std::move(IntResult)); 8950 } else if (SETy->isRealFloatingType()) { 8951 APFloat FloatResult(0.0); 8952 if (!EvaluateFloat(SE, FloatResult, Info)) 8953 return false; 8954 Val = APValue(std::move(FloatResult)); 8955 } else { 8956 return Error(E); 8957 } 8958 8959 // Splat and create vector APValue. 8960 SmallVector<APValue, 4> Elts(NElts, Val); 8961 return Success(Elts, E); 8962 } 8963 case CK_BitCast: { 8964 // Evaluate the operand into an APInt we can extract from. 8965 llvm::APInt SValInt; 8966 if (!EvalAndBitcastToAPInt(Info, SE, SValInt)) 8967 return false; 8968 // Extract the elements 8969 QualType EltTy = VTy->getElementType(); 8970 unsigned EltSize = Info.Ctx.getTypeSize(EltTy); 8971 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); 8972 SmallVector<APValue, 4> Elts; 8973 if (EltTy->isRealFloatingType()) { 8974 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); 8975 unsigned FloatEltSize = EltSize; 8976 if (&Sem == &APFloat::x87DoubleExtended()) 8977 FloatEltSize = 80; 8978 for (unsigned i = 0; i < NElts; i++) { 8979 llvm::APInt Elt; 8980 if (BigEndian) 8981 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); 8982 else 8983 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); 8984 Elts.push_back(APValue(APFloat(Sem, Elt))); 8985 } 8986 } else if (EltTy->isIntegerType()) { 8987 for (unsigned i = 0; i < NElts; i++) { 8988 llvm::APInt Elt; 8989 if (BigEndian) 8990 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); 8991 else 8992 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); 8993 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType()))); 8994 } 8995 } else { 8996 return Error(E); 8997 } 8998 return Success(Elts, E); 8999 } 9000 default: 9001 return ExprEvaluatorBaseTy::VisitCastExpr(E); 9002 } 9003 } 9004 9005 bool 9006 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 9007 const VectorType *VT = E->getType()->castAs<VectorType>(); 9008 unsigned NumInits = E->getNumInits(); 9009 unsigned NumElements = VT->getNumElements(); 9010 9011 QualType EltTy = VT->getElementType(); 9012 SmallVector<APValue, 4> Elements; 9013 9014 // The number of initializers can be less than the number of 9015 // vector elements. For OpenCL, this can be due to nested vector 9016 // initialization. For GCC compatibility, missing trailing elements 9017 // should be initialized with zeroes. 9018 unsigned CountInits = 0, CountElts = 0; 9019 while (CountElts < NumElements) { 9020 // Handle nested vector initialization. 9021 if (CountInits < NumInits 9022 && E->getInit(CountInits)->getType()->isVectorType()) { 9023 APValue v; 9024 if (!EvaluateVector(E->getInit(CountInits), v, Info)) 9025 return Error(E); 9026 unsigned vlen = v.getVectorLength(); 9027 for (unsigned j = 0; j < vlen; j++) 9028 Elements.push_back(v.getVectorElt(j)); 9029 CountElts += vlen; 9030 } else if (EltTy->isIntegerType()) { 9031 llvm::APSInt sInt(32); 9032 if (CountInits < NumInits) { 9033 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info)) 9034 return false; 9035 } else // trailing integer zero. 9036 sInt = Info.Ctx.MakeIntValue(0, EltTy); 9037 Elements.push_back(APValue(sInt)); 9038 CountElts++; 9039 } else { 9040 llvm::APFloat f(0.0); 9041 if (CountInits < NumInits) { 9042 if (!EvaluateFloat(E->getInit(CountInits), f, Info)) 9043 return false; 9044 } else // trailing float zero. 9045 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)); 9046 Elements.push_back(APValue(f)); 9047 CountElts++; 9048 } 9049 CountInits++; 9050 } 9051 return Success(Elements, E); 9052 } 9053 9054 bool 9055 VectorExprEvaluator::ZeroInitialization(const Expr *E) { 9056 const VectorType *VT = E->getType()->getAs<VectorType>(); 9057 QualType EltTy = VT->getElementType(); 9058 APValue ZeroElement; 9059 if (EltTy->isIntegerType()) 9060 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy)); 9061 else 9062 ZeroElement = 9063 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy))); 9064 9065 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement); 9066 return Success(Elements, E); 9067 } 9068 9069 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 9070 VisitIgnoredValue(E->getSubExpr()); 9071 return ZeroInitialization(E); 9072 } 9073 9074 //===----------------------------------------------------------------------===// 9075 // Array Evaluation 9076 //===----------------------------------------------------------------------===// 9077 9078 namespace { 9079 class ArrayExprEvaluator 9080 : public ExprEvaluatorBase<ArrayExprEvaluator> { 9081 const LValue &This; 9082 APValue &Result; 9083 public: 9084 9085 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) 9086 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 9087 9088 bool Success(const APValue &V, const Expr *E) { 9089 assert(V.isArray() && "expected array"); 9090 Result = V; 9091 return true; 9092 } 9093 9094 bool ZeroInitialization(const Expr *E) { 9095 const ConstantArrayType *CAT = 9096 Info.Ctx.getAsConstantArrayType(E->getType()); 9097 if (!CAT) 9098 return Error(E); 9099 9100 Result = APValue(APValue::UninitArray(), 0, 9101 CAT->getSize().getZExtValue()); 9102 if (!Result.hasArrayFiller()) return true; 9103 9104 // Zero-initialize all elements. 9105 LValue Subobject = This; 9106 Subobject.addArray(Info, E, CAT); 9107 ImplicitValueInitExpr VIE(CAT->getElementType()); 9108 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); 9109 } 9110 9111 bool VisitCallExpr(const CallExpr *E) { 9112 return handleCallExpr(E, Result, &This); 9113 } 9114 bool VisitInitListExpr(const InitListExpr *E, 9115 QualType AllocType = QualType()); 9116 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); 9117 bool VisitCXXConstructExpr(const CXXConstructExpr *E); 9118 bool VisitCXXConstructExpr(const CXXConstructExpr *E, 9119 const LValue &Subobject, 9120 APValue *Value, QualType Type); 9121 bool VisitStringLiteral(const StringLiteral *E, 9122 QualType AllocType = QualType()) { 9123 expandStringLiteral(Info, E, Result, AllocType); 9124 return true; 9125 } 9126 }; 9127 } // end anonymous namespace 9128 9129 static bool EvaluateArray(const Expr *E, const LValue &This, 9130 APValue &Result, EvalInfo &Info) { 9131 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue"); 9132 return ArrayExprEvaluator(Info, This, Result).Visit(E); 9133 } 9134 9135 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, 9136 APValue &Result, const InitListExpr *ILE, 9137 QualType AllocType) { 9138 assert(ILE->isRValue() && ILE->getType()->isArrayType() && 9139 "not an array rvalue"); 9140 return ArrayExprEvaluator(Info, This, Result) 9141 .VisitInitListExpr(ILE, AllocType); 9142 } 9143 9144 // Return true iff the given array filler may depend on the element index. 9145 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { 9146 // For now, just whitelist non-class value-initialization and initialization 9147 // lists comprised of them. 9148 if (isa<ImplicitValueInitExpr>(FillerExpr)) 9149 return false; 9150 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) { 9151 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { 9152 if (MaybeElementDependentArrayFiller(ILE->getInit(I))) 9153 return true; 9154 } 9155 return false; 9156 } 9157 return true; 9158 } 9159 9160 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, 9161 QualType AllocType) { 9162 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( 9163 AllocType.isNull() ? E->getType() : AllocType); 9164 if (!CAT) 9165 return Error(E); 9166 9167 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...] 9168 // an appropriately-typed string literal enclosed in braces. 9169 if (E->isStringLiteralInit()) { 9170 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens()); 9171 // FIXME: Support ObjCEncodeExpr here once we support it in 9172 // ArrayExprEvaluator generally. 9173 if (!SL) 9174 return Error(E); 9175 return VisitStringLiteral(SL, AllocType); 9176 } 9177 9178 bool Success = true; 9179 9180 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) && 9181 "zero-initialized array shouldn't have any initialized elts"); 9182 APValue Filler; 9183 if (Result.isArray() && Result.hasArrayFiller()) 9184 Filler = Result.getArrayFiller(); 9185 9186 unsigned NumEltsToInit = E->getNumInits(); 9187 unsigned NumElts = CAT->getSize().getZExtValue(); 9188 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; 9189 9190 // If the initializer might depend on the array index, run it for each 9191 // array element. 9192 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr)) 9193 NumEltsToInit = NumElts; 9194 9195 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: " 9196 << NumEltsToInit << ".\n"); 9197 9198 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts); 9199 9200 // If the array was previously zero-initialized, preserve the 9201 // zero-initialized values. 9202 if (Filler.hasValue()) { 9203 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I) 9204 Result.getArrayInitializedElt(I) = Filler; 9205 if (Result.hasArrayFiller()) 9206 Result.getArrayFiller() = Filler; 9207 } 9208 9209 LValue Subobject = This; 9210 Subobject.addArray(Info, E, CAT); 9211 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { 9212 const Expr *Init = 9213 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; 9214 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 9215 Info, Subobject, Init) || 9216 !HandleLValueArrayAdjustment(Info, Init, Subobject, 9217 CAT->getElementType(), 1)) { 9218 if (!Info.noteFailure()) 9219 return false; 9220 Success = false; 9221 } 9222 } 9223 9224 if (!Result.hasArrayFiller()) 9225 return Success; 9226 9227 // If we get here, we have a trivial filler, which we can just evaluate 9228 // once and splat over the rest of the array elements. 9229 assert(FillerExpr && "no array filler for incomplete init list"); 9230 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, 9231 FillerExpr) && Success; 9232 } 9233 9234 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 9235 LValue CommonLV; 9236 if (E->getCommonExpr() && 9237 !Evaluate(Info.CurrentCall->createTemporary( 9238 E->getCommonExpr(), 9239 getStorageType(Info.Ctx, E->getCommonExpr()), false, 9240 CommonLV), 9241 Info, E->getCommonExpr()->getSourceExpr())) 9242 return false; 9243 9244 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe()); 9245 9246 uint64_t Elements = CAT->getSize().getZExtValue(); 9247 Result = APValue(APValue::UninitArray(), Elements, Elements); 9248 9249 LValue Subobject = This; 9250 Subobject.addArray(Info, E, CAT); 9251 9252 bool Success = true; 9253 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { 9254 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), 9255 Info, Subobject, E->getSubExpr()) || 9256 !HandleLValueArrayAdjustment(Info, E, Subobject, 9257 CAT->getElementType(), 1)) { 9258 if (!Info.noteFailure()) 9259 return false; 9260 Success = false; 9261 } 9262 } 9263 9264 return Success; 9265 } 9266 9267 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { 9268 return VisitCXXConstructExpr(E, This, &Result, E->getType()); 9269 } 9270 9271 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, 9272 const LValue &Subobject, 9273 APValue *Value, 9274 QualType Type) { 9275 bool HadZeroInit = Value->hasValue(); 9276 9277 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { 9278 unsigned N = CAT->getSize().getZExtValue(); 9279 9280 // Preserve the array filler if we had prior zero-initialization. 9281 APValue Filler = 9282 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() 9283 : APValue(); 9284 9285 *Value = APValue(APValue::UninitArray(), N, N); 9286 9287 if (HadZeroInit) 9288 for (unsigned I = 0; I != N; ++I) 9289 Value->getArrayInitializedElt(I) = Filler; 9290 9291 // Initialize the elements. 9292 LValue ArrayElt = Subobject; 9293 ArrayElt.addArray(Info, E, CAT); 9294 for (unsigned I = 0; I != N; ++I) 9295 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), 9296 CAT->getElementType()) || 9297 !HandleLValueArrayAdjustment(Info, E, ArrayElt, 9298 CAT->getElementType(), 1)) 9299 return false; 9300 9301 return true; 9302 } 9303 9304 if (!Type->isRecordType()) 9305 return Error(E); 9306 9307 return RecordExprEvaluator(Info, Subobject, *Value) 9308 .VisitCXXConstructExpr(E, Type); 9309 } 9310 9311 //===----------------------------------------------------------------------===// 9312 // Integer Evaluation 9313 // 9314 // As a GNU extension, we support casting pointers to sufficiently-wide integer 9315 // types and back in constant folding. Integer values are thus represented 9316 // either as an integer-valued APValue, or as an lvalue-valued APValue. 9317 //===----------------------------------------------------------------------===// 9318 9319 namespace { 9320 class IntExprEvaluator 9321 : public ExprEvaluatorBase<IntExprEvaluator> { 9322 APValue &Result; 9323 public: 9324 IntExprEvaluator(EvalInfo &info, APValue &result) 9325 : ExprEvaluatorBaseTy(info), Result(result) {} 9326 9327 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { 9328 assert(E->getType()->isIntegralOrEnumerationType() && 9329 "Invalid evaluation result."); 9330 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && 9331 "Invalid evaluation result."); 9332 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 9333 "Invalid evaluation result."); 9334 Result = APValue(SI); 9335 return true; 9336 } 9337 bool Success(const llvm::APSInt &SI, const Expr *E) { 9338 return Success(SI, E, Result); 9339 } 9340 9341 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { 9342 assert(E->getType()->isIntegralOrEnumerationType() && 9343 "Invalid evaluation result."); 9344 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && 9345 "Invalid evaluation result."); 9346 Result = APValue(APSInt(I)); 9347 Result.getInt().setIsUnsigned( 9348 E->getType()->isUnsignedIntegerOrEnumerationType()); 9349 return true; 9350 } 9351 bool Success(const llvm::APInt &I, const Expr *E) { 9352 return Success(I, E, Result); 9353 } 9354 9355 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 9356 assert(E->getType()->isIntegralOrEnumerationType() && 9357 "Invalid evaluation result."); 9358 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); 9359 return true; 9360 } 9361 bool Success(uint64_t Value, const Expr *E) { 9362 return Success(Value, E, Result); 9363 } 9364 9365 bool Success(CharUnits Size, const Expr *E) { 9366 return Success(Size.getQuantity(), E); 9367 } 9368 9369 bool Success(const APValue &V, const Expr *E) { 9370 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { 9371 Result = V; 9372 return true; 9373 } 9374 return Success(V.getInt(), E); 9375 } 9376 9377 bool ZeroInitialization(const Expr *E) { return Success(0, E); } 9378 9379 //===--------------------------------------------------------------------===// 9380 // Visitor Methods 9381 //===--------------------------------------------------------------------===// 9382 9383 bool VisitConstantExpr(const ConstantExpr *E); 9384 9385 bool VisitIntegerLiteral(const IntegerLiteral *E) { 9386 return Success(E->getValue(), E); 9387 } 9388 bool VisitCharacterLiteral(const CharacterLiteral *E) { 9389 return Success(E->getValue(), E); 9390 } 9391 9392 bool CheckReferencedDecl(const Expr *E, const Decl *D); 9393 bool VisitDeclRefExpr(const DeclRefExpr *E) { 9394 if (CheckReferencedDecl(E, E->getDecl())) 9395 return true; 9396 9397 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); 9398 } 9399 bool VisitMemberExpr(const MemberExpr *E) { 9400 if (CheckReferencedDecl(E, E->getMemberDecl())) { 9401 VisitIgnoredBaseExpression(E->getBase()); 9402 return true; 9403 } 9404 9405 return ExprEvaluatorBaseTy::VisitMemberExpr(E); 9406 } 9407 9408 bool VisitCallExpr(const CallExpr *E); 9409 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); 9410 bool VisitBinaryOperator(const BinaryOperator *E); 9411 bool VisitOffsetOfExpr(const OffsetOfExpr *E); 9412 bool VisitUnaryOperator(const UnaryOperator *E); 9413 9414 bool VisitCastExpr(const CastExpr* E); 9415 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); 9416 9417 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 9418 return Success(E->getValue(), E); 9419 } 9420 9421 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 9422 return Success(E->getValue(), E); 9423 } 9424 9425 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 9426 if (Info.ArrayInitIndex == uint64_t(-1)) { 9427 // We were asked to evaluate this subexpression independent of the 9428 // enclosing ArrayInitLoopExpr. We can't do that. 9429 Info.FFDiag(E); 9430 return false; 9431 } 9432 return Success(Info.ArrayInitIndex, E); 9433 } 9434 9435 // Note, GNU defines __null as an integer, not a pointer. 9436 bool VisitGNUNullExpr(const GNUNullExpr *E) { 9437 return ZeroInitialization(E); 9438 } 9439 9440 bool VisitTypeTraitExpr(const TypeTraitExpr *E) { 9441 return Success(E->getValue(), E); 9442 } 9443 9444 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 9445 return Success(E->getValue(), E); 9446 } 9447 9448 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 9449 return Success(E->getValue(), E); 9450 } 9451 9452 bool VisitUnaryReal(const UnaryOperator *E); 9453 bool VisitUnaryImag(const UnaryOperator *E); 9454 9455 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); 9456 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); 9457 bool VisitSourceLocExpr(const SourceLocExpr *E); 9458 // FIXME: Missing: array subscript of vector, member of vector 9459 }; 9460 9461 class FixedPointExprEvaluator 9462 : public ExprEvaluatorBase<FixedPointExprEvaluator> { 9463 APValue &Result; 9464 9465 public: 9466 FixedPointExprEvaluator(EvalInfo &info, APValue &result) 9467 : ExprEvaluatorBaseTy(info), Result(result) {} 9468 9469 bool Success(const llvm::APInt &I, const Expr *E) { 9470 return Success( 9471 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); 9472 } 9473 9474 bool Success(uint64_t Value, const Expr *E) { 9475 return Success( 9476 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); 9477 } 9478 9479 bool Success(const APValue &V, const Expr *E) { 9480 return Success(V.getFixedPoint(), E); 9481 } 9482 9483 bool Success(const APFixedPoint &V, const Expr *E) { 9484 assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); 9485 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && 9486 "Invalid evaluation result."); 9487 Result = APValue(V); 9488 return true; 9489 } 9490 9491 //===--------------------------------------------------------------------===// 9492 // Visitor Methods 9493 //===--------------------------------------------------------------------===// 9494 9495 bool VisitFixedPointLiteral(const FixedPointLiteral *E) { 9496 return Success(E->getValue(), E); 9497 } 9498 9499 bool VisitCastExpr(const CastExpr *E); 9500 bool VisitUnaryOperator(const UnaryOperator *E); 9501 bool VisitBinaryOperator(const BinaryOperator *E); 9502 }; 9503 } // end anonymous namespace 9504 9505 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and 9506 /// produce either the integer value or a pointer. 9507 /// 9508 /// GCC has a heinous extension which folds casts between pointer types and 9509 /// pointer-sized integral types. We support this by allowing the evaluation of 9510 /// an integer rvalue to produce a pointer (represented as an lvalue) instead. 9511 /// Some simple arithmetic on such values is supported (they are treated much 9512 /// like char*). 9513 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, 9514 EvalInfo &Info) { 9515 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType()); 9516 return IntExprEvaluator(Info, Result).Visit(E); 9517 } 9518 9519 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { 9520 APValue Val; 9521 if (!EvaluateIntegerOrLValue(E, Val, Info)) 9522 return false; 9523 if (!Val.isInt()) { 9524 // FIXME: It would be better to produce the diagnostic for casting 9525 // a pointer to an integer. 9526 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 9527 return false; 9528 } 9529 Result = Val.getInt(); 9530 return true; 9531 } 9532 9533 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { 9534 APValue Evaluated = E->EvaluateInContext( 9535 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); 9536 return Success(Evaluated, E); 9537 } 9538 9539 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, 9540 EvalInfo &Info) { 9541 if (E->getType()->isFixedPointType()) { 9542 APValue Val; 9543 if (!FixedPointExprEvaluator(Info, Val).Visit(E)) 9544 return false; 9545 if (!Val.isFixedPoint()) 9546 return false; 9547 9548 Result = Val.getFixedPoint(); 9549 return true; 9550 } 9551 return false; 9552 } 9553 9554 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, 9555 EvalInfo &Info) { 9556 if (E->getType()->isIntegerType()) { 9557 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType()); 9558 APSInt Val; 9559 if (!EvaluateInteger(E, Val, Info)) 9560 return false; 9561 Result = APFixedPoint(Val, FXSema); 9562 return true; 9563 } else if (E->getType()->isFixedPointType()) { 9564 return EvaluateFixedPoint(E, Result, Info); 9565 } 9566 return false; 9567 } 9568 9569 /// Check whether the given declaration can be directly converted to an integral 9570 /// rvalue. If not, no diagnostic is produced; there are other things we can 9571 /// try. 9572 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { 9573 // Enums are integer constant exprs. 9574 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) { 9575 // Check for signedness/width mismatches between E type and ECD value. 9576 bool SameSign = (ECD->getInitVal().isSigned() 9577 == E->getType()->isSignedIntegerOrEnumerationType()); 9578 bool SameWidth = (ECD->getInitVal().getBitWidth() 9579 == Info.Ctx.getIntWidth(E->getType())); 9580 if (SameSign && SameWidth) 9581 return Success(ECD->getInitVal(), E); 9582 else { 9583 // Get rid of mismatch (otherwise Success assertions will fail) 9584 // by computing a new value matching the type of E. 9585 llvm::APSInt Val = ECD->getInitVal(); 9586 if (!SameSign) 9587 Val.setIsSigned(!ECD->getInitVal().isSigned()); 9588 if (!SameWidth) 9589 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType())); 9590 return Success(Val, E); 9591 } 9592 } 9593 return false; 9594 } 9595 9596 /// Values returned by __builtin_classify_type, chosen to match the values 9597 /// produced by GCC's builtin. 9598 enum class GCCTypeClass { 9599 None = -1, 9600 Void = 0, 9601 Integer = 1, 9602 // GCC reserves 2 for character types, but instead classifies them as 9603 // integers. 9604 Enum = 3, 9605 Bool = 4, 9606 Pointer = 5, 9607 // GCC reserves 6 for references, but appears to never use it (because 9608 // expressions never have reference type, presumably). 9609 PointerToDataMember = 7, 9610 RealFloat = 8, 9611 Complex = 9, 9612 // GCC reserves 10 for functions, but does not use it since GCC version 6 due 9613 // to decay to pointer. (Prior to version 6 it was only used in C++ mode). 9614 // GCC claims to reserve 11 for pointers to member functions, but *actually* 9615 // uses 12 for that purpose, same as for a class or struct. Maybe it 9616 // internally implements a pointer to member as a struct? Who knows. 9617 PointerToMemberFunction = 12, // Not a bug, see above. 9618 ClassOrStruct = 12, 9619 Union = 13, 9620 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to 9621 // decay to pointer. (Prior to version 6 it was only used in C++ mode). 9622 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string 9623 // literals. 9624 }; 9625 9626 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 9627 /// as GCC. 9628 static GCCTypeClass 9629 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { 9630 assert(!T->isDependentType() && "unexpected dependent type"); 9631 9632 QualType CanTy = T.getCanonicalType(); 9633 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy); 9634 9635 switch (CanTy->getTypeClass()) { 9636 #define TYPE(ID, BASE) 9637 #define DEPENDENT_TYPE(ID, BASE) case Type::ID: 9638 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID: 9639 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID: 9640 #include "clang/AST/TypeNodes.def" 9641 case Type::Auto: 9642 case Type::DeducedTemplateSpecialization: 9643 llvm_unreachable("unexpected non-canonical or dependent type"); 9644 9645 case Type::Builtin: 9646 switch (BT->getKind()) { 9647 #define BUILTIN_TYPE(ID, SINGLETON_ID) 9648 #define SIGNED_TYPE(ID, SINGLETON_ID) \ 9649 case BuiltinType::ID: return GCCTypeClass::Integer; 9650 #define FLOATING_TYPE(ID, SINGLETON_ID) \ 9651 case BuiltinType::ID: return GCCTypeClass::RealFloat; 9652 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ 9653 case BuiltinType::ID: break; 9654 #include "clang/AST/BuiltinTypes.def" 9655 case BuiltinType::Void: 9656 return GCCTypeClass::Void; 9657 9658 case BuiltinType::Bool: 9659 return GCCTypeClass::Bool; 9660 9661 case BuiltinType::Char_U: 9662 case BuiltinType::UChar: 9663 case BuiltinType::WChar_U: 9664 case BuiltinType::Char8: 9665 case BuiltinType::Char16: 9666 case BuiltinType::Char32: 9667 case BuiltinType::UShort: 9668 case BuiltinType::UInt: 9669 case BuiltinType::ULong: 9670 case BuiltinType::ULongLong: 9671 case BuiltinType::UInt128: 9672 return GCCTypeClass::Integer; 9673 9674 case BuiltinType::UShortAccum: 9675 case BuiltinType::UAccum: 9676 case BuiltinType::ULongAccum: 9677 case BuiltinType::UShortFract: 9678 case BuiltinType::UFract: 9679 case BuiltinType::ULongFract: 9680 case BuiltinType::SatUShortAccum: 9681 case BuiltinType::SatUAccum: 9682 case BuiltinType::SatULongAccum: 9683 case BuiltinType::SatUShortFract: 9684 case BuiltinType::SatUFract: 9685 case BuiltinType::SatULongFract: 9686 return GCCTypeClass::None; 9687 9688 case BuiltinType::NullPtr: 9689 9690 case BuiltinType::ObjCId: 9691 case BuiltinType::ObjCClass: 9692 case BuiltinType::ObjCSel: 9693 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 9694 case BuiltinType::Id: 9695 #include "clang/Basic/OpenCLImageTypes.def" 9696 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 9697 case BuiltinType::Id: 9698 #include "clang/Basic/OpenCLExtensionTypes.def" 9699 case BuiltinType::OCLSampler: 9700 case BuiltinType::OCLEvent: 9701 case BuiltinType::OCLClkEvent: 9702 case BuiltinType::OCLQueue: 9703 case BuiltinType::OCLReserveID: 9704 #define SVE_TYPE(Name, Id, SingletonId) \ 9705 case BuiltinType::Id: 9706 #include "clang/Basic/AArch64SVEACLETypes.def" 9707 return GCCTypeClass::None; 9708 9709 case BuiltinType::Dependent: 9710 llvm_unreachable("unexpected dependent type"); 9711 }; 9712 llvm_unreachable("unexpected placeholder type"); 9713 9714 case Type::Enum: 9715 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer; 9716 9717 case Type::Pointer: 9718 case Type::ConstantArray: 9719 case Type::VariableArray: 9720 case Type::IncompleteArray: 9721 case Type::FunctionNoProto: 9722 case Type::FunctionProto: 9723 return GCCTypeClass::Pointer; 9724 9725 case Type::MemberPointer: 9726 return CanTy->isMemberDataPointerType() 9727 ? GCCTypeClass::PointerToDataMember 9728 : GCCTypeClass::PointerToMemberFunction; 9729 9730 case Type::Complex: 9731 return GCCTypeClass::Complex; 9732 9733 case Type::Record: 9734 return CanTy->isUnionType() ? GCCTypeClass::Union 9735 : GCCTypeClass::ClassOrStruct; 9736 9737 case Type::Atomic: 9738 // GCC classifies _Atomic T the same as T. 9739 return EvaluateBuiltinClassifyType( 9740 CanTy->castAs<AtomicType>()->getValueType(), LangOpts); 9741 9742 case Type::BlockPointer: 9743 case Type::Vector: 9744 case Type::ExtVector: 9745 case Type::ObjCObject: 9746 case Type::ObjCInterface: 9747 case Type::ObjCObjectPointer: 9748 case Type::Pipe: 9749 // GCC classifies vectors as None. We follow its lead and classify all 9750 // other types that don't fit into the regular classification the same way. 9751 return GCCTypeClass::None; 9752 9753 case Type::LValueReference: 9754 case Type::RValueReference: 9755 llvm_unreachable("invalid type for expression"); 9756 } 9757 9758 llvm_unreachable("unexpected type class"); 9759 } 9760 9761 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way 9762 /// as GCC. 9763 static GCCTypeClass 9764 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { 9765 // If no argument was supplied, default to None. This isn't 9766 // ideal, however it is what gcc does. 9767 if (E->getNumArgs() == 0) 9768 return GCCTypeClass::None; 9769 9770 // FIXME: Bizarrely, GCC treats a call with more than one argument as not 9771 // being an ICE, but still folds it to a constant using the type of the first 9772 // argument. 9773 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts); 9774 } 9775 9776 /// EvaluateBuiltinConstantPForLValue - Determine the result of 9777 /// __builtin_constant_p when applied to the given pointer. 9778 /// 9779 /// A pointer is only "constant" if it is null (or a pointer cast to integer) 9780 /// or it points to the first character of a string literal. 9781 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { 9782 APValue::LValueBase Base = LV.getLValueBase(); 9783 if (Base.isNull()) { 9784 // A null base is acceptable. 9785 return true; 9786 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) { 9787 if (!isa<StringLiteral>(E)) 9788 return false; 9789 return LV.getLValueOffset().isZero(); 9790 } else if (Base.is<TypeInfoLValue>()) { 9791 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to 9792 // evaluate to true. 9793 return true; 9794 } else { 9795 // Any other base is not constant enough for GCC. 9796 return false; 9797 } 9798 } 9799 9800 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to 9801 /// GCC as we can manage. 9802 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { 9803 // This evaluation is not permitted to have side-effects, so evaluate it in 9804 // a speculative evaluation context. 9805 SpeculativeEvaluationRAII SpeculativeEval(Info); 9806 9807 // Constant-folding is always enabled for the operand of __builtin_constant_p 9808 // (even when the enclosing evaluation context otherwise requires a strict 9809 // language-specific constant expression). 9810 FoldConstant Fold(Info, true); 9811 9812 QualType ArgType = Arg->getType(); 9813 9814 // __builtin_constant_p always has one operand. The rules which gcc follows 9815 // are not precisely documented, but are as follows: 9816 // 9817 // - If the operand is of integral, floating, complex or enumeration type, 9818 // and can be folded to a known value of that type, it returns 1. 9819 // - If the operand can be folded to a pointer to the first character 9820 // of a string literal (or such a pointer cast to an integral type) 9821 // or to a null pointer or an integer cast to a pointer, it returns 1. 9822 // 9823 // Otherwise, it returns 0. 9824 // 9825 // FIXME: GCC also intends to return 1 for literals of aggregate types, but 9826 // its support for this did not work prior to GCC 9 and is not yet well 9827 // understood. 9828 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() || 9829 ArgType->isAnyComplexType() || ArgType->isPointerType() || 9830 ArgType->isNullPtrType()) { 9831 APValue V; 9832 if (!::EvaluateAsRValue(Info, Arg, V)) { 9833 Fold.keepDiagnostics(); 9834 return false; 9835 } 9836 9837 // For a pointer (possibly cast to integer), there are special rules. 9838 if (V.getKind() == APValue::LValue) 9839 return EvaluateBuiltinConstantPForLValue(V); 9840 9841 // Otherwise, any constant value is good enough. 9842 return V.hasValue(); 9843 } 9844 9845 // Anything else isn't considered to be sufficiently constant. 9846 return false; 9847 } 9848 9849 /// Retrieves the "underlying object type" of the given expression, 9850 /// as used by __builtin_object_size. 9851 static QualType getObjectType(APValue::LValueBase B) { 9852 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) { 9853 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 9854 return VD->getType(); 9855 } else if (const Expr *E = B.get<const Expr*>()) { 9856 if (isa<CompoundLiteralExpr>(E)) 9857 return E->getType(); 9858 } else if (B.is<TypeInfoLValue>()) { 9859 return B.getTypeInfoType(); 9860 } else if (B.is<DynamicAllocLValue>()) { 9861 return B.getDynamicAllocType(); 9862 } 9863 9864 return QualType(); 9865 } 9866 9867 /// A more selective version of E->IgnoreParenCasts for 9868 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only 9869 /// to change the type of E. 9870 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` 9871 /// 9872 /// Always returns an RValue with a pointer representation. 9873 static const Expr *ignorePointerCastsAndParens(const Expr *E) { 9874 assert(E->isRValue() && E->getType()->hasPointerRepresentation()); 9875 9876 auto *NoParens = E->IgnoreParens(); 9877 auto *Cast = dyn_cast<CastExpr>(NoParens); 9878 if (Cast == nullptr) 9879 return NoParens; 9880 9881 // We only conservatively allow a few kinds of casts, because this code is 9882 // inherently a simple solution that seeks to support the common case. 9883 auto CastKind = Cast->getCastKind(); 9884 if (CastKind != CK_NoOp && CastKind != CK_BitCast && 9885 CastKind != CK_AddressSpaceConversion) 9886 return NoParens; 9887 9888 auto *SubExpr = Cast->getSubExpr(); 9889 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue()) 9890 return NoParens; 9891 return ignorePointerCastsAndParens(SubExpr); 9892 } 9893 9894 /// Checks to see if the given LValue's Designator is at the end of the LValue's 9895 /// record layout. e.g. 9896 /// struct { struct { int a, b; } fst, snd; } obj; 9897 /// obj.fst // no 9898 /// obj.snd // yes 9899 /// obj.fst.a // no 9900 /// obj.fst.b // no 9901 /// obj.snd.a // no 9902 /// obj.snd.b // yes 9903 /// 9904 /// Please note: this function is specialized for how __builtin_object_size 9905 /// views "objects". 9906 /// 9907 /// If this encounters an invalid RecordDecl or otherwise cannot determine the 9908 /// correct result, it will always return true. 9909 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { 9910 assert(!LVal.Designator.Invalid); 9911 9912 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { 9913 const RecordDecl *Parent = FD->getParent(); 9914 Invalid = Parent->isInvalidDecl(); 9915 if (Invalid || Parent->isUnion()) 9916 return true; 9917 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent); 9918 return FD->getFieldIndex() + 1 == Layout.getFieldCount(); 9919 }; 9920 9921 auto &Base = LVal.getLValueBase(); 9922 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) { 9923 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) { 9924 bool Invalid; 9925 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 9926 return Invalid; 9927 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) { 9928 for (auto *FD : IFD->chain()) { 9929 bool Invalid; 9930 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid)) 9931 return Invalid; 9932 } 9933 } 9934 } 9935 9936 unsigned I = 0; 9937 QualType BaseType = getType(Base); 9938 if (LVal.Designator.FirstEntryIsAnUnsizedArray) { 9939 // If we don't know the array bound, conservatively assume we're looking at 9940 // the final array element. 9941 ++I; 9942 if (BaseType->isIncompleteArrayType()) 9943 BaseType = Ctx.getAsArrayType(BaseType)->getElementType(); 9944 else 9945 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 9946 } 9947 9948 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { 9949 const auto &Entry = LVal.Designator.Entries[I]; 9950 if (BaseType->isArrayType()) { 9951 // Because __builtin_object_size treats arrays as objects, we can ignore 9952 // the index iff this is the last array in the Designator. 9953 if (I + 1 == E) 9954 return true; 9955 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType)); 9956 uint64_t Index = Entry.getAsArrayIndex(); 9957 if (Index + 1 != CAT->getSize()) 9958 return false; 9959 BaseType = CAT->getElementType(); 9960 } else if (BaseType->isAnyComplexType()) { 9961 const auto *CT = BaseType->castAs<ComplexType>(); 9962 uint64_t Index = Entry.getAsArrayIndex(); 9963 if (Index != 1) 9964 return false; 9965 BaseType = CT->getElementType(); 9966 } else if (auto *FD = getAsField(Entry)) { 9967 bool Invalid; 9968 if (!IsLastOrInvalidFieldDecl(FD, Invalid)) 9969 return Invalid; 9970 BaseType = FD->getType(); 9971 } else { 9972 assert(getAsBaseClass(Entry) && "Expecting cast to a base class"); 9973 return false; 9974 } 9975 } 9976 return true; 9977 } 9978 9979 /// Tests to see if the LValue has a user-specified designator (that isn't 9980 /// necessarily valid). Note that this always returns 'true' if the LValue has 9981 /// an unsized array as its first designator entry, because there's currently no 9982 /// way to tell if the user typed *foo or foo[0]. 9983 static bool refersToCompleteObject(const LValue &LVal) { 9984 if (LVal.Designator.Invalid) 9985 return false; 9986 9987 if (!LVal.Designator.Entries.empty()) 9988 return LVal.Designator.isMostDerivedAnUnsizedArray(); 9989 9990 if (!LVal.InvalidBase) 9991 return true; 9992 9993 // If `E` is a MemberExpr, then the first part of the designator is hiding in 9994 // the LValueBase. 9995 const auto *E = LVal.Base.dyn_cast<const Expr *>(); 9996 return !E || !isa<MemberExpr>(E); 9997 } 9998 9999 /// Attempts to detect a user writing into a piece of memory that's impossible 10000 /// to figure out the size of by just using types. 10001 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { 10002 const SubobjectDesignator &Designator = LVal.Designator; 10003 // Notes: 10004 // - Users can only write off of the end when we have an invalid base. Invalid 10005 // bases imply we don't know where the memory came from. 10006 // - We used to be a bit more aggressive here; we'd only be conservative if 10007 // the array at the end was flexible, or if it had 0 or 1 elements. This 10008 // broke some common standard library extensions (PR30346), but was 10009 // otherwise seemingly fine. It may be useful to reintroduce this behavior 10010 // with some sort of whitelist. OTOH, it seems that GCC is always 10011 // conservative with the last element in structs (if it's an array), so our 10012 // current behavior is more compatible than a whitelisting approach would 10013 // be. 10014 return LVal.InvalidBase && 10015 Designator.Entries.size() == Designator.MostDerivedPathLength && 10016 Designator.MostDerivedIsArrayElement && 10017 isDesignatorAtObjectEnd(Ctx, LVal); 10018 } 10019 10020 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. 10021 /// Fails if the conversion would cause loss of precision. 10022 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, 10023 CharUnits &Result) { 10024 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max(); 10025 if (Int.ugt(CharUnitsMax)) 10026 return false; 10027 Result = CharUnits::fromQuantity(Int.getZExtValue()); 10028 return true; 10029 } 10030 10031 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will 10032 /// determine how many bytes exist from the beginning of the object to either 10033 /// the end of the current subobject, or the end of the object itself, depending 10034 /// on what the LValue looks like + the value of Type. 10035 /// 10036 /// If this returns false, the value of Result is undefined. 10037 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, 10038 unsigned Type, const LValue &LVal, 10039 CharUnits &EndOffset) { 10040 bool DetermineForCompleteObject = refersToCompleteObject(LVal); 10041 10042 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) { 10043 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType()) 10044 return false; 10045 return HandleSizeof(Info, ExprLoc, Ty, Result); 10046 }; 10047 10048 // We want to evaluate the size of the entire object. This is a valid fallback 10049 // for when Type=1 and the designator is invalid, because we're asked for an 10050 // upper-bound. 10051 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) { 10052 // Type=3 wants a lower bound, so we can't fall back to this. 10053 if (Type == 3 && !DetermineForCompleteObject) 10054 return false; 10055 10056 llvm::APInt APEndOffset; 10057 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10058 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10059 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10060 10061 if (LVal.InvalidBase) 10062 return false; 10063 10064 QualType BaseTy = getObjectType(LVal.getLValueBase()); 10065 return CheckedHandleSizeof(BaseTy, EndOffset); 10066 } 10067 10068 // We want to evaluate the size of a subobject. 10069 const SubobjectDesignator &Designator = LVal.Designator; 10070 10071 // The following is a moderately common idiom in C: 10072 // 10073 // struct Foo { int a; char c[1]; }; 10074 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar)); 10075 // strcpy(&F->c[0], Bar); 10076 // 10077 // In order to not break too much legacy code, we need to support it. 10078 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) { 10079 // If we can resolve this to an alloc_size call, we can hand that back, 10080 // because we know for certain how many bytes there are to write to. 10081 llvm::APInt APEndOffset; 10082 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) && 10083 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset)) 10084 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset); 10085 10086 // If we cannot determine the size of the initial allocation, then we can't 10087 // given an accurate upper-bound. However, we are still able to give 10088 // conservative lower-bounds for Type=3. 10089 if (Type == 1) 10090 return false; 10091 } 10092 10093 CharUnits BytesPerElem; 10094 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem)) 10095 return false; 10096 10097 // According to the GCC documentation, we want the size of the subobject 10098 // denoted by the pointer. But that's not quite right -- what we actually 10099 // want is the size of the immediately-enclosing array, if there is one. 10100 int64_t ElemsRemaining; 10101 if (Designator.MostDerivedIsArrayElement && 10102 Designator.Entries.size() == Designator.MostDerivedPathLength) { 10103 uint64_t ArraySize = Designator.getMostDerivedArraySize(); 10104 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex(); 10105 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex; 10106 } else { 10107 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1; 10108 } 10109 10110 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining; 10111 return true; 10112 } 10113 10114 /// Tries to evaluate the __builtin_object_size for @p E. If successful, 10115 /// returns true and stores the result in @p Size. 10116 /// 10117 /// If @p WasError is non-null, this will report whether the failure to evaluate 10118 /// is to be treated as an Error in IntExprEvaluator. 10119 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, 10120 EvalInfo &Info, uint64_t &Size) { 10121 // Determine the denoted object. 10122 LValue LVal; 10123 { 10124 // The operand of __builtin_object_size is never evaluated for side-effects. 10125 // If there are any, but we can determine the pointed-to object anyway, then 10126 // ignore the side-effects. 10127 SpeculativeEvaluationRAII SpeculativeEval(Info); 10128 IgnoreSideEffectsRAII Fold(Info); 10129 10130 if (E->isGLValue()) { 10131 // It's possible for us to be given GLValues if we're called via 10132 // Expr::tryEvaluateObjectSize. 10133 APValue RVal; 10134 if (!EvaluateAsRValue(Info, E, RVal)) 10135 return false; 10136 LVal.setFrom(Info.Ctx, RVal); 10137 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info, 10138 /*InvalidBaseOK=*/true)) 10139 return false; 10140 } 10141 10142 // If we point to before the start of the object, there are no accessible 10143 // bytes. 10144 if (LVal.getLValueOffset().isNegative()) { 10145 Size = 0; 10146 return true; 10147 } 10148 10149 CharUnits EndOffset; 10150 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset)) 10151 return false; 10152 10153 // If we've fallen outside of the end offset, just pretend there's nothing to 10154 // write to/read from. 10155 if (EndOffset <= LVal.getLValueOffset()) 10156 Size = 0; 10157 else 10158 Size = (EndOffset - LVal.getLValueOffset()).getQuantity(); 10159 return true; 10160 } 10161 10162 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) { 10163 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true); 10164 if (E->getResultAPValueKind() != APValue::None) 10165 return Success(E->getAPValueResult(), E); 10166 return ExprEvaluatorBaseTy::VisitConstantExpr(E); 10167 } 10168 10169 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { 10170 if (unsigned BuiltinOp = E->getBuiltinCallee()) 10171 return VisitBuiltinCallExpr(E, BuiltinOp); 10172 10173 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10174 } 10175 10176 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, 10177 unsigned BuiltinOp) { 10178 switch (unsigned BuiltinOp = E->getBuiltinCallee()) { 10179 default: 10180 return ExprEvaluatorBaseTy::VisitCallExpr(E); 10181 10182 case Builtin::BI__builtin_dynamic_object_size: 10183 case Builtin::BI__builtin_object_size: { 10184 // The type was checked when we built the expression. 10185 unsigned Type = 10186 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 10187 assert(Type <= 3 && "unexpected type"); 10188 10189 uint64_t Size; 10190 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size)) 10191 return Success(Size, E); 10192 10193 if (E->getArg(0)->HasSideEffects(Info.Ctx)) 10194 return Success((Type & 2) ? 0 : -1, E); 10195 10196 // Expression had no side effects, but we couldn't statically determine the 10197 // size of the referenced object. 10198 switch (Info.EvalMode) { 10199 case EvalInfo::EM_ConstantExpression: 10200 case EvalInfo::EM_ConstantFold: 10201 case EvalInfo::EM_IgnoreSideEffects: 10202 // Leave it to IR generation. 10203 return Error(E); 10204 case EvalInfo::EM_ConstantExpressionUnevaluated: 10205 // Reduce it to a constant now. 10206 return Success((Type & 2) ? 0 : -1, E); 10207 } 10208 10209 llvm_unreachable("unexpected EvalMode"); 10210 } 10211 10212 case Builtin::BI__builtin_os_log_format_buffer_size: { 10213 analyze_os_log::OSLogBufferLayout Layout; 10214 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout); 10215 return Success(Layout.size().getQuantity(), E); 10216 } 10217 10218 case Builtin::BI__builtin_bswap16: 10219 case Builtin::BI__builtin_bswap32: 10220 case Builtin::BI__builtin_bswap64: { 10221 APSInt Val; 10222 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10223 return false; 10224 10225 return Success(Val.byteSwap(), E); 10226 } 10227 10228 case Builtin::BI__builtin_classify_type: 10229 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E); 10230 10231 case Builtin::BI__builtin_clrsb: 10232 case Builtin::BI__builtin_clrsbl: 10233 case Builtin::BI__builtin_clrsbll: { 10234 APSInt Val; 10235 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10236 return false; 10237 10238 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E); 10239 } 10240 10241 case Builtin::BI__builtin_clz: 10242 case Builtin::BI__builtin_clzl: 10243 case Builtin::BI__builtin_clzll: 10244 case Builtin::BI__builtin_clzs: { 10245 APSInt Val; 10246 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10247 return false; 10248 if (!Val) 10249 return Error(E); 10250 10251 return Success(Val.countLeadingZeros(), E); 10252 } 10253 10254 case Builtin::BI__builtin_constant_p: { 10255 const Expr *Arg = E->getArg(0); 10256 if (EvaluateBuiltinConstantP(Info, Arg)) 10257 return Success(true, E); 10258 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { 10259 // Outside a constant context, eagerly evaluate to false in the presence 10260 // of side-effects in order to avoid -Wunsequenced false-positives in 10261 // a branch on __builtin_constant_p(expr). 10262 return Success(false, E); 10263 } 10264 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 10265 return false; 10266 } 10267 10268 case Builtin::BI__builtin_is_constant_evaluated: 10269 return Success(Info.InConstantContext, E); 10270 10271 case Builtin::BI__builtin_ctz: 10272 case Builtin::BI__builtin_ctzl: 10273 case Builtin::BI__builtin_ctzll: 10274 case Builtin::BI__builtin_ctzs: { 10275 APSInt Val; 10276 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10277 return false; 10278 if (!Val) 10279 return Error(E); 10280 10281 return Success(Val.countTrailingZeros(), E); 10282 } 10283 10284 case Builtin::BI__builtin_eh_return_data_regno: { 10285 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue(); 10286 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand); 10287 return Success(Operand, E); 10288 } 10289 10290 case Builtin::BI__builtin_expect: 10291 return Visit(E->getArg(0)); 10292 10293 case Builtin::BI__builtin_ffs: 10294 case Builtin::BI__builtin_ffsl: 10295 case Builtin::BI__builtin_ffsll: { 10296 APSInt Val; 10297 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10298 return false; 10299 10300 unsigned N = Val.countTrailingZeros(); 10301 return Success(N == Val.getBitWidth() ? 0 : N + 1, E); 10302 } 10303 10304 case Builtin::BI__builtin_fpclassify: { 10305 APFloat Val(0.0); 10306 if (!EvaluateFloat(E->getArg(5), Val, Info)) 10307 return false; 10308 unsigned Arg; 10309 switch (Val.getCategory()) { 10310 case APFloat::fcNaN: Arg = 0; break; 10311 case APFloat::fcInfinity: Arg = 1; break; 10312 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; 10313 case APFloat::fcZero: Arg = 4; break; 10314 } 10315 return Visit(E->getArg(Arg)); 10316 } 10317 10318 case Builtin::BI__builtin_isinf_sign: { 10319 APFloat Val(0.0); 10320 return EvaluateFloat(E->getArg(0), Val, Info) && 10321 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E); 10322 } 10323 10324 case Builtin::BI__builtin_isinf: { 10325 APFloat Val(0.0); 10326 return EvaluateFloat(E->getArg(0), Val, Info) && 10327 Success(Val.isInfinity() ? 1 : 0, E); 10328 } 10329 10330 case Builtin::BI__builtin_isfinite: { 10331 APFloat Val(0.0); 10332 return EvaluateFloat(E->getArg(0), Val, Info) && 10333 Success(Val.isFinite() ? 1 : 0, E); 10334 } 10335 10336 case Builtin::BI__builtin_isnan: { 10337 APFloat Val(0.0); 10338 return EvaluateFloat(E->getArg(0), Val, Info) && 10339 Success(Val.isNaN() ? 1 : 0, E); 10340 } 10341 10342 case Builtin::BI__builtin_isnormal: { 10343 APFloat Val(0.0); 10344 return EvaluateFloat(E->getArg(0), Val, Info) && 10345 Success(Val.isNormal() ? 1 : 0, E); 10346 } 10347 10348 case Builtin::BI__builtin_parity: 10349 case Builtin::BI__builtin_parityl: 10350 case Builtin::BI__builtin_parityll: { 10351 APSInt Val; 10352 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10353 return false; 10354 10355 return Success(Val.countPopulation() % 2, E); 10356 } 10357 10358 case Builtin::BI__builtin_popcount: 10359 case Builtin::BI__builtin_popcountl: 10360 case Builtin::BI__builtin_popcountll: { 10361 APSInt Val; 10362 if (!EvaluateInteger(E->getArg(0), Val, Info)) 10363 return false; 10364 10365 return Success(Val.countPopulation(), E); 10366 } 10367 10368 case Builtin::BIstrlen: 10369 case Builtin::BIwcslen: 10370 // A call to strlen is not a constant expression. 10371 if (Info.getLangOpts().CPlusPlus11) 10372 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 10373 << /*isConstexpr*/0 << /*isConstructor*/0 10374 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 10375 else 10376 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 10377 LLVM_FALLTHROUGH; 10378 case Builtin::BI__builtin_strlen: 10379 case Builtin::BI__builtin_wcslen: { 10380 // As an extension, we support __builtin_strlen() as a constant expression, 10381 // and support folding strlen() to a constant. 10382 LValue String; 10383 if (!EvaluatePointer(E->getArg(0), String, Info)) 10384 return false; 10385 10386 QualType CharTy = E->getArg(0)->getType()->getPointeeType(); 10387 10388 // Fast path: if it's a string literal, search the string value. 10389 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>( 10390 String.getLValueBase().dyn_cast<const Expr *>())) { 10391 // The string literal may have embedded null characters. Find the first 10392 // one and truncate there. 10393 StringRef Str = S->getBytes(); 10394 int64_t Off = String.Offset.getQuantity(); 10395 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && 10396 S->getCharByteWidth() == 1 && 10397 // FIXME: Add fast-path for wchar_t too. 10398 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) { 10399 Str = Str.substr(Off); 10400 10401 StringRef::size_type Pos = Str.find(0); 10402 if (Pos != StringRef::npos) 10403 Str = Str.substr(0, Pos); 10404 10405 return Success(Str.size(), E); 10406 } 10407 10408 // Fall through to slow path to issue appropriate diagnostic. 10409 } 10410 10411 // Slow path: scan the bytes of the string looking for the terminating 0. 10412 for (uint64_t Strlen = 0; /**/; ++Strlen) { 10413 APValue Char; 10414 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) || 10415 !Char.isInt()) 10416 return false; 10417 if (!Char.getInt()) 10418 return Success(Strlen, E); 10419 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1)) 10420 return false; 10421 } 10422 } 10423 10424 case Builtin::BIstrcmp: 10425 case Builtin::BIwcscmp: 10426 case Builtin::BIstrncmp: 10427 case Builtin::BIwcsncmp: 10428 case Builtin::BImemcmp: 10429 case Builtin::BIbcmp: 10430 case Builtin::BIwmemcmp: 10431 // A call to strlen is not a constant expression. 10432 if (Info.getLangOpts().CPlusPlus11) 10433 Info.CCEDiag(E, diag::note_constexpr_invalid_function) 10434 << /*isConstexpr*/0 << /*isConstructor*/0 10435 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); 10436 else 10437 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); 10438 LLVM_FALLTHROUGH; 10439 case Builtin::BI__builtin_strcmp: 10440 case Builtin::BI__builtin_wcscmp: 10441 case Builtin::BI__builtin_strncmp: 10442 case Builtin::BI__builtin_wcsncmp: 10443 case Builtin::BI__builtin_memcmp: 10444 case Builtin::BI__builtin_bcmp: 10445 case Builtin::BI__builtin_wmemcmp: { 10446 LValue String1, String2; 10447 if (!EvaluatePointer(E->getArg(0), String1, Info) || 10448 !EvaluatePointer(E->getArg(1), String2, Info)) 10449 return false; 10450 10451 uint64_t MaxLength = uint64_t(-1); 10452 if (BuiltinOp != Builtin::BIstrcmp && 10453 BuiltinOp != Builtin::BIwcscmp && 10454 BuiltinOp != Builtin::BI__builtin_strcmp && 10455 BuiltinOp != Builtin::BI__builtin_wcscmp) { 10456 APSInt N; 10457 if (!EvaluateInteger(E->getArg(2), N, Info)) 10458 return false; 10459 MaxLength = N.getExtValue(); 10460 } 10461 10462 // Empty substrings compare equal by definition. 10463 if (MaxLength == 0u) 10464 return Success(0, E); 10465 10466 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) || 10467 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) || 10468 String1.Designator.Invalid || String2.Designator.Invalid) 10469 return false; 10470 10471 QualType CharTy1 = String1.Designator.getType(Info.Ctx); 10472 QualType CharTy2 = String2.Designator.getType(Info.Ctx); 10473 10474 bool IsRawByte = BuiltinOp == Builtin::BImemcmp || 10475 BuiltinOp == Builtin::BIbcmp || 10476 BuiltinOp == Builtin::BI__builtin_memcmp || 10477 BuiltinOp == Builtin::BI__builtin_bcmp; 10478 10479 assert(IsRawByte || 10480 (Info.Ctx.hasSameUnqualifiedType( 10481 CharTy1, E->getArg(0)->getType()->getPointeeType()) && 10482 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2))); 10483 10484 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { 10485 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && 10486 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && 10487 Char1.isInt() && Char2.isInt(); 10488 }; 10489 const auto &AdvanceElems = [&] { 10490 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && 10491 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); 10492 }; 10493 10494 if (IsRawByte) { 10495 uint64_t BytesRemaining = MaxLength; 10496 // Pointers to const void may point to objects of incomplete type. 10497 if (CharTy1->isIncompleteType()) { 10498 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1; 10499 return false; 10500 } 10501 if (CharTy2->isIncompleteType()) { 10502 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2; 10503 return false; 10504 } 10505 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)}; 10506 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width); 10507 // Give up on comparing between elements with disparate widths. 10508 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2)) 10509 return false; 10510 uint64_t BytesPerElement = CharTy1Size.getQuantity(); 10511 assert(BytesRemaining && "BytesRemaining should not be zero: the " 10512 "following loop considers at least one element"); 10513 while (true) { 10514 APValue Char1, Char2; 10515 if (!ReadCurElems(Char1, Char2)) 10516 return false; 10517 // We have compatible in-memory widths, but a possible type and 10518 // (for `bool`) internal representation mismatch. 10519 // Assuming two's complement representation, including 0 for `false` and 10520 // 1 for `true`, we can check an appropriate number of elements for 10521 // equality even if they are not byte-sized. 10522 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width); 10523 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width); 10524 if (Char1InMem.ne(Char2InMem)) { 10525 // If the elements are byte-sized, then we can produce a three-way 10526 // comparison result in a straightforward manner. 10527 if (BytesPerElement == 1u) { 10528 // memcmp always compares unsigned chars. 10529 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E); 10530 } 10531 // The result is byte-order sensitive, and we have multibyte elements. 10532 // FIXME: We can compare the remaining bytes in the correct order. 10533 return false; 10534 } 10535 if (!AdvanceElems()) 10536 return false; 10537 if (BytesRemaining <= BytesPerElement) 10538 break; 10539 BytesRemaining -= BytesPerElement; 10540 } 10541 // Enough elements are equal to account for the memcmp limit. 10542 return Success(0, E); 10543 } 10544 10545 bool StopAtNull = 10546 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp && 10547 BuiltinOp != Builtin::BIwmemcmp && 10548 BuiltinOp != Builtin::BI__builtin_memcmp && 10549 BuiltinOp != Builtin::BI__builtin_bcmp && 10550 BuiltinOp != Builtin::BI__builtin_wmemcmp); 10551 bool IsWide = BuiltinOp == Builtin::BIwcscmp || 10552 BuiltinOp == Builtin::BIwcsncmp || 10553 BuiltinOp == Builtin::BIwmemcmp || 10554 BuiltinOp == Builtin::BI__builtin_wcscmp || 10555 BuiltinOp == Builtin::BI__builtin_wcsncmp || 10556 BuiltinOp == Builtin::BI__builtin_wmemcmp; 10557 10558 for (; MaxLength; --MaxLength) { 10559 APValue Char1, Char2; 10560 if (!ReadCurElems(Char1, Char2)) 10561 return false; 10562 if (Char1.getInt() != Char2.getInt()) { 10563 if (IsWide) // wmemcmp compares with wchar_t signedness. 10564 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E); 10565 // memcmp always compares unsigned chars. 10566 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E); 10567 } 10568 if (StopAtNull && !Char1.getInt()) 10569 return Success(0, E); 10570 assert(!(StopAtNull && !Char2.getInt())); 10571 if (!AdvanceElems()) 10572 return false; 10573 } 10574 // We hit the strncmp / memcmp limit. 10575 return Success(0, E); 10576 } 10577 10578 case Builtin::BI__atomic_always_lock_free: 10579 case Builtin::BI__atomic_is_lock_free: 10580 case Builtin::BI__c11_atomic_is_lock_free: { 10581 APSInt SizeVal; 10582 if (!EvaluateInteger(E->getArg(0), SizeVal, Info)) 10583 return false; 10584 10585 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power 10586 // of two less than the maximum inline atomic width, we know it is 10587 // lock-free. If the size isn't a power of two, or greater than the 10588 // maximum alignment where we promote atomics, we know it is not lock-free 10589 // (at least not in the sense of atomic_is_lock_free). Otherwise, 10590 // the answer can only be determined at runtime; for example, 16-byte 10591 // atomics have lock-free implementations on some, but not all, 10592 // x86-64 processors. 10593 10594 // Check power-of-two. 10595 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue()); 10596 if (Size.isPowerOfTwo()) { 10597 // Check against inlining width. 10598 unsigned InlineWidthBits = 10599 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth(); 10600 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) { 10601 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free || 10602 Size == CharUnits::One() || 10603 E->getArg(1)->isNullPointerConstant(Info.Ctx, 10604 Expr::NPC_NeverValueDependent)) 10605 // OK, we will inline appropriately-aligned operations of this size, 10606 // and _Atomic(T) is appropriately-aligned. 10607 return Success(1, E); 10608 10609 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> 10610 castAs<PointerType>()->getPointeeType(); 10611 if (!PointeeType->isIncompleteType() && 10612 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { 10613 // OK, we will inline operations on this object. 10614 return Success(1, E); 10615 } 10616 } 10617 } 10618 10619 return BuiltinOp == Builtin::BI__atomic_always_lock_free ? 10620 Success(0, E) : Error(E); 10621 } 10622 case Builtin::BIomp_is_initial_device: 10623 // We can decide statically which value the runtime would return if called. 10624 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E); 10625 case Builtin::BI__builtin_add_overflow: 10626 case Builtin::BI__builtin_sub_overflow: 10627 case Builtin::BI__builtin_mul_overflow: 10628 case Builtin::BI__builtin_sadd_overflow: 10629 case Builtin::BI__builtin_uadd_overflow: 10630 case Builtin::BI__builtin_uaddl_overflow: 10631 case Builtin::BI__builtin_uaddll_overflow: 10632 case Builtin::BI__builtin_usub_overflow: 10633 case Builtin::BI__builtin_usubl_overflow: 10634 case Builtin::BI__builtin_usubll_overflow: 10635 case Builtin::BI__builtin_umul_overflow: 10636 case Builtin::BI__builtin_umull_overflow: 10637 case Builtin::BI__builtin_umulll_overflow: 10638 case Builtin::BI__builtin_saddl_overflow: 10639 case Builtin::BI__builtin_saddll_overflow: 10640 case Builtin::BI__builtin_ssub_overflow: 10641 case Builtin::BI__builtin_ssubl_overflow: 10642 case Builtin::BI__builtin_ssubll_overflow: 10643 case Builtin::BI__builtin_smul_overflow: 10644 case Builtin::BI__builtin_smull_overflow: 10645 case Builtin::BI__builtin_smulll_overflow: { 10646 LValue ResultLValue; 10647 APSInt LHS, RHS; 10648 10649 QualType ResultType = E->getArg(2)->getType()->getPointeeType(); 10650 if (!EvaluateInteger(E->getArg(0), LHS, Info) || 10651 !EvaluateInteger(E->getArg(1), RHS, Info) || 10652 !EvaluatePointer(E->getArg(2), ResultLValue, Info)) 10653 return false; 10654 10655 APSInt Result; 10656 bool DidOverflow = false; 10657 10658 // If the types don't have to match, enlarge all 3 to the largest of them. 10659 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 10660 BuiltinOp == Builtin::BI__builtin_sub_overflow || 10661 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 10662 bool IsSigned = LHS.isSigned() || RHS.isSigned() || 10663 ResultType->isSignedIntegerOrEnumerationType(); 10664 bool AllSigned = LHS.isSigned() && RHS.isSigned() && 10665 ResultType->isSignedIntegerOrEnumerationType(); 10666 uint64_t LHSSize = LHS.getBitWidth(); 10667 uint64_t RHSSize = RHS.getBitWidth(); 10668 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); 10669 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize); 10670 10671 // Add an additional bit if the signedness isn't uniformly agreed to. We 10672 // could do this ONLY if there is a signed and an unsigned that both have 10673 // MaxBits, but the code to check that is pretty nasty. The issue will be 10674 // caught in the shrink-to-result later anyway. 10675 if (IsSigned && !AllSigned) 10676 ++MaxBits; 10677 10678 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned); 10679 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned); 10680 Result = APSInt(MaxBits, !IsSigned); 10681 } 10682 10683 // Find largest int. 10684 switch (BuiltinOp) { 10685 default: 10686 llvm_unreachable("Invalid value for BuiltinOp"); 10687 case Builtin::BI__builtin_add_overflow: 10688 case Builtin::BI__builtin_sadd_overflow: 10689 case Builtin::BI__builtin_saddl_overflow: 10690 case Builtin::BI__builtin_saddll_overflow: 10691 case Builtin::BI__builtin_uadd_overflow: 10692 case Builtin::BI__builtin_uaddl_overflow: 10693 case Builtin::BI__builtin_uaddll_overflow: 10694 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow) 10695 : LHS.uadd_ov(RHS, DidOverflow); 10696 break; 10697 case Builtin::BI__builtin_sub_overflow: 10698 case Builtin::BI__builtin_ssub_overflow: 10699 case Builtin::BI__builtin_ssubl_overflow: 10700 case Builtin::BI__builtin_ssubll_overflow: 10701 case Builtin::BI__builtin_usub_overflow: 10702 case Builtin::BI__builtin_usubl_overflow: 10703 case Builtin::BI__builtin_usubll_overflow: 10704 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow) 10705 : LHS.usub_ov(RHS, DidOverflow); 10706 break; 10707 case Builtin::BI__builtin_mul_overflow: 10708 case Builtin::BI__builtin_smul_overflow: 10709 case Builtin::BI__builtin_smull_overflow: 10710 case Builtin::BI__builtin_smulll_overflow: 10711 case Builtin::BI__builtin_umul_overflow: 10712 case Builtin::BI__builtin_umull_overflow: 10713 case Builtin::BI__builtin_umulll_overflow: 10714 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow) 10715 : LHS.umul_ov(RHS, DidOverflow); 10716 break; 10717 } 10718 10719 // In the case where multiple sizes are allowed, truncate and see if 10720 // the values are the same. 10721 if (BuiltinOp == Builtin::BI__builtin_add_overflow || 10722 BuiltinOp == Builtin::BI__builtin_sub_overflow || 10723 BuiltinOp == Builtin::BI__builtin_mul_overflow) { 10724 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead, 10725 // since it will give us the behavior of a TruncOrSelf in the case where 10726 // its parameter <= its size. We previously set Result to be at least the 10727 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth 10728 // will work exactly like TruncOrSelf. 10729 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType)); 10730 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType()); 10731 10732 if (!APSInt::isSameValue(Temp, Result)) 10733 DidOverflow = true; 10734 Result = Temp; 10735 } 10736 10737 APValue APV{Result}; 10738 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV)) 10739 return false; 10740 return Success(DidOverflow, E); 10741 } 10742 } 10743 } 10744 10745 /// Determine whether this is a pointer past the end of the complete 10746 /// object referred to by the lvalue. 10747 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, 10748 const LValue &LV) { 10749 // A null pointer can be viewed as being "past the end" but we don't 10750 // choose to look at it that way here. 10751 if (!LV.getLValueBase()) 10752 return false; 10753 10754 // If the designator is valid and refers to a subobject, we're not pointing 10755 // past the end. 10756 if (!LV.getLValueDesignator().Invalid && 10757 !LV.getLValueDesignator().isOnePastTheEnd()) 10758 return false; 10759 10760 // A pointer to an incomplete type might be past-the-end if the type's size is 10761 // zero. We cannot tell because the type is incomplete. 10762 QualType Ty = getType(LV.getLValueBase()); 10763 if (Ty->isIncompleteType()) 10764 return true; 10765 10766 // We're a past-the-end pointer if we point to the byte after the object, 10767 // no matter what our type or path is. 10768 auto Size = Ctx.getTypeSizeInChars(Ty); 10769 return LV.getLValueOffset() == Size; 10770 } 10771 10772 namespace { 10773 10774 /// Data recursive integer evaluator of certain binary operators. 10775 /// 10776 /// We use a data recursive algorithm for binary operators so that we are able 10777 /// to handle extreme cases of chained binary operators without causing stack 10778 /// overflow. 10779 class DataRecursiveIntBinOpEvaluator { 10780 struct EvalResult { 10781 APValue Val; 10782 bool Failed; 10783 10784 EvalResult() : Failed(false) { } 10785 10786 void swap(EvalResult &RHS) { 10787 Val.swap(RHS.Val); 10788 Failed = RHS.Failed; 10789 RHS.Failed = false; 10790 } 10791 }; 10792 10793 struct Job { 10794 const Expr *E; 10795 EvalResult LHSResult; // meaningful only for binary operator expression. 10796 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; 10797 10798 Job() = default; 10799 Job(Job &&) = default; 10800 10801 void startSpeculativeEval(EvalInfo &Info) { 10802 SpecEvalRAII = SpeculativeEvaluationRAII(Info); 10803 } 10804 10805 private: 10806 SpeculativeEvaluationRAII SpecEvalRAII; 10807 }; 10808 10809 SmallVector<Job, 16> Queue; 10810 10811 IntExprEvaluator &IntEval; 10812 EvalInfo &Info; 10813 APValue &FinalResult; 10814 10815 public: 10816 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) 10817 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } 10818 10819 /// True if \param E is a binary operator that we are going to handle 10820 /// data recursively. 10821 /// We handle binary operators that are comma, logical, or that have operands 10822 /// with integral or enumeration type. 10823 static bool shouldEnqueue(const BinaryOperator *E) { 10824 return E->getOpcode() == BO_Comma || E->isLogicalOp() || 10825 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() && 10826 E->getLHS()->getType()->isIntegralOrEnumerationType() && 10827 E->getRHS()->getType()->isIntegralOrEnumerationType()); 10828 } 10829 10830 bool Traverse(const BinaryOperator *E) { 10831 enqueue(E); 10832 EvalResult PrevResult; 10833 while (!Queue.empty()) 10834 process(PrevResult); 10835 10836 if (PrevResult.Failed) return false; 10837 10838 FinalResult.swap(PrevResult.Val); 10839 return true; 10840 } 10841 10842 private: 10843 bool Success(uint64_t Value, const Expr *E, APValue &Result) { 10844 return IntEval.Success(Value, E, Result); 10845 } 10846 bool Success(const APSInt &Value, const Expr *E, APValue &Result) { 10847 return IntEval.Success(Value, E, Result); 10848 } 10849 bool Error(const Expr *E) { 10850 return IntEval.Error(E); 10851 } 10852 bool Error(const Expr *E, diag::kind D) { 10853 return IntEval.Error(E, D); 10854 } 10855 10856 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { 10857 return Info.CCEDiag(E, D); 10858 } 10859 10860 // Returns true if visiting the RHS is necessary, false otherwise. 10861 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 10862 bool &SuppressRHSDiags); 10863 10864 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 10865 const BinaryOperator *E, APValue &Result); 10866 10867 void EvaluateExpr(const Expr *E, EvalResult &Result) { 10868 Result.Failed = !Evaluate(Result.Val, Info, E); 10869 if (Result.Failed) 10870 Result.Val = APValue(); 10871 } 10872 10873 void process(EvalResult &Result); 10874 10875 void enqueue(const Expr *E) { 10876 E = E->IgnoreParens(); 10877 Queue.resize(Queue.size()+1); 10878 Queue.back().E = E; 10879 Queue.back().Kind = Job::AnyExprKind; 10880 } 10881 }; 10882 10883 } 10884 10885 bool DataRecursiveIntBinOpEvaluator:: 10886 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, 10887 bool &SuppressRHSDiags) { 10888 if (E->getOpcode() == BO_Comma) { 10889 // Ignore LHS but note if we could not evaluate it. 10890 if (LHSResult.Failed) 10891 return Info.noteSideEffect(); 10892 return true; 10893 } 10894 10895 if (E->isLogicalOp()) { 10896 bool LHSAsBool; 10897 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) { 10898 // We were able to evaluate the LHS, see if we can get away with not 10899 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 10900 if (LHSAsBool == (E->getOpcode() == BO_LOr)) { 10901 Success(LHSAsBool, E, LHSResult.Val); 10902 return false; // Ignore RHS 10903 } 10904 } else { 10905 LHSResult.Failed = true; 10906 10907 // Since we weren't able to evaluate the left hand side, it 10908 // might have had side effects. 10909 if (!Info.noteSideEffect()) 10910 return false; 10911 10912 // We can't evaluate the LHS; however, sometimes the result 10913 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 10914 // Don't ignore RHS and suppress diagnostics from this arm. 10915 SuppressRHSDiags = true; 10916 } 10917 10918 return true; 10919 } 10920 10921 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 10922 E->getRHS()->getType()->isIntegralOrEnumerationType()); 10923 10924 if (LHSResult.Failed && !Info.noteFailure()) 10925 return false; // Ignore RHS; 10926 10927 return true; 10928 } 10929 10930 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, 10931 bool IsSub) { 10932 // Compute the new offset in the appropriate width, wrapping at 64 bits. 10933 // FIXME: When compiling for a 32-bit target, we should use 32-bit 10934 // offsets. 10935 assert(!LVal.hasLValuePath() && "have designator for integer lvalue"); 10936 CharUnits &Offset = LVal.getLValueOffset(); 10937 uint64_t Offset64 = Offset.getQuantity(); 10938 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); 10939 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 10940 : Offset64 + Index64); 10941 } 10942 10943 bool DataRecursiveIntBinOpEvaluator:: 10944 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, 10945 const BinaryOperator *E, APValue &Result) { 10946 if (E->getOpcode() == BO_Comma) { 10947 if (RHSResult.Failed) 10948 return false; 10949 Result = RHSResult.Val; 10950 return true; 10951 } 10952 10953 if (E->isLogicalOp()) { 10954 bool lhsResult, rhsResult; 10955 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult); 10956 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult); 10957 10958 if (LHSIsOK) { 10959 if (RHSIsOK) { 10960 if (E->getOpcode() == BO_LOr) 10961 return Success(lhsResult || rhsResult, E, Result); 10962 else 10963 return Success(lhsResult && rhsResult, E, Result); 10964 } 10965 } else { 10966 if (RHSIsOK) { 10967 // We can't evaluate the LHS; however, sometimes the result 10968 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 10969 if (rhsResult == (E->getOpcode() == BO_LOr)) 10970 return Success(rhsResult, E, Result); 10971 } 10972 } 10973 10974 return false; 10975 } 10976 10977 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() && 10978 E->getRHS()->getType()->isIntegralOrEnumerationType()); 10979 10980 if (LHSResult.Failed || RHSResult.Failed) 10981 return false; 10982 10983 const APValue &LHSVal = LHSResult.Val; 10984 const APValue &RHSVal = RHSResult.Val; 10985 10986 // Handle cases like (unsigned long)&a + 4. 10987 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { 10988 Result = LHSVal; 10989 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub); 10990 return true; 10991 } 10992 10993 // Handle cases like 4 + (unsigned long)&a 10994 if (E->getOpcode() == BO_Add && 10995 RHSVal.isLValue() && LHSVal.isInt()) { 10996 Result = RHSVal; 10997 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); 10998 return true; 10999 } 11000 11001 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) { 11002 // Handle (intptr_t)&&A - (intptr_t)&&B. 11003 if (!LHSVal.getLValueOffset().isZero() || 11004 !RHSVal.getLValueOffset().isZero()) 11005 return false; 11006 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>(); 11007 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>(); 11008 if (!LHSExpr || !RHSExpr) 11009 return false; 11010 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 11011 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 11012 if (!LHSAddrExpr || !RHSAddrExpr) 11013 return false; 11014 // Make sure both labels come from the same function. 11015 if (LHSAddrExpr->getLabel()->getDeclContext() != 11016 RHSAddrExpr->getLabel()->getDeclContext()) 11017 return false; 11018 Result = APValue(LHSAddrExpr, RHSAddrExpr); 11019 return true; 11020 } 11021 11022 // All the remaining cases expect both operands to be an integer 11023 if (!LHSVal.isInt() || !RHSVal.isInt()) 11024 return Error(E); 11025 11026 // Set up the width and signedness manually, in case it can't be deduced 11027 // from the operation we're performing. 11028 // FIXME: Don't do this in the cases where we can deduce it. 11029 APSInt Value(Info.Ctx.getIntWidth(E->getType()), 11030 E->getType()->isUnsignedIntegerOrEnumerationType()); 11031 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(), 11032 RHSVal.getInt(), Value)) 11033 return false; 11034 return Success(Value, E, Result); 11035 } 11036 11037 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) { 11038 Job &job = Queue.back(); 11039 11040 switch (job.Kind) { 11041 case Job::AnyExprKind: { 11042 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) { 11043 if (shouldEnqueue(Bop)) { 11044 job.Kind = Job::BinOpKind; 11045 enqueue(Bop->getLHS()); 11046 return; 11047 } 11048 } 11049 11050 EvaluateExpr(job.E, Result); 11051 Queue.pop_back(); 11052 return; 11053 } 11054 11055 case Job::BinOpKind: { 11056 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 11057 bool SuppressRHSDiags = false; 11058 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { 11059 Queue.pop_back(); 11060 return; 11061 } 11062 if (SuppressRHSDiags) 11063 job.startSpeculativeEval(Info); 11064 job.LHSResult.swap(Result); 11065 job.Kind = Job::BinOpVisitedLHSKind; 11066 enqueue(Bop->getRHS()); 11067 return; 11068 } 11069 11070 case Job::BinOpVisitedLHSKind: { 11071 const BinaryOperator *Bop = cast<BinaryOperator>(job.E); 11072 EvalResult RHS; 11073 RHS.swap(Result); 11074 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); 11075 Queue.pop_back(); 11076 return; 11077 } 11078 } 11079 11080 llvm_unreachable("Invalid Job::Kind!"); 11081 } 11082 11083 namespace { 11084 /// Used when we determine that we should fail, but can keep evaluating prior to 11085 /// noting that we had a failure. 11086 class DelayedNoteFailureRAII { 11087 EvalInfo &Info; 11088 bool NoteFailure; 11089 11090 public: 11091 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true) 11092 : Info(Info), NoteFailure(NoteFailure) {} 11093 ~DelayedNoteFailureRAII() { 11094 if (NoteFailure) { 11095 bool ContinueAfterFailure = Info.noteFailure(); 11096 (void)ContinueAfterFailure; 11097 assert(ContinueAfterFailure && 11098 "Shouldn't have kept evaluating on failure."); 11099 } 11100 } 11101 }; 11102 } 11103 11104 template <class SuccessCB, class AfterCB> 11105 static bool 11106 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, 11107 SuccessCB &&Success, AfterCB &&DoAfter) { 11108 assert(E->isComparisonOp() && "expected comparison operator"); 11109 assert((E->getOpcode() == BO_Cmp || 11110 E->getType()->isIntegralOrEnumerationType()) && 11111 "unsupported binary expression evaluation"); 11112 auto Error = [&](const Expr *E) { 11113 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 11114 return false; 11115 }; 11116 11117 using CCR = ComparisonCategoryResult; 11118 bool IsRelational = E->isRelationalOp(); 11119 bool IsEquality = E->isEqualityOp(); 11120 if (E->getOpcode() == BO_Cmp) { 11121 const ComparisonCategoryInfo &CmpInfo = 11122 Info.Ctx.CompCategories.getInfoForType(E->getType()); 11123 IsRelational = CmpInfo.isOrdered(); 11124 IsEquality = CmpInfo.isEquality(); 11125 } 11126 11127 QualType LHSTy = E->getLHS()->getType(); 11128 QualType RHSTy = E->getRHS()->getType(); 11129 11130 if (LHSTy->isIntegralOrEnumerationType() && 11131 RHSTy->isIntegralOrEnumerationType()) { 11132 APSInt LHS, RHS; 11133 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info); 11134 if (!LHSOK && !Info.noteFailure()) 11135 return false; 11136 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK) 11137 return false; 11138 if (LHS < RHS) 11139 return Success(CCR::Less, E); 11140 if (LHS > RHS) 11141 return Success(CCR::Greater, E); 11142 return Success(CCR::Equal, E); 11143 } 11144 11145 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) { 11146 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy)); 11147 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy)); 11148 11149 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info); 11150 if (!LHSOK && !Info.noteFailure()) 11151 return false; 11152 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK) 11153 return false; 11154 if (LHSFX < RHSFX) 11155 return Success(CCR::Less, E); 11156 if (LHSFX > RHSFX) 11157 return Success(CCR::Greater, E); 11158 return Success(CCR::Equal, E); 11159 } 11160 11161 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) { 11162 ComplexValue LHS, RHS; 11163 bool LHSOK; 11164 if (E->isAssignmentOp()) { 11165 LValue LV; 11166 EvaluateLValue(E->getLHS(), LV, Info); 11167 LHSOK = false; 11168 } else if (LHSTy->isRealFloatingType()) { 11169 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info); 11170 if (LHSOK) { 11171 LHS.makeComplexFloat(); 11172 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics()); 11173 } 11174 } else { 11175 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info); 11176 } 11177 if (!LHSOK && !Info.noteFailure()) 11178 return false; 11179 11180 if (E->getRHS()->getType()->isRealFloatingType()) { 11181 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK) 11182 return false; 11183 RHS.makeComplexFloat(); 11184 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics()); 11185 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 11186 return false; 11187 11188 if (LHS.isComplexFloat()) { 11189 APFloat::cmpResult CR_r = 11190 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); 11191 APFloat::cmpResult CR_i = 11192 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); 11193 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; 11194 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 11195 } else { 11196 assert(IsEquality && "invalid complex comparison"); 11197 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() && 11198 LHS.getComplexIntImag() == RHS.getComplexIntImag(); 11199 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E); 11200 } 11201 } 11202 11203 if (LHSTy->isRealFloatingType() && 11204 RHSTy->isRealFloatingType()) { 11205 APFloat RHS(0.0), LHS(0.0); 11206 11207 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); 11208 if (!LHSOK && !Info.noteFailure()) 11209 return false; 11210 11211 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK) 11212 return false; 11213 11214 assert(E->isComparisonOp() && "Invalid binary operator!"); 11215 auto GetCmpRes = [&]() { 11216 switch (LHS.compare(RHS)) { 11217 case APFloat::cmpEqual: 11218 return CCR::Equal; 11219 case APFloat::cmpLessThan: 11220 return CCR::Less; 11221 case APFloat::cmpGreaterThan: 11222 return CCR::Greater; 11223 case APFloat::cmpUnordered: 11224 return CCR::Unordered; 11225 } 11226 llvm_unreachable("Unrecognised APFloat::cmpResult enum"); 11227 }; 11228 return Success(GetCmpRes(), E); 11229 } 11230 11231 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 11232 LValue LHSValue, RHSValue; 11233 11234 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 11235 if (!LHSOK && !Info.noteFailure()) 11236 return false; 11237 11238 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 11239 return false; 11240 11241 // Reject differing bases from the normal codepath; we special-case 11242 // comparisons to null. 11243 if (!HasSameBase(LHSValue, RHSValue)) { 11244 // Inequalities and subtractions between unrelated pointers have 11245 // unspecified or undefined behavior. 11246 if (!IsEquality) 11247 return Error(E); 11248 // A constant address may compare equal to the address of a symbol. 11249 // The one exception is that address of an object cannot compare equal 11250 // to a null pointer constant. 11251 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) || 11252 (!RHSValue.Base && !RHSValue.Offset.isZero())) 11253 return Error(E); 11254 // It's implementation-defined whether distinct literals will have 11255 // distinct addresses. In clang, the result of such a comparison is 11256 // unspecified, so it is not a constant expression. However, we do know 11257 // that the address of a literal will be non-null. 11258 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) && 11259 LHSValue.Base && RHSValue.Base) 11260 return Error(E); 11261 // We can't tell whether weak symbols will end up pointing to the same 11262 // object. 11263 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue)) 11264 return Error(E); 11265 // We can't compare the address of the start of one object with the 11266 // past-the-end address of another object, per C++ DR1652. 11267 if ((LHSValue.Base && LHSValue.Offset.isZero() && 11268 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) || 11269 (RHSValue.Base && RHSValue.Offset.isZero() && 11270 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))) 11271 return Error(E); 11272 // We can't tell whether an object is at the same address as another 11273 // zero sized object. 11274 if ((RHSValue.Base && isZeroSized(LHSValue)) || 11275 (LHSValue.Base && isZeroSized(RHSValue))) 11276 return Error(E); 11277 return Success(CCR::Nonequal, E); 11278 } 11279 11280 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 11281 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 11282 11283 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 11284 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 11285 11286 // C++11 [expr.rel]p3: 11287 // Pointers to void (after pointer conversions) can be compared, with a 11288 // result defined as follows: If both pointers represent the same 11289 // address or are both the null pointer value, the result is true if the 11290 // operator is <= or >= and false otherwise; otherwise the result is 11291 // unspecified. 11292 // We interpret this as applying to pointers to *cv* void. 11293 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational) 11294 Info.CCEDiag(E, diag::note_constexpr_void_comparison); 11295 11296 // C++11 [expr.rel]p2: 11297 // - If two pointers point to non-static data members of the same object, 11298 // or to subobjects or array elements fo such members, recursively, the 11299 // pointer to the later declared member compares greater provided the 11300 // two members have the same access control and provided their class is 11301 // not a union. 11302 // [...] 11303 // - Otherwise pointer comparisons are unspecified. 11304 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) { 11305 bool WasArrayIndex; 11306 unsigned Mismatch = FindDesignatorMismatch( 11307 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex); 11308 // At the point where the designators diverge, the comparison has a 11309 // specified value if: 11310 // - we are comparing array indices 11311 // - we are comparing fields of a union, or fields with the same access 11312 // Otherwise, the result is unspecified and thus the comparison is not a 11313 // constant expression. 11314 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && 11315 Mismatch < RHSDesignator.Entries.size()) { 11316 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); 11317 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); 11318 if (!LF && !RF) 11319 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); 11320 else if (!LF) 11321 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 11322 << getAsBaseClass(LHSDesignator.Entries[Mismatch]) 11323 << RF->getParent() << RF; 11324 else if (!RF) 11325 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field) 11326 << getAsBaseClass(RHSDesignator.Entries[Mismatch]) 11327 << LF->getParent() << LF; 11328 else if (!LF->getParent()->isUnion() && 11329 LF->getAccess() != RF->getAccess()) 11330 Info.CCEDiag(E, 11331 diag::note_constexpr_pointer_comparison_differing_access) 11332 << LF << LF->getAccess() << RF << RF->getAccess() 11333 << LF->getParent(); 11334 } 11335 } 11336 11337 // The comparison here must be unsigned, and performed with the same 11338 // width as the pointer. 11339 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy); 11340 uint64_t CompareLHS = LHSOffset.getQuantity(); 11341 uint64_t CompareRHS = RHSOffset.getQuantity(); 11342 assert(PtrSize <= 64 && "Unexpected pointer width"); 11343 uint64_t Mask = ~0ULL >> (64 - PtrSize); 11344 CompareLHS &= Mask; 11345 CompareRHS &= Mask; 11346 11347 // If there is a base and this is a relational operator, we can only 11348 // compare pointers within the object in question; otherwise, the result 11349 // depends on where the object is located in memory. 11350 if (!LHSValue.Base.isNull() && IsRelational) { 11351 QualType BaseTy = getType(LHSValue.Base); 11352 if (BaseTy->isIncompleteType()) 11353 return Error(E); 11354 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy); 11355 uint64_t OffsetLimit = Size.getQuantity(); 11356 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit) 11357 return Error(E); 11358 } 11359 11360 if (CompareLHS < CompareRHS) 11361 return Success(CCR::Less, E); 11362 if (CompareLHS > CompareRHS) 11363 return Success(CCR::Greater, E); 11364 return Success(CCR::Equal, E); 11365 } 11366 11367 if (LHSTy->isMemberPointerType()) { 11368 assert(IsEquality && "unexpected member pointer operation"); 11369 assert(RHSTy->isMemberPointerType() && "invalid comparison"); 11370 11371 MemberPtr LHSValue, RHSValue; 11372 11373 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info); 11374 if (!LHSOK && !Info.noteFailure()) 11375 return false; 11376 11377 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK) 11378 return false; 11379 11380 // C++11 [expr.eq]p2: 11381 // If both operands are null, they compare equal. Otherwise if only one is 11382 // null, they compare unequal. 11383 if (!LHSValue.getDecl() || !RHSValue.getDecl()) { 11384 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl(); 11385 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 11386 } 11387 11388 // Otherwise if either is a pointer to a virtual member function, the 11389 // result is unspecified. 11390 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl())) 11391 if (MD->isVirtual()) 11392 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 11393 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl())) 11394 if (MD->isVirtual()) 11395 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; 11396 11397 // Otherwise they compare equal if and only if they would refer to the 11398 // same member of the same most derived object or the same subobject if 11399 // they were dereferenced with a hypothetical object of the associated 11400 // class type. 11401 bool Equal = LHSValue == RHSValue; 11402 return Success(Equal ? CCR::Equal : CCR::Nonequal, E); 11403 } 11404 11405 if (LHSTy->isNullPtrType()) { 11406 assert(E->isComparisonOp() && "unexpected nullptr operation"); 11407 assert(RHSTy->isNullPtrType() && "missing pointer conversion"); 11408 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t 11409 // are compared, the result is true of the operator is <=, >= or ==, and 11410 // false otherwise. 11411 return Success(CCR::Equal, E); 11412 } 11413 11414 return DoAfter(); 11415 } 11416 11417 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { 11418 if (!CheckLiteralType(Info, E)) 11419 return false; 11420 11421 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 11422 const BinaryOperator *E) { 11423 // Evaluation succeeded. Lookup the information for the comparison category 11424 // type and fetch the VarDecl for the result. 11425 const ComparisonCategoryInfo &CmpInfo = 11426 Info.Ctx.CompCategories.getInfoForType(E->getType()); 11427 const VarDecl *VD = 11428 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD; 11429 // Check and evaluate the result as a constant expression. 11430 LValue LV; 11431 LV.set(VD); 11432 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 11433 return false; 11434 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result); 11435 }; 11436 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 11437 return ExprEvaluatorBaseTy::VisitBinCmp(E); 11438 }); 11439 } 11440 11441 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 11442 // We don't call noteFailure immediately because the assignment happens after 11443 // we evaluate LHS and RHS. 11444 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp()) 11445 return Error(E); 11446 11447 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp()); 11448 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E)) 11449 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E); 11450 11451 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() || 11452 !E->getRHS()->getType()->isIntegralOrEnumerationType()) && 11453 "DataRecursiveIntBinOpEvaluator should have handled integral types"); 11454 11455 if (E->isComparisonOp()) { 11456 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way 11457 // comparisons and then translating the result. 11458 auto OnSuccess = [&](ComparisonCategoryResult ResKind, 11459 const BinaryOperator *E) { 11460 using CCR = ComparisonCategoryResult; 11461 bool IsEqual = ResKind == CCR::Equal, 11462 IsLess = ResKind == CCR::Less, 11463 IsGreater = ResKind == CCR::Greater; 11464 auto Op = E->getOpcode(); 11465 switch (Op) { 11466 default: 11467 llvm_unreachable("unsupported binary operator"); 11468 case BO_EQ: 11469 case BO_NE: 11470 return Success(IsEqual == (Op == BO_EQ), E); 11471 case BO_LT: return Success(IsLess, E); 11472 case BO_GT: return Success(IsGreater, E); 11473 case BO_LE: return Success(IsEqual || IsLess, E); 11474 case BO_GE: return Success(IsEqual || IsGreater, E); 11475 } 11476 }; 11477 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() { 11478 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11479 }); 11480 } 11481 11482 QualType LHSTy = E->getLHS()->getType(); 11483 QualType RHSTy = E->getRHS()->getType(); 11484 11485 if (LHSTy->isPointerType() && RHSTy->isPointerType() && 11486 E->getOpcode() == BO_Sub) { 11487 LValue LHSValue, RHSValue; 11488 11489 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info); 11490 if (!LHSOK && !Info.noteFailure()) 11491 return false; 11492 11493 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK) 11494 return false; 11495 11496 // Reject differing bases from the normal codepath; we special-case 11497 // comparisons to null. 11498 if (!HasSameBase(LHSValue, RHSValue)) { 11499 // Handle &&A - &&B. 11500 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) 11501 return Error(E); 11502 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>(); 11503 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>(); 11504 if (!LHSExpr || !RHSExpr) 11505 return Error(E); 11506 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr); 11507 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr); 11508 if (!LHSAddrExpr || !RHSAddrExpr) 11509 return Error(E); 11510 // Make sure both labels come from the same function. 11511 if (LHSAddrExpr->getLabel()->getDeclContext() != 11512 RHSAddrExpr->getLabel()->getDeclContext()) 11513 return Error(E); 11514 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); 11515 } 11516 const CharUnits &LHSOffset = LHSValue.getLValueOffset(); 11517 const CharUnits &RHSOffset = RHSValue.getLValueOffset(); 11518 11519 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); 11520 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); 11521 11522 // C++11 [expr.add]p6: 11523 // Unless both pointers point to elements of the same array object, or 11524 // one past the last element of the array object, the behavior is 11525 // undefined. 11526 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && 11527 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator, 11528 RHSDesignator)) 11529 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array); 11530 11531 QualType Type = E->getLHS()->getType(); 11532 QualType ElementType = Type->getAs<PointerType>()->getPointeeType(); 11533 11534 CharUnits ElementSize; 11535 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) 11536 return false; 11537 11538 // As an extension, a type may have zero size (empty struct or union in 11539 // C, array of zero length). Pointer subtraction in such cases has 11540 // undefined behavior, so is not constant. 11541 if (ElementSize.isZero()) { 11542 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size) 11543 << ElementType; 11544 return false; 11545 } 11546 11547 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, 11548 // and produce incorrect results when it overflows. Such behavior 11549 // appears to be non-conforming, but is common, so perhaps we should 11550 // assume the standard intended for such cases to be undefined behavior 11551 // and check for them. 11552 11553 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for 11554 // overflow in the final conversion to ptrdiff_t. 11555 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false); 11556 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false); 11557 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), 11558 false); 11559 APSInt TrueResult = (LHS - RHS) / ElemSize; 11560 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType())); 11561 11562 if (Result.extend(65) != TrueResult && 11563 !HandleOverflow(Info, E, TrueResult, E->getType())) 11564 return false; 11565 return Success(Result, E); 11566 } 11567 11568 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 11569 } 11570 11571 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with 11572 /// a result as the expression's type. 11573 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( 11574 const UnaryExprOrTypeTraitExpr *E) { 11575 switch(E->getKind()) { 11576 case UETT_PreferredAlignOf: 11577 case UETT_AlignOf: { 11578 if (E->isArgumentType()) 11579 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()), 11580 E); 11581 else 11582 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()), 11583 E); 11584 } 11585 11586 case UETT_VecStep: { 11587 QualType Ty = E->getTypeOfArgument(); 11588 11589 if (Ty->isVectorType()) { 11590 unsigned n = Ty->castAs<VectorType>()->getNumElements(); 11591 11592 // The vec_step built-in functions that take a 3-component 11593 // vector return 4. (OpenCL 1.1 spec 6.11.12) 11594 if (n == 3) 11595 n = 4; 11596 11597 return Success(n, E); 11598 } else 11599 return Success(1, E); 11600 } 11601 11602 case UETT_SizeOf: { 11603 QualType SrcTy = E->getTypeOfArgument(); 11604 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 11605 // the result is the size of the referenced type." 11606 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>()) 11607 SrcTy = Ref->getPointeeType(); 11608 11609 CharUnits Sizeof; 11610 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof)) 11611 return false; 11612 return Success(Sizeof, E); 11613 } 11614 case UETT_OpenMPRequiredSimdAlign: 11615 assert(E->isArgumentType()); 11616 return Success( 11617 Info.Ctx.toCharUnitsFromBits( 11618 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) 11619 .getQuantity(), 11620 E); 11621 } 11622 11623 llvm_unreachable("unknown expr/type trait"); 11624 } 11625 11626 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { 11627 CharUnits Result; 11628 unsigned n = OOE->getNumComponents(); 11629 if (n == 0) 11630 return Error(OOE); 11631 QualType CurrentType = OOE->getTypeSourceInfo()->getType(); 11632 for (unsigned i = 0; i != n; ++i) { 11633 OffsetOfNode ON = OOE->getComponent(i); 11634 switch (ON.getKind()) { 11635 case OffsetOfNode::Array: { 11636 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); 11637 APSInt IdxResult; 11638 if (!EvaluateInteger(Idx, IdxResult, Info)) 11639 return false; 11640 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); 11641 if (!AT) 11642 return Error(OOE); 11643 CurrentType = AT->getElementType(); 11644 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType); 11645 Result += IdxResult.getSExtValue() * ElementSize; 11646 break; 11647 } 11648 11649 case OffsetOfNode::Field: { 11650 FieldDecl *MemberDecl = ON.getField(); 11651 const RecordType *RT = CurrentType->getAs<RecordType>(); 11652 if (!RT) 11653 return Error(OOE); 11654 RecordDecl *RD = RT->getDecl(); 11655 if (RD->isInvalidDecl()) return false; 11656 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 11657 unsigned i = MemberDecl->getFieldIndex(); 11658 assert(i < RL.getFieldCount() && "offsetof field in wrong type"); 11659 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); 11660 CurrentType = MemberDecl->getType().getNonReferenceType(); 11661 break; 11662 } 11663 11664 case OffsetOfNode::Identifier: 11665 llvm_unreachable("dependent __builtin_offsetof"); 11666 11667 case OffsetOfNode::Base: { 11668 CXXBaseSpecifier *BaseSpec = ON.getBase(); 11669 if (BaseSpec->isVirtual()) 11670 return Error(OOE); 11671 11672 // Find the layout of the class whose base we are looking into. 11673 const RecordType *RT = CurrentType->getAs<RecordType>(); 11674 if (!RT) 11675 return Error(OOE); 11676 RecordDecl *RD = RT->getDecl(); 11677 if (RD->isInvalidDecl()) return false; 11678 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); 11679 11680 // Find the base class itself. 11681 CurrentType = BaseSpec->getType(); 11682 const RecordType *BaseRT = CurrentType->getAs<RecordType>(); 11683 if (!BaseRT) 11684 return Error(OOE); 11685 11686 // Add the offset to the base. 11687 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl())); 11688 break; 11689 } 11690 } 11691 } 11692 return Success(Result, OOE); 11693 } 11694 11695 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 11696 switch (E->getOpcode()) { 11697 default: 11698 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 11699 // See C99 6.6p3. 11700 return Error(E); 11701 case UO_Extension: 11702 // FIXME: Should extension allow i-c-e extension expressions in its scope? 11703 // If so, we could clear the diagnostic ID. 11704 return Visit(E->getSubExpr()); 11705 case UO_Plus: 11706 // The result is just the value. 11707 return Visit(E->getSubExpr()); 11708 case UO_Minus: { 11709 if (!Visit(E->getSubExpr())) 11710 return false; 11711 if (!Result.isInt()) return Error(E); 11712 const APSInt &Value = Result.getInt(); 11713 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && 11714 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), 11715 E->getType())) 11716 return false; 11717 return Success(-Value, E); 11718 } 11719 case UO_Not: { 11720 if (!Visit(E->getSubExpr())) 11721 return false; 11722 if (!Result.isInt()) return Error(E); 11723 return Success(~Result.getInt(), E); 11724 } 11725 case UO_LNot: { 11726 bool bres; 11727 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 11728 return false; 11729 return Success(!bres, E); 11730 } 11731 } 11732 } 11733 11734 /// HandleCast - This is used to evaluate implicit or explicit casts where the 11735 /// result type is integer. 11736 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { 11737 const Expr *SubExpr = E->getSubExpr(); 11738 QualType DestType = E->getType(); 11739 QualType SrcType = SubExpr->getType(); 11740 11741 switch (E->getCastKind()) { 11742 case CK_BaseToDerived: 11743 case CK_DerivedToBase: 11744 case CK_UncheckedDerivedToBase: 11745 case CK_Dynamic: 11746 case CK_ToUnion: 11747 case CK_ArrayToPointerDecay: 11748 case CK_FunctionToPointerDecay: 11749 case CK_NullToPointer: 11750 case CK_NullToMemberPointer: 11751 case CK_BaseToDerivedMemberPointer: 11752 case CK_DerivedToBaseMemberPointer: 11753 case CK_ReinterpretMemberPointer: 11754 case CK_ConstructorConversion: 11755 case CK_IntegralToPointer: 11756 case CK_ToVoid: 11757 case CK_VectorSplat: 11758 case CK_IntegralToFloating: 11759 case CK_FloatingCast: 11760 case CK_CPointerToObjCPointerCast: 11761 case CK_BlockPointerToObjCPointerCast: 11762 case CK_AnyPointerToBlockPointerCast: 11763 case CK_ObjCObjectLValueCast: 11764 case CK_FloatingRealToComplex: 11765 case CK_FloatingComplexToReal: 11766 case CK_FloatingComplexCast: 11767 case CK_FloatingComplexToIntegralComplex: 11768 case CK_IntegralRealToComplex: 11769 case CK_IntegralComplexCast: 11770 case CK_IntegralComplexToFloatingComplex: 11771 case CK_BuiltinFnToFnPtr: 11772 case CK_ZeroToOCLOpaqueType: 11773 case CK_NonAtomicToAtomic: 11774 case CK_AddressSpaceConversion: 11775 case CK_IntToOCLSampler: 11776 case CK_FixedPointCast: 11777 case CK_IntegralToFixedPoint: 11778 llvm_unreachable("invalid cast kind for integral value"); 11779 11780 case CK_BitCast: 11781 case CK_Dependent: 11782 case CK_LValueBitCast: 11783 case CK_ARCProduceObject: 11784 case CK_ARCConsumeObject: 11785 case CK_ARCReclaimReturnedObject: 11786 case CK_ARCExtendBlockObject: 11787 case CK_CopyAndAutoreleaseBlockObject: 11788 return Error(E); 11789 11790 case CK_UserDefinedConversion: 11791 case CK_LValueToRValue: 11792 case CK_AtomicToNonAtomic: 11793 case CK_NoOp: 11794 case CK_LValueToRValueBitCast: 11795 return ExprEvaluatorBaseTy::VisitCastExpr(E); 11796 11797 case CK_MemberPointerToBoolean: 11798 case CK_PointerToBoolean: 11799 case CK_IntegralToBoolean: 11800 case CK_FloatingToBoolean: 11801 case CK_BooleanToSignedIntegral: 11802 case CK_FloatingComplexToBoolean: 11803 case CK_IntegralComplexToBoolean: { 11804 bool BoolResult; 11805 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info)) 11806 return false; 11807 uint64_t IntResult = BoolResult; 11808 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral) 11809 IntResult = (uint64_t)-1; 11810 return Success(IntResult, E); 11811 } 11812 11813 case CK_FixedPointToIntegral: { 11814 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType)); 11815 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 11816 return false; 11817 bool Overflowed; 11818 llvm::APSInt Result = Src.convertToInt( 11819 Info.Ctx.getIntWidth(DestType), 11820 DestType->isSignedIntegerOrEnumerationType(), &Overflowed); 11821 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 11822 return false; 11823 return Success(Result, E); 11824 } 11825 11826 case CK_FixedPointToBoolean: { 11827 // Unsigned padding does not affect this. 11828 APValue Val; 11829 if (!Evaluate(Val, Info, SubExpr)) 11830 return false; 11831 return Success(Val.getFixedPoint().getBoolValue(), E); 11832 } 11833 11834 case CK_IntegralCast: { 11835 if (!Visit(SubExpr)) 11836 return false; 11837 11838 if (!Result.isInt()) { 11839 // Allow casts of address-of-label differences if they are no-ops 11840 // or narrowing. (The narrowing case isn't actually guaranteed to 11841 // be constant-evaluatable except in some narrow cases which are hard 11842 // to detect here. We let it through on the assumption the user knows 11843 // what they are doing.) 11844 if (Result.isAddrLabelDiff()) 11845 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType); 11846 // Only allow casts of lvalues if they are lossless. 11847 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); 11848 } 11849 11850 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, 11851 Result.getInt()), E); 11852 } 11853 11854 case CK_PointerToIntegral: { 11855 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; 11856 11857 LValue LV; 11858 if (!EvaluatePointer(SubExpr, LV, Info)) 11859 return false; 11860 11861 if (LV.getLValueBase()) { 11862 // Only allow based lvalue casts if they are lossless. 11863 // FIXME: Allow a larger integer size than the pointer size, and allow 11864 // narrowing back down to pointer width in subsequent integral casts. 11865 // FIXME: Check integer type's active bits, not its type size. 11866 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType)) 11867 return Error(E); 11868 11869 LV.Designator.setInvalid(); 11870 LV.moveInto(Result); 11871 return true; 11872 } 11873 11874 APSInt AsInt; 11875 APValue V; 11876 LV.moveInto(V); 11877 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx)) 11878 llvm_unreachable("Can't cast this!"); 11879 11880 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E); 11881 } 11882 11883 case CK_IntegralComplexToReal: { 11884 ComplexValue C; 11885 if (!EvaluateComplex(SubExpr, C, Info)) 11886 return false; 11887 return Success(C.getComplexIntReal(), E); 11888 } 11889 11890 case CK_FloatingToIntegral: { 11891 APFloat F(0.0); 11892 if (!EvaluateFloat(SubExpr, F, Info)) 11893 return false; 11894 11895 APSInt Value; 11896 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value)) 11897 return false; 11898 return Success(Value, E); 11899 } 11900 } 11901 11902 llvm_unreachable("unknown cast resulting in integral value"); 11903 } 11904 11905 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 11906 if (E->getSubExpr()->getType()->isAnyComplexType()) { 11907 ComplexValue LV; 11908 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 11909 return false; 11910 if (!LV.isComplexInt()) 11911 return Error(E); 11912 return Success(LV.getComplexIntReal(), E); 11913 } 11914 11915 return Visit(E->getSubExpr()); 11916 } 11917 11918 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 11919 if (E->getSubExpr()->getType()->isComplexIntegerType()) { 11920 ComplexValue LV; 11921 if (!EvaluateComplex(E->getSubExpr(), LV, Info)) 11922 return false; 11923 if (!LV.isComplexInt()) 11924 return Error(E); 11925 return Success(LV.getComplexIntImag(), E); 11926 } 11927 11928 VisitIgnoredValue(E->getSubExpr()); 11929 return Success(0, E); 11930 } 11931 11932 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 11933 return Success(E->getPackLength(), E); 11934 } 11935 11936 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 11937 return Success(E->getValue(), E); 11938 } 11939 11940 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 11941 switch (E->getOpcode()) { 11942 default: 11943 // Invalid unary operators 11944 return Error(E); 11945 case UO_Plus: 11946 // The result is just the value. 11947 return Visit(E->getSubExpr()); 11948 case UO_Minus: { 11949 if (!Visit(E->getSubExpr())) return false; 11950 if (!Result.isFixedPoint()) 11951 return Error(E); 11952 bool Overflowed; 11953 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); 11954 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) 11955 return false; 11956 return Success(Negated, E); 11957 } 11958 case UO_LNot: { 11959 bool bres; 11960 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) 11961 return false; 11962 return Success(!bres, E); 11963 } 11964 } 11965 } 11966 11967 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { 11968 const Expr *SubExpr = E->getSubExpr(); 11969 QualType DestType = E->getType(); 11970 assert(DestType->isFixedPointType() && 11971 "Expected destination type to be a fixed point type"); 11972 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType); 11973 11974 switch (E->getCastKind()) { 11975 case CK_FixedPointCast: { 11976 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType())); 11977 if (!EvaluateFixedPoint(SubExpr, Src, Info)) 11978 return false; 11979 bool Overflowed; 11980 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); 11981 if (Overflowed && !HandleOverflow(Info, E, Result, DestType)) 11982 return false; 11983 return Success(Result, E); 11984 } 11985 case CK_IntegralToFixedPoint: { 11986 APSInt Src; 11987 if (!EvaluateInteger(SubExpr, Src, Info)) 11988 return false; 11989 11990 bool Overflowed; 11991 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11992 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed); 11993 11994 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType)) 11995 return false; 11996 11997 return Success(IntResult, E); 11998 } 11999 case CK_NoOp: 12000 case CK_LValueToRValue: 12001 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12002 default: 12003 return Error(E); 12004 } 12005 } 12006 12007 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12008 const Expr *LHS = E->getLHS(); 12009 const Expr *RHS = E->getRHS(); 12010 FixedPointSemantics ResultFXSema = 12011 Info.Ctx.getFixedPointSemantics(E->getType()); 12012 12013 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType())); 12014 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info)) 12015 return false; 12016 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType())); 12017 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info)) 12018 return false; 12019 12020 switch (E->getOpcode()) { 12021 case BO_Add: { 12022 bool AddOverflow, ConversionOverflow; 12023 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow) 12024 .convert(ResultFXSema, &ConversionOverflow); 12025 if ((AddOverflow || ConversionOverflow) && 12026 !HandleOverflow(Info, E, Result, E->getType())) 12027 return false; 12028 return Success(Result, E); 12029 } 12030 default: 12031 return false; 12032 } 12033 llvm_unreachable("Should've exited before this"); 12034 } 12035 12036 //===----------------------------------------------------------------------===// 12037 // Float Evaluation 12038 //===----------------------------------------------------------------------===// 12039 12040 namespace { 12041 class FloatExprEvaluator 12042 : public ExprEvaluatorBase<FloatExprEvaluator> { 12043 APFloat &Result; 12044 public: 12045 FloatExprEvaluator(EvalInfo &info, APFloat &result) 12046 : ExprEvaluatorBaseTy(info), Result(result) {} 12047 12048 bool Success(const APValue &V, const Expr *e) { 12049 Result = V.getFloat(); 12050 return true; 12051 } 12052 12053 bool ZeroInitialization(const Expr *E) { 12054 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); 12055 return true; 12056 } 12057 12058 bool VisitCallExpr(const CallExpr *E); 12059 12060 bool VisitUnaryOperator(const UnaryOperator *E); 12061 bool VisitBinaryOperator(const BinaryOperator *E); 12062 bool VisitFloatingLiteral(const FloatingLiteral *E); 12063 bool VisitCastExpr(const CastExpr *E); 12064 12065 bool VisitUnaryReal(const UnaryOperator *E); 12066 bool VisitUnaryImag(const UnaryOperator *E); 12067 12068 // FIXME: Missing: array subscript of vector, member of vector 12069 }; 12070 } // end anonymous namespace 12071 12072 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { 12073 assert(E->isRValue() && E->getType()->isRealFloatingType()); 12074 return FloatExprEvaluator(Info, Result).Visit(E); 12075 } 12076 12077 static bool TryEvaluateBuiltinNaN(const ASTContext &Context, 12078 QualType ResultTy, 12079 const Expr *Arg, 12080 bool SNaN, 12081 llvm::APFloat &Result) { 12082 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 12083 if (!S) return false; 12084 12085 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); 12086 12087 llvm::APInt fill; 12088 12089 // Treat empty strings as if they were zero. 12090 if (S->getString().empty()) 12091 fill = llvm::APInt(32, 0); 12092 else if (S->getString().getAsInteger(0, fill)) 12093 return false; 12094 12095 if (Context.getTargetInfo().isNan2008()) { 12096 if (SNaN) 12097 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 12098 else 12099 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 12100 } else { 12101 // Prior to IEEE 754-2008, architectures were allowed to choose whether 12102 // the first bit of their significand was set for qNaN or sNaN. MIPS chose 12103 // a different encoding to what became a standard in 2008, and for pre- 12104 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as 12105 // sNaN. This is now known as "legacy NaN" encoding. 12106 if (SNaN) 12107 Result = llvm::APFloat::getQNaN(Sem, false, &fill); 12108 else 12109 Result = llvm::APFloat::getSNaN(Sem, false, &fill); 12110 } 12111 12112 return true; 12113 } 12114 12115 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { 12116 switch (E->getBuiltinCallee()) { 12117 default: 12118 return ExprEvaluatorBaseTy::VisitCallExpr(E); 12119 12120 case Builtin::BI__builtin_huge_val: 12121 case Builtin::BI__builtin_huge_valf: 12122 case Builtin::BI__builtin_huge_vall: 12123 case Builtin::BI__builtin_huge_valf128: 12124 case Builtin::BI__builtin_inf: 12125 case Builtin::BI__builtin_inff: 12126 case Builtin::BI__builtin_infl: 12127 case Builtin::BI__builtin_inff128: { 12128 const llvm::fltSemantics &Sem = 12129 Info.Ctx.getFloatTypeSemantics(E->getType()); 12130 Result = llvm::APFloat::getInf(Sem); 12131 return true; 12132 } 12133 12134 case Builtin::BI__builtin_nans: 12135 case Builtin::BI__builtin_nansf: 12136 case Builtin::BI__builtin_nansl: 12137 case Builtin::BI__builtin_nansf128: 12138 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 12139 true, Result)) 12140 return Error(E); 12141 return true; 12142 12143 case Builtin::BI__builtin_nan: 12144 case Builtin::BI__builtin_nanf: 12145 case Builtin::BI__builtin_nanl: 12146 case Builtin::BI__builtin_nanf128: 12147 // If this is __builtin_nan() turn this into a nan, otherwise we 12148 // can't constant fold it. 12149 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), 12150 false, Result)) 12151 return Error(E); 12152 return true; 12153 12154 case Builtin::BI__builtin_fabs: 12155 case Builtin::BI__builtin_fabsf: 12156 case Builtin::BI__builtin_fabsl: 12157 case Builtin::BI__builtin_fabsf128: 12158 if (!EvaluateFloat(E->getArg(0), Result, Info)) 12159 return false; 12160 12161 if (Result.isNegative()) 12162 Result.changeSign(); 12163 return true; 12164 12165 // FIXME: Builtin::BI__builtin_powi 12166 // FIXME: Builtin::BI__builtin_powif 12167 // FIXME: Builtin::BI__builtin_powil 12168 12169 case Builtin::BI__builtin_copysign: 12170 case Builtin::BI__builtin_copysignf: 12171 case Builtin::BI__builtin_copysignl: 12172 case Builtin::BI__builtin_copysignf128: { 12173 APFloat RHS(0.); 12174 if (!EvaluateFloat(E->getArg(0), Result, Info) || 12175 !EvaluateFloat(E->getArg(1), RHS, Info)) 12176 return false; 12177 Result.copySign(RHS); 12178 return true; 12179 } 12180 } 12181 } 12182 12183 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { 12184 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12185 ComplexValue CV; 12186 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 12187 return false; 12188 Result = CV.FloatReal; 12189 return true; 12190 } 12191 12192 return Visit(E->getSubExpr()); 12193 } 12194 12195 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { 12196 if (E->getSubExpr()->getType()->isAnyComplexType()) { 12197 ComplexValue CV; 12198 if (!EvaluateComplex(E->getSubExpr(), CV, Info)) 12199 return false; 12200 Result = CV.FloatImag; 12201 return true; 12202 } 12203 12204 VisitIgnoredValue(E->getSubExpr()); 12205 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); 12206 Result = llvm::APFloat::getZero(Sem); 12207 return true; 12208 } 12209 12210 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12211 switch (E->getOpcode()) { 12212 default: return Error(E); 12213 case UO_Plus: 12214 return EvaluateFloat(E->getSubExpr(), Result, Info); 12215 case UO_Minus: 12216 if (!EvaluateFloat(E->getSubExpr(), Result, Info)) 12217 return false; 12218 Result.changeSign(); 12219 return true; 12220 } 12221 } 12222 12223 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12224 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 12225 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12226 12227 APFloat RHS(0.0); 12228 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info); 12229 if (!LHSOK && !Info.noteFailure()) 12230 return false; 12231 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK && 12232 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); 12233 } 12234 12235 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { 12236 Result = E->getValue(); 12237 return true; 12238 } 12239 12240 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { 12241 const Expr* SubExpr = E->getSubExpr(); 12242 12243 switch (E->getCastKind()) { 12244 default: 12245 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12246 12247 case CK_IntegralToFloating: { 12248 APSInt IntResult; 12249 return EvaluateInteger(SubExpr, IntResult, Info) && 12250 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult, 12251 E->getType(), Result); 12252 } 12253 12254 case CK_FloatingCast: { 12255 if (!Visit(SubExpr)) 12256 return false; 12257 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(), 12258 Result); 12259 } 12260 12261 case CK_FloatingComplexToReal: { 12262 ComplexValue V; 12263 if (!EvaluateComplex(SubExpr, V, Info)) 12264 return false; 12265 Result = V.getComplexFloatReal(); 12266 return true; 12267 } 12268 } 12269 } 12270 12271 //===----------------------------------------------------------------------===// 12272 // Complex Evaluation (for float and integer) 12273 //===----------------------------------------------------------------------===// 12274 12275 namespace { 12276 class ComplexExprEvaluator 12277 : public ExprEvaluatorBase<ComplexExprEvaluator> { 12278 ComplexValue &Result; 12279 12280 public: 12281 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) 12282 : ExprEvaluatorBaseTy(info), Result(Result) {} 12283 12284 bool Success(const APValue &V, const Expr *e) { 12285 Result.setFrom(V); 12286 return true; 12287 } 12288 12289 bool ZeroInitialization(const Expr *E); 12290 12291 //===--------------------------------------------------------------------===// 12292 // Visitor Methods 12293 //===--------------------------------------------------------------------===// 12294 12295 bool VisitImaginaryLiteral(const ImaginaryLiteral *E); 12296 bool VisitCastExpr(const CastExpr *E); 12297 bool VisitBinaryOperator(const BinaryOperator *E); 12298 bool VisitUnaryOperator(const UnaryOperator *E); 12299 bool VisitInitListExpr(const InitListExpr *E); 12300 }; 12301 } // end anonymous namespace 12302 12303 static bool EvaluateComplex(const Expr *E, ComplexValue &Result, 12304 EvalInfo &Info) { 12305 assert(E->isRValue() && E->getType()->isAnyComplexType()); 12306 return ComplexExprEvaluator(Info, Result).Visit(E); 12307 } 12308 12309 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { 12310 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType(); 12311 if (ElemTy->isRealFloatingType()) { 12312 Result.makeComplexFloat(); 12313 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy)); 12314 Result.FloatReal = Zero; 12315 Result.FloatImag = Zero; 12316 } else { 12317 Result.makeComplexInt(); 12318 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy); 12319 Result.IntReal = Zero; 12320 Result.IntImag = Zero; 12321 } 12322 return true; 12323 } 12324 12325 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 12326 const Expr* SubExpr = E->getSubExpr(); 12327 12328 if (SubExpr->getType()->isRealFloatingType()) { 12329 Result.makeComplexFloat(); 12330 APFloat &Imag = Result.FloatImag; 12331 if (!EvaluateFloat(SubExpr, Imag, Info)) 12332 return false; 12333 12334 Result.FloatReal = APFloat(Imag.getSemantics()); 12335 return true; 12336 } else { 12337 assert(SubExpr->getType()->isIntegerType() && 12338 "Unexpected imaginary literal."); 12339 12340 Result.makeComplexInt(); 12341 APSInt &Imag = Result.IntImag; 12342 if (!EvaluateInteger(SubExpr, Imag, Info)) 12343 return false; 12344 12345 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned()); 12346 return true; 12347 } 12348 } 12349 12350 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { 12351 12352 switch (E->getCastKind()) { 12353 case CK_BitCast: 12354 case CK_BaseToDerived: 12355 case CK_DerivedToBase: 12356 case CK_UncheckedDerivedToBase: 12357 case CK_Dynamic: 12358 case CK_ToUnion: 12359 case CK_ArrayToPointerDecay: 12360 case CK_FunctionToPointerDecay: 12361 case CK_NullToPointer: 12362 case CK_NullToMemberPointer: 12363 case CK_BaseToDerivedMemberPointer: 12364 case CK_DerivedToBaseMemberPointer: 12365 case CK_MemberPointerToBoolean: 12366 case CK_ReinterpretMemberPointer: 12367 case CK_ConstructorConversion: 12368 case CK_IntegralToPointer: 12369 case CK_PointerToIntegral: 12370 case CK_PointerToBoolean: 12371 case CK_ToVoid: 12372 case CK_VectorSplat: 12373 case CK_IntegralCast: 12374 case CK_BooleanToSignedIntegral: 12375 case CK_IntegralToBoolean: 12376 case CK_IntegralToFloating: 12377 case CK_FloatingToIntegral: 12378 case CK_FloatingToBoolean: 12379 case CK_FloatingCast: 12380 case CK_CPointerToObjCPointerCast: 12381 case CK_BlockPointerToObjCPointerCast: 12382 case CK_AnyPointerToBlockPointerCast: 12383 case CK_ObjCObjectLValueCast: 12384 case CK_FloatingComplexToReal: 12385 case CK_FloatingComplexToBoolean: 12386 case CK_IntegralComplexToReal: 12387 case CK_IntegralComplexToBoolean: 12388 case CK_ARCProduceObject: 12389 case CK_ARCConsumeObject: 12390 case CK_ARCReclaimReturnedObject: 12391 case CK_ARCExtendBlockObject: 12392 case CK_CopyAndAutoreleaseBlockObject: 12393 case CK_BuiltinFnToFnPtr: 12394 case CK_ZeroToOCLOpaqueType: 12395 case CK_NonAtomicToAtomic: 12396 case CK_AddressSpaceConversion: 12397 case CK_IntToOCLSampler: 12398 case CK_FixedPointCast: 12399 case CK_FixedPointToBoolean: 12400 case CK_FixedPointToIntegral: 12401 case CK_IntegralToFixedPoint: 12402 llvm_unreachable("invalid cast kind for complex value"); 12403 12404 case CK_LValueToRValue: 12405 case CK_AtomicToNonAtomic: 12406 case CK_NoOp: 12407 case CK_LValueToRValueBitCast: 12408 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12409 12410 case CK_Dependent: 12411 case CK_LValueBitCast: 12412 case CK_UserDefinedConversion: 12413 return Error(E); 12414 12415 case CK_FloatingRealToComplex: { 12416 APFloat &Real = Result.FloatReal; 12417 if (!EvaluateFloat(E->getSubExpr(), Real, Info)) 12418 return false; 12419 12420 Result.makeComplexFloat(); 12421 Result.FloatImag = APFloat(Real.getSemantics()); 12422 return true; 12423 } 12424 12425 case CK_FloatingComplexCast: { 12426 if (!Visit(E->getSubExpr())) 12427 return false; 12428 12429 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 12430 QualType From 12431 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 12432 12433 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && 12434 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); 12435 } 12436 12437 case CK_FloatingComplexToIntegralComplex: { 12438 if (!Visit(E->getSubExpr())) 12439 return false; 12440 12441 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 12442 QualType From 12443 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 12444 Result.makeComplexInt(); 12445 return HandleFloatToIntCast(Info, E, From, Result.FloatReal, 12446 To, Result.IntReal) && 12447 HandleFloatToIntCast(Info, E, From, Result.FloatImag, 12448 To, Result.IntImag); 12449 } 12450 12451 case CK_IntegralRealToComplex: { 12452 APSInt &Real = Result.IntReal; 12453 if (!EvaluateInteger(E->getSubExpr(), Real, Info)) 12454 return false; 12455 12456 Result.makeComplexInt(); 12457 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned()); 12458 return true; 12459 } 12460 12461 case CK_IntegralComplexCast: { 12462 if (!Visit(E->getSubExpr())) 12463 return false; 12464 12465 QualType To = E->getType()->getAs<ComplexType>()->getElementType(); 12466 QualType From 12467 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType(); 12468 12469 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); 12470 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); 12471 return true; 12472 } 12473 12474 case CK_IntegralComplexToFloatingComplex: { 12475 if (!Visit(E->getSubExpr())) 12476 return false; 12477 12478 QualType To = E->getType()->castAs<ComplexType>()->getElementType(); 12479 QualType From 12480 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType(); 12481 Result.makeComplexFloat(); 12482 return HandleIntToFloatCast(Info, E, From, Result.IntReal, 12483 To, Result.FloatReal) && 12484 HandleIntToFloatCast(Info, E, From, Result.IntImag, 12485 To, Result.FloatImag); 12486 } 12487 } 12488 12489 llvm_unreachable("unknown cast resulting in complex value"); 12490 } 12491 12492 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { 12493 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) 12494 return ExprEvaluatorBaseTy::VisitBinaryOperator(E); 12495 12496 // Track whether the LHS or RHS is real at the type system level. When this is 12497 // the case we can simplify our evaluation strategy. 12498 bool LHSReal = false, RHSReal = false; 12499 12500 bool LHSOK; 12501 if (E->getLHS()->getType()->isRealFloatingType()) { 12502 LHSReal = true; 12503 APFloat &Real = Result.FloatReal; 12504 LHSOK = EvaluateFloat(E->getLHS(), Real, Info); 12505 if (LHSOK) { 12506 Result.makeComplexFloat(); 12507 Result.FloatImag = APFloat(Real.getSemantics()); 12508 } 12509 } else { 12510 LHSOK = Visit(E->getLHS()); 12511 } 12512 if (!LHSOK && !Info.noteFailure()) 12513 return false; 12514 12515 ComplexValue RHS; 12516 if (E->getRHS()->getType()->isRealFloatingType()) { 12517 RHSReal = true; 12518 APFloat &Real = RHS.FloatReal; 12519 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK) 12520 return false; 12521 RHS.makeComplexFloat(); 12522 RHS.FloatImag = APFloat(Real.getSemantics()); 12523 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK) 12524 return false; 12525 12526 assert(!(LHSReal && RHSReal) && 12527 "Cannot have both operands of a complex operation be real."); 12528 switch (E->getOpcode()) { 12529 default: return Error(E); 12530 case BO_Add: 12531 if (Result.isComplexFloat()) { 12532 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), 12533 APFloat::rmNearestTiesToEven); 12534 if (LHSReal) 12535 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 12536 else if (!RHSReal) 12537 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(), 12538 APFloat::rmNearestTiesToEven); 12539 } else { 12540 Result.getComplexIntReal() += RHS.getComplexIntReal(); 12541 Result.getComplexIntImag() += RHS.getComplexIntImag(); 12542 } 12543 break; 12544 case BO_Sub: 12545 if (Result.isComplexFloat()) { 12546 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(), 12547 APFloat::rmNearestTiesToEven); 12548 if (LHSReal) { 12549 Result.getComplexFloatImag() = RHS.getComplexFloatImag(); 12550 Result.getComplexFloatImag().changeSign(); 12551 } else if (!RHSReal) { 12552 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(), 12553 APFloat::rmNearestTiesToEven); 12554 } 12555 } else { 12556 Result.getComplexIntReal() -= RHS.getComplexIntReal(); 12557 Result.getComplexIntImag() -= RHS.getComplexIntImag(); 12558 } 12559 break; 12560 case BO_Mul: 12561 if (Result.isComplexFloat()) { 12562 // This is an implementation of complex multiplication according to the 12563 // constraints laid out in C11 Annex G. The implementation uses the 12564 // following naming scheme: 12565 // (a + ib) * (c + id) 12566 ComplexValue LHS = Result; 12567 APFloat &A = LHS.getComplexFloatReal(); 12568 APFloat &B = LHS.getComplexFloatImag(); 12569 APFloat &C = RHS.getComplexFloatReal(); 12570 APFloat &D = RHS.getComplexFloatImag(); 12571 APFloat &ResR = Result.getComplexFloatReal(); 12572 APFloat &ResI = Result.getComplexFloatImag(); 12573 if (LHSReal) { 12574 assert(!RHSReal && "Cannot have two real operands for a complex op!"); 12575 ResR = A * C; 12576 ResI = A * D; 12577 } else if (RHSReal) { 12578 ResR = C * A; 12579 ResI = C * B; 12580 } else { 12581 // In the fully general case, we need to handle NaNs and infinities 12582 // robustly. 12583 APFloat AC = A * C; 12584 APFloat BD = B * D; 12585 APFloat AD = A * D; 12586 APFloat BC = B * C; 12587 ResR = AC - BD; 12588 ResI = AD + BC; 12589 if (ResR.isNaN() && ResI.isNaN()) { 12590 bool Recalc = false; 12591 if (A.isInfinity() || B.isInfinity()) { 12592 A = APFloat::copySign( 12593 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 12594 B = APFloat::copySign( 12595 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 12596 if (C.isNaN()) 12597 C = APFloat::copySign(APFloat(C.getSemantics()), C); 12598 if (D.isNaN()) 12599 D = APFloat::copySign(APFloat(D.getSemantics()), D); 12600 Recalc = true; 12601 } 12602 if (C.isInfinity() || D.isInfinity()) { 12603 C = APFloat::copySign( 12604 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 12605 D = APFloat::copySign( 12606 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 12607 if (A.isNaN()) 12608 A = APFloat::copySign(APFloat(A.getSemantics()), A); 12609 if (B.isNaN()) 12610 B = APFloat::copySign(APFloat(B.getSemantics()), B); 12611 Recalc = true; 12612 } 12613 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || 12614 AD.isInfinity() || BC.isInfinity())) { 12615 if (A.isNaN()) 12616 A = APFloat::copySign(APFloat(A.getSemantics()), A); 12617 if (B.isNaN()) 12618 B = APFloat::copySign(APFloat(B.getSemantics()), B); 12619 if (C.isNaN()) 12620 C = APFloat::copySign(APFloat(C.getSemantics()), C); 12621 if (D.isNaN()) 12622 D = APFloat::copySign(APFloat(D.getSemantics()), D); 12623 Recalc = true; 12624 } 12625 if (Recalc) { 12626 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D); 12627 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C); 12628 } 12629 } 12630 } 12631 } else { 12632 ComplexValue LHS = Result; 12633 Result.getComplexIntReal() = 12634 (LHS.getComplexIntReal() * RHS.getComplexIntReal() - 12635 LHS.getComplexIntImag() * RHS.getComplexIntImag()); 12636 Result.getComplexIntImag() = 12637 (LHS.getComplexIntReal() * RHS.getComplexIntImag() + 12638 LHS.getComplexIntImag() * RHS.getComplexIntReal()); 12639 } 12640 break; 12641 case BO_Div: 12642 if (Result.isComplexFloat()) { 12643 // This is an implementation of complex division according to the 12644 // constraints laid out in C11 Annex G. The implementation uses the 12645 // following naming scheme: 12646 // (a + ib) / (c + id) 12647 ComplexValue LHS = Result; 12648 APFloat &A = LHS.getComplexFloatReal(); 12649 APFloat &B = LHS.getComplexFloatImag(); 12650 APFloat &C = RHS.getComplexFloatReal(); 12651 APFloat &D = RHS.getComplexFloatImag(); 12652 APFloat &ResR = Result.getComplexFloatReal(); 12653 APFloat &ResI = Result.getComplexFloatImag(); 12654 if (RHSReal) { 12655 ResR = A / C; 12656 ResI = B / C; 12657 } else { 12658 if (LHSReal) { 12659 // No real optimizations we can do here, stub out with zero. 12660 B = APFloat::getZero(A.getSemantics()); 12661 } 12662 int DenomLogB = 0; 12663 APFloat MaxCD = maxnum(abs(C), abs(D)); 12664 if (MaxCD.isFinite()) { 12665 DenomLogB = ilogb(MaxCD); 12666 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven); 12667 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven); 12668 } 12669 APFloat Denom = C * C + D * D; 12670 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB, 12671 APFloat::rmNearestTiesToEven); 12672 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB, 12673 APFloat::rmNearestTiesToEven); 12674 if (ResR.isNaN() && ResI.isNaN()) { 12675 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) { 12676 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A; 12677 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B; 12678 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() && 12679 D.isFinite()) { 12680 A = APFloat::copySign( 12681 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A); 12682 B = APFloat::copySign( 12683 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B); 12684 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D); 12685 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D); 12686 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) { 12687 C = APFloat::copySign( 12688 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C); 12689 D = APFloat::copySign( 12690 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D); 12691 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D); 12692 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D); 12693 } 12694 } 12695 } 12696 } else { 12697 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) 12698 return Error(E, diag::note_expr_divide_by_zero); 12699 12700 ComplexValue LHS = Result; 12701 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + 12702 RHS.getComplexIntImag() * RHS.getComplexIntImag(); 12703 Result.getComplexIntReal() = 12704 (LHS.getComplexIntReal() * RHS.getComplexIntReal() + 12705 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; 12706 Result.getComplexIntImag() = 12707 (LHS.getComplexIntImag() * RHS.getComplexIntReal() - 12708 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; 12709 } 12710 break; 12711 } 12712 12713 return true; 12714 } 12715 12716 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { 12717 // Get the operand value into 'Result'. 12718 if (!Visit(E->getSubExpr())) 12719 return false; 12720 12721 switch (E->getOpcode()) { 12722 default: 12723 return Error(E); 12724 case UO_Extension: 12725 return true; 12726 case UO_Plus: 12727 // The result is always just the subexpr. 12728 return true; 12729 case UO_Minus: 12730 if (Result.isComplexFloat()) { 12731 Result.getComplexFloatReal().changeSign(); 12732 Result.getComplexFloatImag().changeSign(); 12733 } 12734 else { 12735 Result.getComplexIntReal() = -Result.getComplexIntReal(); 12736 Result.getComplexIntImag() = -Result.getComplexIntImag(); 12737 } 12738 return true; 12739 case UO_Not: 12740 if (Result.isComplexFloat()) 12741 Result.getComplexFloatImag().changeSign(); 12742 else 12743 Result.getComplexIntImag() = -Result.getComplexIntImag(); 12744 return true; 12745 } 12746 } 12747 12748 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { 12749 if (E->getNumInits() == 2) { 12750 if (E->getType()->isComplexType()) { 12751 Result.makeComplexFloat(); 12752 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info)) 12753 return false; 12754 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info)) 12755 return false; 12756 } else { 12757 Result.makeComplexInt(); 12758 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info)) 12759 return false; 12760 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info)) 12761 return false; 12762 } 12763 return true; 12764 } 12765 return ExprEvaluatorBaseTy::VisitInitListExpr(E); 12766 } 12767 12768 //===----------------------------------------------------------------------===// 12769 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic 12770 // implicit conversion. 12771 //===----------------------------------------------------------------------===// 12772 12773 namespace { 12774 class AtomicExprEvaluator : 12775 public ExprEvaluatorBase<AtomicExprEvaluator> { 12776 const LValue *This; 12777 APValue &Result; 12778 public: 12779 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) 12780 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} 12781 12782 bool Success(const APValue &V, const Expr *E) { 12783 Result = V; 12784 return true; 12785 } 12786 12787 bool ZeroInitialization(const Expr *E) { 12788 ImplicitValueInitExpr VIE( 12789 E->getType()->castAs<AtomicType>()->getValueType()); 12790 // For atomic-qualified class (and array) types in C++, initialize the 12791 // _Atomic-wrapped subobject directly, in-place. 12792 return This ? EvaluateInPlace(Result, Info, *This, &VIE) 12793 : Evaluate(Result, Info, &VIE); 12794 } 12795 12796 bool VisitCastExpr(const CastExpr *E) { 12797 switch (E->getCastKind()) { 12798 default: 12799 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12800 case CK_NonAtomicToAtomic: 12801 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr()) 12802 : Evaluate(Result, Info, E->getSubExpr()); 12803 } 12804 } 12805 }; 12806 } // end anonymous namespace 12807 12808 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, 12809 EvalInfo &Info) { 12810 assert(E->isRValue() && E->getType()->isAtomicType()); 12811 return AtomicExprEvaluator(Info, This, Result).Visit(E); 12812 } 12813 12814 //===----------------------------------------------------------------------===// 12815 // Void expression evaluation, primarily for a cast to void on the LHS of a 12816 // comma operator 12817 //===----------------------------------------------------------------------===// 12818 12819 namespace { 12820 class VoidExprEvaluator 12821 : public ExprEvaluatorBase<VoidExprEvaluator> { 12822 public: 12823 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} 12824 12825 bool Success(const APValue &V, const Expr *e) { return true; } 12826 12827 bool ZeroInitialization(const Expr *E) { return true; } 12828 12829 bool VisitCastExpr(const CastExpr *E) { 12830 switch (E->getCastKind()) { 12831 default: 12832 return ExprEvaluatorBaseTy::VisitCastExpr(E); 12833 case CK_ToVoid: 12834 VisitIgnoredValue(E->getSubExpr()); 12835 return true; 12836 } 12837 } 12838 12839 bool VisitCallExpr(const CallExpr *E) { 12840 switch (E->getBuiltinCallee()) { 12841 default: 12842 return ExprEvaluatorBaseTy::VisitCallExpr(E); 12843 case Builtin::BI__assume: 12844 case Builtin::BI__builtin_assume: 12845 // The argument is not evaluated! 12846 return true; 12847 } 12848 } 12849 12850 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); 12851 }; 12852 } // end anonymous namespace 12853 12854 static bool hasVirtualDestructor(QualType T) { 12855 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 12856 if (CXXDestructorDecl *DD = RD->getDestructor()) 12857 return DD->isVirtual(); 12858 return false; 12859 } 12860 12861 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 12862 // We cannot speculatively evaluate a delete expression. 12863 if (Info.SpeculativeEvaluationDepth) 12864 return false; 12865 12866 FunctionDecl *OperatorDelete = E->getOperatorDelete(); 12867 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) { 12868 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) 12869 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete; 12870 return false; 12871 } 12872 12873 const Expr *Arg = E->getArgument(); 12874 12875 LValue Pointer; 12876 if (!EvaluatePointer(Arg, Pointer, Info)) 12877 return false; 12878 if (Pointer.Designator.Invalid) 12879 return false; 12880 12881 // Deleting a null pointer has no effect. 12882 if (Pointer.isNullPointer()) { 12883 // This is the only case where we need to produce an extension warning: 12884 // the only other way we can succeed is if we find a dynamic allocation, 12885 // and we will have warned when we allocated it in that case. 12886 if (!Info.getLangOpts().CPlusPlus2a) 12887 Info.CCEDiag(E, diag::note_constexpr_new); 12888 return true; 12889 } 12890 12891 auto PointerAsString = [&] { 12892 APValue Printable; 12893 Pointer.moveInto(Printable); 12894 return Printable.getAsString(Info.Ctx, Arg->getType()); 12895 }; 12896 12897 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>(); 12898 if (!DA) { 12899 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc) 12900 << PointerAsString(); 12901 if (Pointer.Base) 12902 NoteLValueLocation(Info, Pointer.Base); 12903 return false; 12904 } 12905 QualType AllocType = Pointer.Base.getDynamicAllocType(); 12906 12907 Optional<EvalInfo::DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA); 12908 if (!Alloc) { 12909 Info.FFDiag(E, diag::note_constexpr_double_delete); 12910 return false; 12911 } 12912 12913 if (E->isArrayForm() != AllocType->isConstantArrayType()) { 12914 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch) 12915 << E->isArrayForm() << AllocType; 12916 NoteLValueLocation(Info, Pointer.Base); 12917 return false; 12918 } 12919 12920 bool Subobject = false; 12921 if (E->isArrayForm()) { 12922 Subobject = Pointer.Designator.Entries.size() != 1 || 12923 Pointer.Designator.Entries[0].getAsArrayIndex() != 0; 12924 } else { 12925 Subobject = Pointer.Designator.MostDerivedPathLength != 0 || 12926 Pointer.Designator.isOnePastTheEnd(); 12927 } 12928 if (Subobject) { 12929 Info.FFDiag(E, diag::note_constexpr_delete_subobject) 12930 << PointerAsString() << Pointer.Designator.isOnePastTheEnd(); 12931 return false; 12932 } 12933 12934 // For the non-array case, the designator must be empty if the static type 12935 // does not have a virtual destructor. 12936 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 && 12937 !hasVirtualDestructor(Arg->getType()->getPointeeType())) { 12938 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor) 12939 << Arg->getType()->getPointeeType() << AllocType; 12940 return false; 12941 } 12942 12943 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(), 12944 (*Alloc)->Value, AllocType)) 12945 return false; 12946 12947 if (!Info.HeapAllocs.erase(DA)) { 12948 // The element was already erased. This means the destructor call also 12949 // deleted the object. 12950 // FIXME: This probably results in undefined behavior before we get this 12951 // far, and should be diagnosed elsewhere first. 12952 Info.FFDiag(E, diag::note_constexpr_double_delete); 12953 return false; 12954 } 12955 12956 return true; 12957 } 12958 12959 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { 12960 assert(E->isRValue() && E->getType()->isVoidType()); 12961 return VoidExprEvaluator(Info).Visit(E); 12962 } 12963 12964 //===----------------------------------------------------------------------===// 12965 // Top level Expr::EvaluateAsRValue method. 12966 //===----------------------------------------------------------------------===// 12967 12968 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { 12969 // In C, function designators are not lvalues, but we evaluate them as if they 12970 // are. 12971 QualType T = E->getType(); 12972 if (E->isGLValue() || T->isFunctionType()) { 12973 LValue LV; 12974 if (!EvaluateLValue(E, LV, Info)) 12975 return false; 12976 LV.moveInto(Result); 12977 } else if (T->isVectorType()) { 12978 if (!EvaluateVector(E, Result, Info)) 12979 return false; 12980 } else if (T->isIntegralOrEnumerationType()) { 12981 if (!IntExprEvaluator(Info, Result).Visit(E)) 12982 return false; 12983 } else if (T->hasPointerRepresentation()) { 12984 LValue LV; 12985 if (!EvaluatePointer(E, LV, Info)) 12986 return false; 12987 LV.moveInto(Result); 12988 } else if (T->isRealFloatingType()) { 12989 llvm::APFloat F(0.0); 12990 if (!EvaluateFloat(E, F, Info)) 12991 return false; 12992 Result = APValue(F); 12993 } else if (T->isAnyComplexType()) { 12994 ComplexValue C; 12995 if (!EvaluateComplex(E, C, Info)) 12996 return false; 12997 C.moveInto(Result); 12998 } else if (T->isFixedPointType()) { 12999 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; 13000 } else if (T->isMemberPointerType()) { 13001 MemberPtr P; 13002 if (!EvaluateMemberPointer(E, P, Info)) 13003 return false; 13004 P.moveInto(Result); 13005 return true; 13006 } else if (T->isArrayType()) { 13007 LValue LV; 13008 APValue &Value = 13009 Info.CurrentCall->createTemporary(E, T, false, LV); 13010 if (!EvaluateArray(E, LV, Value, Info)) 13011 return false; 13012 Result = Value; 13013 } else if (T->isRecordType()) { 13014 LValue LV; 13015 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV); 13016 if (!EvaluateRecord(E, LV, Value, Info)) 13017 return false; 13018 Result = Value; 13019 } else if (T->isVoidType()) { 13020 if (!Info.getLangOpts().CPlusPlus11) 13021 Info.CCEDiag(E, diag::note_constexpr_nonliteral) 13022 << E->getType(); 13023 if (!EvaluateVoid(E, Info)) 13024 return false; 13025 } else if (T->isAtomicType()) { 13026 QualType Unqual = T.getAtomicUnqualifiedType(); 13027 if (Unqual->isArrayType() || Unqual->isRecordType()) { 13028 LValue LV; 13029 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV); 13030 if (!EvaluateAtomic(E, &LV, Value, Info)) 13031 return false; 13032 } else { 13033 if (!EvaluateAtomic(E, nullptr, Result, Info)) 13034 return false; 13035 } 13036 } else if (Info.getLangOpts().CPlusPlus11) { 13037 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); 13038 return false; 13039 } else { 13040 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); 13041 return false; 13042 } 13043 13044 return true; 13045 } 13046 13047 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some 13048 /// cases, the in-place evaluation is essential, since later initializers for 13049 /// an object can indirectly refer to subobjects which were initialized earlier. 13050 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, 13051 const Expr *E, bool AllowNonLiteralTypes) { 13052 assert(!E->isValueDependent()); 13053 13054 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) 13055 return false; 13056 13057 if (E->isRValue()) { 13058 // Evaluate arrays and record types in-place, so that later initializers can 13059 // refer to earlier-initialized members of the object. 13060 QualType T = E->getType(); 13061 if (T->isArrayType()) 13062 return EvaluateArray(E, This, Result, Info); 13063 else if (T->isRecordType()) 13064 return EvaluateRecord(E, This, Result, Info); 13065 else if (T->isAtomicType()) { 13066 QualType Unqual = T.getAtomicUnqualifiedType(); 13067 if (Unqual->isArrayType() || Unqual->isRecordType()) 13068 return EvaluateAtomic(E, &This, Result, Info); 13069 } 13070 } 13071 13072 // For any other type, in-place evaluation is unimportant. 13073 return Evaluate(Result, Info, E); 13074 } 13075 13076 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit 13077 /// lvalue-to-rvalue cast if it is an lvalue. 13078 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { 13079 if (Info.EnableNewConstInterp) { 13080 auto &InterpCtx = Info.Ctx.getInterpContext(); 13081 switch (InterpCtx.evaluateAsRValue(Info, E, Result)) { 13082 case interp::InterpResult::Success: 13083 return true; 13084 case interp::InterpResult::Fail: 13085 return false; 13086 case interp::InterpResult::Bail: 13087 break; 13088 } 13089 } 13090 13091 if (E->getType().isNull()) 13092 return false; 13093 13094 if (!CheckLiteralType(Info, E)) 13095 return false; 13096 13097 if (!::Evaluate(Result, Info, E)) 13098 return false; 13099 13100 if (E->isGLValue()) { 13101 LValue LV; 13102 LV.setFrom(Info.Ctx, Result); 13103 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result)) 13104 return false; 13105 } 13106 13107 // Check this core constant expression is a constant expression. 13108 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) && 13109 CheckMemoryLeaks(Info); 13110 } 13111 13112 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, 13113 const ASTContext &Ctx, bool &IsConst) { 13114 // Fast-path evaluations of integer literals, since we sometimes see files 13115 // containing vast quantities of these. 13116 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) { 13117 Result.Val = APValue(APSInt(L->getValue(), 13118 L->getType()->isUnsignedIntegerType())); 13119 IsConst = true; 13120 return true; 13121 } 13122 13123 // This case should be rare, but we need to check it before we check on 13124 // the type below. 13125 if (Exp->getType().isNull()) { 13126 IsConst = false; 13127 return true; 13128 } 13129 13130 // FIXME: Evaluating values of large array and record types can cause 13131 // performance problems. Only do so in C++11 for now. 13132 if (Exp->isRValue() && (Exp->getType()->isArrayType() || 13133 Exp->getType()->isRecordType()) && 13134 !Ctx.getLangOpts().CPlusPlus11) { 13135 IsConst = false; 13136 return true; 13137 } 13138 return false; 13139 } 13140 13141 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, 13142 Expr::SideEffectsKind SEK) { 13143 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) || 13144 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); 13145 } 13146 13147 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, 13148 const ASTContext &Ctx, EvalInfo &Info) { 13149 bool IsConst; 13150 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) 13151 return IsConst; 13152 13153 return EvaluateAsRValue(Info, E, Result.Val); 13154 } 13155 13156 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, 13157 const ASTContext &Ctx, 13158 Expr::SideEffectsKind AllowSideEffects, 13159 EvalInfo &Info) { 13160 if (!E->getType()->isIntegralOrEnumerationType()) 13161 return false; 13162 13163 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) || 13164 !ExprResult.Val.isInt() || 13165 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 13166 return false; 13167 13168 return true; 13169 } 13170 13171 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, 13172 const ASTContext &Ctx, 13173 Expr::SideEffectsKind AllowSideEffects, 13174 EvalInfo &Info) { 13175 if (!E->getType()->isFixedPointType()) 13176 return false; 13177 13178 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info)) 13179 return false; 13180 13181 if (!ExprResult.Val.isFixedPoint() || 13182 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 13183 return false; 13184 13185 return true; 13186 } 13187 13188 /// EvaluateAsRValue - Return true if this is a constant which we can fold using 13189 /// any crazy technique (that has nothing to do with language standards) that 13190 /// we want to. If this function returns true, it returns the folded constant 13191 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion 13192 /// will be applied to the result. 13193 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, 13194 bool InConstantContext) const { 13195 assert(!isValueDependent() && 13196 "Expression evaluator can't be called on a dependent expression."); 13197 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 13198 Info.InConstantContext = InConstantContext; 13199 return ::EvaluateAsRValue(this, Result, Ctx, Info); 13200 } 13201 13202 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, 13203 bool InConstantContext) const { 13204 assert(!isValueDependent() && 13205 "Expression evaluator can't be called on a dependent expression."); 13206 EvalResult Scratch; 13207 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) && 13208 HandleConversionToBool(Scratch.Val, Result); 13209 } 13210 13211 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, 13212 SideEffectsKind AllowSideEffects, 13213 bool InConstantContext) const { 13214 assert(!isValueDependent() && 13215 "Expression evaluator can't be called on a dependent expression."); 13216 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 13217 Info.InConstantContext = InConstantContext; 13218 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); 13219 } 13220 13221 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, 13222 SideEffectsKind AllowSideEffects, 13223 bool InConstantContext) const { 13224 assert(!isValueDependent() && 13225 "Expression evaluator can't be called on a dependent expression."); 13226 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects); 13227 Info.InConstantContext = InConstantContext; 13228 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); 13229 } 13230 13231 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, 13232 SideEffectsKind AllowSideEffects, 13233 bool InConstantContext) const { 13234 assert(!isValueDependent() && 13235 "Expression evaluator can't be called on a dependent expression."); 13236 13237 if (!getType()->isRealFloatingType()) 13238 return false; 13239 13240 EvalResult ExprResult; 13241 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) || 13242 !ExprResult.Val.isFloat() || 13243 hasUnacceptableSideEffect(ExprResult, AllowSideEffects)) 13244 return false; 13245 13246 Result = ExprResult.Val.getFloat(); 13247 return true; 13248 } 13249 13250 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, 13251 bool InConstantContext) const { 13252 assert(!isValueDependent() && 13253 "Expression evaluator can't be called on a dependent expression."); 13254 13255 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold); 13256 Info.InConstantContext = InConstantContext; 13257 LValue LV; 13258 CheckedTemporaries CheckedTemps; 13259 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() || 13260 Result.HasSideEffects || 13261 !CheckLValueConstantExpression(Info, getExprLoc(), 13262 Ctx.getLValueReferenceType(getType()), LV, 13263 Expr::EvaluateForCodeGen, CheckedTemps)) 13264 return false; 13265 13266 LV.moveInto(Result.Val); 13267 return true; 13268 } 13269 13270 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage, 13271 const ASTContext &Ctx) const { 13272 assert(!isValueDependent() && 13273 "Expression evaluator can't be called on a dependent expression."); 13274 13275 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression; 13276 EvalInfo Info(Ctx, Result, EM); 13277 Info.InConstantContext = true; 13278 13279 if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects) 13280 return false; 13281 13282 if (!Info.discardCleanups()) 13283 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 13284 13285 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val, 13286 Usage) && 13287 CheckMemoryLeaks(Info); 13288 } 13289 13290 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, 13291 const VarDecl *VD, 13292 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 13293 assert(!isValueDependent() && 13294 "Expression evaluator can't be called on a dependent expression."); 13295 13296 // FIXME: Evaluating initializers for large array and record types can cause 13297 // performance problems. Only do so in C++11 for now. 13298 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) && 13299 !Ctx.getLangOpts().CPlusPlus11) 13300 return false; 13301 13302 Expr::EvalStatus EStatus; 13303 EStatus.Diag = &Notes; 13304 13305 EvalInfo Info(Ctx, EStatus, VD->isConstexpr() 13306 ? EvalInfo::EM_ConstantExpression 13307 : EvalInfo::EM_ConstantFold); 13308 Info.setEvaluatingDecl(VD, Value); 13309 Info.InConstantContext = true; 13310 13311 SourceLocation DeclLoc = VD->getLocation(); 13312 QualType DeclTy = VD->getType(); 13313 13314 if (Info.EnableNewConstInterp) { 13315 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext(); 13316 switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) { 13317 case interp::InterpResult::Fail: 13318 // Bail out if an error was encountered. 13319 return false; 13320 case interp::InterpResult::Success: 13321 // Evaluation succeeded and value was set. 13322 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value); 13323 case interp::InterpResult::Bail: 13324 // Evaluate the value again for the tree evaluator to use. 13325 break; 13326 } 13327 } 13328 13329 LValue LVal; 13330 LVal.set(VD); 13331 13332 // C++11 [basic.start.init]p2: 13333 // Variables with static storage duration or thread storage duration shall be 13334 // zero-initialized before any other initialization takes place. 13335 // This behavior is not present in C. 13336 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() && 13337 !DeclTy->isReferenceType()) { 13338 ImplicitValueInitExpr VIE(DeclTy); 13339 if (!EvaluateInPlace(Value, Info, LVal, &VIE, 13340 /*AllowNonLiteralTypes=*/true)) 13341 return false; 13342 } 13343 13344 if (!EvaluateInPlace(Value, Info, LVal, this, 13345 /*AllowNonLiteralTypes=*/true) || 13346 EStatus.HasSideEffects) 13347 return false; 13348 13349 // At this point, any lifetime-extended temporaries are completely 13350 // initialized. 13351 Info.performLifetimeExtension(); 13352 13353 if (!Info.discardCleanups()) 13354 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 13355 13356 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) && 13357 CheckMemoryLeaks(Info); 13358 } 13359 13360 bool VarDecl::evaluateDestruction( 13361 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 13362 assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() && 13363 "cannot evaluate destruction of non-constant-initialized variable"); 13364 13365 Expr::EvalStatus EStatus; 13366 EStatus.Diag = &Notes; 13367 13368 // Make a copy of the value for the destructor to mutate. 13369 APValue DestroyedValue = *getEvaluatedValue(); 13370 13371 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression); 13372 Info.setEvaluatingDecl(this, DestroyedValue, 13373 EvalInfo::EvaluatingDeclKind::Dtor); 13374 Info.InConstantContext = true; 13375 13376 SourceLocation DeclLoc = getLocation(); 13377 QualType DeclTy = getType(); 13378 13379 LValue LVal; 13380 LVal.set(this); 13381 13382 // FIXME: Consider storing whether this variable has constant destruction in 13383 // the EvaluatedStmt so that CodeGen can query it. 13384 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) || 13385 EStatus.HasSideEffects) 13386 return false; 13387 13388 if (!Info.discardCleanups()) 13389 llvm_unreachable("Unhandled cleanup; missing full expression marker?"); 13390 13391 ensureEvaluatedStmt()->HasConstantDestruction = true; 13392 return true; 13393 } 13394 13395 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be 13396 /// constant folded, but discard the result. 13397 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { 13398 assert(!isValueDependent() && 13399 "Expression evaluator can't be called on a dependent expression."); 13400 13401 EvalResult Result; 13402 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) && 13403 !hasUnacceptableSideEffect(Result, SEK); 13404 } 13405 13406 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, 13407 SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 13408 assert(!isValueDependent() && 13409 "Expression evaluator can't be called on a dependent expression."); 13410 13411 EvalResult EVResult; 13412 EVResult.Diag = Diag; 13413 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 13414 Info.InConstantContext = true; 13415 13416 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info); 13417 (void)Result; 13418 assert(Result && "Could not evaluate expression"); 13419 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 13420 13421 return EVResult.Val.getInt(); 13422 } 13423 13424 APSInt Expr::EvaluateKnownConstIntCheckOverflow( 13425 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const { 13426 assert(!isValueDependent() && 13427 "Expression evaluator can't be called on a dependent expression."); 13428 13429 EvalResult EVResult; 13430 EVResult.Diag = Diag; 13431 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 13432 Info.InConstantContext = true; 13433 Info.CheckingForUndefinedBehavior = true; 13434 13435 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val); 13436 (void)Result; 13437 assert(Result && "Could not evaluate expression"); 13438 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer"); 13439 13440 return EVResult.Val.getInt(); 13441 } 13442 13443 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { 13444 assert(!isValueDependent() && 13445 "Expression evaluator can't be called on a dependent expression."); 13446 13447 bool IsConst; 13448 EvalResult EVResult; 13449 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) { 13450 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects); 13451 Info.CheckingForUndefinedBehavior = true; 13452 (void)::EvaluateAsRValue(Info, this, EVResult.Val); 13453 } 13454 } 13455 13456 bool Expr::EvalResult::isGlobalLValue() const { 13457 assert(Val.isLValue()); 13458 return IsGlobalLValue(Val.getLValueBase()); 13459 } 13460 13461 13462 /// isIntegerConstantExpr - this recursive routine will test if an expression is 13463 /// an integer constant expression. 13464 13465 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero, 13466 /// comma, etc 13467 13468 // CheckICE - This function does the fundamental ICE checking: the returned 13469 // ICEDiag contains an ICEKind indicating whether the expression is an ICE, 13470 // and a (possibly null) SourceLocation indicating the location of the problem. 13471 // 13472 // Note that to reduce code duplication, this helper does no evaluation 13473 // itself; the caller checks whether the expression is evaluatable, and 13474 // in the rare cases where CheckICE actually cares about the evaluated 13475 // value, it calls into Evaluate. 13476 13477 namespace { 13478 13479 enum ICEKind { 13480 /// This expression is an ICE. 13481 IK_ICE, 13482 /// This expression is not an ICE, but if it isn't evaluated, it's 13483 /// a legal subexpression for an ICE. This return value is used to handle 13484 /// the comma operator in C99 mode, and non-constant subexpressions. 13485 IK_ICEIfUnevaluated, 13486 /// This expression is not an ICE, and is not a legal subexpression for one. 13487 IK_NotICE 13488 }; 13489 13490 struct ICEDiag { 13491 ICEKind Kind; 13492 SourceLocation Loc; 13493 13494 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} 13495 }; 13496 13497 } 13498 13499 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } 13500 13501 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } 13502 13503 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { 13504 Expr::EvalResult EVResult; 13505 Expr::EvalStatus Status; 13506 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 13507 13508 Info.InConstantContext = true; 13509 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects || 13510 !EVResult.Val.isInt()) 13511 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13512 13513 return NoDiag(); 13514 } 13515 13516 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { 13517 assert(!E->isValueDependent() && "Should not see value dependent exprs!"); 13518 if (!E->getType()->isIntegralOrEnumerationType()) 13519 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13520 13521 switch (E->getStmtClass()) { 13522 #define ABSTRACT_STMT(Node) 13523 #define STMT(Node, Base) case Expr::Node##Class: 13524 #define EXPR(Node, Base) 13525 #include "clang/AST/StmtNodes.inc" 13526 case Expr::PredefinedExprClass: 13527 case Expr::FloatingLiteralClass: 13528 case Expr::ImaginaryLiteralClass: 13529 case Expr::StringLiteralClass: 13530 case Expr::ArraySubscriptExprClass: 13531 case Expr::OMPArraySectionExprClass: 13532 case Expr::MemberExprClass: 13533 case Expr::CompoundAssignOperatorClass: 13534 case Expr::CompoundLiteralExprClass: 13535 case Expr::ExtVectorElementExprClass: 13536 case Expr::DesignatedInitExprClass: 13537 case Expr::ArrayInitLoopExprClass: 13538 case Expr::ArrayInitIndexExprClass: 13539 case Expr::NoInitExprClass: 13540 case Expr::DesignatedInitUpdateExprClass: 13541 case Expr::ImplicitValueInitExprClass: 13542 case Expr::ParenListExprClass: 13543 case Expr::VAArgExprClass: 13544 case Expr::AddrLabelExprClass: 13545 case Expr::StmtExprClass: 13546 case Expr::CXXMemberCallExprClass: 13547 case Expr::CUDAKernelCallExprClass: 13548 case Expr::CXXDynamicCastExprClass: 13549 case Expr::CXXTypeidExprClass: 13550 case Expr::CXXUuidofExprClass: 13551 case Expr::MSPropertyRefExprClass: 13552 case Expr::MSPropertySubscriptExprClass: 13553 case Expr::CXXNullPtrLiteralExprClass: 13554 case Expr::UserDefinedLiteralClass: 13555 case Expr::CXXThisExprClass: 13556 case Expr::CXXThrowExprClass: 13557 case Expr::CXXNewExprClass: 13558 case Expr::CXXDeleteExprClass: 13559 case Expr::CXXPseudoDestructorExprClass: 13560 case Expr::UnresolvedLookupExprClass: 13561 case Expr::TypoExprClass: 13562 case Expr::DependentScopeDeclRefExprClass: 13563 case Expr::CXXConstructExprClass: 13564 case Expr::CXXInheritedCtorInitExprClass: 13565 case Expr::CXXStdInitializerListExprClass: 13566 case Expr::CXXBindTemporaryExprClass: 13567 case Expr::ExprWithCleanupsClass: 13568 case Expr::CXXTemporaryObjectExprClass: 13569 case Expr::CXXUnresolvedConstructExprClass: 13570 case Expr::CXXDependentScopeMemberExprClass: 13571 case Expr::UnresolvedMemberExprClass: 13572 case Expr::ObjCStringLiteralClass: 13573 case Expr::ObjCBoxedExprClass: 13574 case Expr::ObjCArrayLiteralClass: 13575 case Expr::ObjCDictionaryLiteralClass: 13576 case Expr::ObjCEncodeExprClass: 13577 case Expr::ObjCMessageExprClass: 13578 case Expr::ObjCSelectorExprClass: 13579 case Expr::ObjCProtocolExprClass: 13580 case Expr::ObjCIvarRefExprClass: 13581 case Expr::ObjCPropertyRefExprClass: 13582 case Expr::ObjCSubscriptRefExprClass: 13583 case Expr::ObjCIsaExprClass: 13584 case Expr::ObjCAvailabilityCheckExprClass: 13585 case Expr::ShuffleVectorExprClass: 13586 case Expr::ConvertVectorExprClass: 13587 case Expr::BlockExprClass: 13588 case Expr::NoStmtClass: 13589 case Expr::OpaqueValueExprClass: 13590 case Expr::PackExpansionExprClass: 13591 case Expr::SubstNonTypeTemplateParmPackExprClass: 13592 case Expr::FunctionParmPackExprClass: 13593 case Expr::AsTypeExprClass: 13594 case Expr::ObjCIndirectCopyRestoreExprClass: 13595 case Expr::MaterializeTemporaryExprClass: 13596 case Expr::PseudoObjectExprClass: 13597 case Expr::AtomicExprClass: 13598 case Expr::LambdaExprClass: 13599 case Expr::CXXFoldExprClass: 13600 case Expr::CoawaitExprClass: 13601 case Expr::DependentCoawaitExprClass: 13602 case Expr::CoyieldExprClass: 13603 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13604 13605 case Expr::InitListExprClass: { 13606 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the 13607 // form "T x = { a };" is equivalent to "T x = a;". 13608 // Unless we're initializing a reference, T is a scalar as it is known to be 13609 // of integral or enumeration type. 13610 if (E->isRValue()) 13611 if (cast<InitListExpr>(E)->getNumInits() == 1) 13612 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx); 13613 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13614 } 13615 13616 case Expr::SizeOfPackExprClass: 13617 case Expr::GNUNullExprClass: 13618 case Expr::SourceLocExprClass: 13619 return NoDiag(); 13620 13621 case Expr::SubstNonTypeTemplateParmExprClass: 13622 return 13623 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx); 13624 13625 case Expr::ConstantExprClass: 13626 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx); 13627 13628 case Expr::ParenExprClass: 13629 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx); 13630 case Expr::GenericSelectionExprClass: 13631 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx); 13632 case Expr::IntegerLiteralClass: 13633 case Expr::FixedPointLiteralClass: 13634 case Expr::CharacterLiteralClass: 13635 case Expr::ObjCBoolLiteralExprClass: 13636 case Expr::CXXBoolLiteralExprClass: 13637 case Expr::CXXScalarValueInitExprClass: 13638 case Expr::TypeTraitExprClass: 13639 case Expr::ArrayTypeTraitExprClass: 13640 case Expr::ExpressionTraitExprClass: 13641 case Expr::CXXNoexceptExprClass: 13642 return NoDiag(); 13643 case Expr::CallExprClass: 13644 case Expr::CXXOperatorCallExprClass: { 13645 // C99 6.6/3 allows function calls within unevaluated subexpressions of 13646 // constant expressions, but they can never be ICEs because an ICE cannot 13647 // contain an operand of (pointer to) function type. 13648 const CallExpr *CE = cast<CallExpr>(E); 13649 if (CE->getBuiltinCallee()) 13650 return CheckEvalInICE(E, Ctx); 13651 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13652 } 13653 case Expr::DeclRefExprClass: { 13654 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl())) 13655 return NoDiag(); 13656 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl(); 13657 if (Ctx.getLangOpts().CPlusPlus && 13658 D && IsConstNonVolatile(D->getType())) { 13659 // Parameter variables are never constants. Without this check, 13660 // getAnyInitializer() can find a default argument, which leads 13661 // to chaos. 13662 if (isa<ParmVarDecl>(D)) 13663 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 13664 13665 // C++ 7.1.5.1p2 13666 // A variable of non-volatile const-qualified integral or enumeration 13667 // type initialized by an ICE can be used in ICEs. 13668 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) { 13669 if (!Dcl->getType()->isIntegralOrEnumerationType()) 13670 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 13671 13672 const VarDecl *VD; 13673 // Look for a declaration of this variable that has an initializer, and 13674 // check whether it is an ICE. 13675 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE()) 13676 return NoDiag(); 13677 else 13678 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation()); 13679 } 13680 } 13681 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13682 } 13683 case Expr::UnaryOperatorClass: { 13684 const UnaryOperator *Exp = cast<UnaryOperator>(E); 13685 switch (Exp->getOpcode()) { 13686 case UO_PostInc: 13687 case UO_PostDec: 13688 case UO_PreInc: 13689 case UO_PreDec: 13690 case UO_AddrOf: 13691 case UO_Deref: 13692 case UO_Coawait: 13693 // C99 6.6/3 allows increment and decrement within unevaluated 13694 // subexpressions of constant expressions, but they can never be ICEs 13695 // because an ICE cannot contain an lvalue operand. 13696 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13697 case UO_Extension: 13698 case UO_LNot: 13699 case UO_Plus: 13700 case UO_Minus: 13701 case UO_Not: 13702 case UO_Real: 13703 case UO_Imag: 13704 return CheckICE(Exp->getSubExpr(), Ctx); 13705 } 13706 llvm_unreachable("invalid unary operator class"); 13707 } 13708 case Expr::OffsetOfExprClass: { 13709 // Note that per C99, offsetof must be an ICE. And AFAIK, using 13710 // EvaluateAsRValue matches the proposed gcc behavior for cases like 13711 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect 13712 // compliance: we should warn earlier for offsetof expressions with 13713 // array subscripts that aren't ICEs, and if the array subscripts 13714 // are ICEs, the value of the offsetof must be an integer constant. 13715 return CheckEvalInICE(E, Ctx); 13716 } 13717 case Expr::UnaryExprOrTypeTraitExprClass: { 13718 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E); 13719 if ((Exp->getKind() == UETT_SizeOf) && 13720 Exp->getTypeOfArgument()->isVariableArrayType()) 13721 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13722 return NoDiag(); 13723 } 13724 case Expr::BinaryOperatorClass: { 13725 const BinaryOperator *Exp = cast<BinaryOperator>(E); 13726 switch (Exp->getOpcode()) { 13727 case BO_PtrMemD: 13728 case BO_PtrMemI: 13729 case BO_Assign: 13730 case BO_MulAssign: 13731 case BO_DivAssign: 13732 case BO_RemAssign: 13733 case BO_AddAssign: 13734 case BO_SubAssign: 13735 case BO_ShlAssign: 13736 case BO_ShrAssign: 13737 case BO_AndAssign: 13738 case BO_XorAssign: 13739 case BO_OrAssign: 13740 // C99 6.6/3 allows assignments within unevaluated subexpressions of 13741 // constant expressions, but they can never be ICEs because an ICE cannot 13742 // contain an lvalue operand. 13743 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13744 13745 case BO_Mul: 13746 case BO_Div: 13747 case BO_Rem: 13748 case BO_Add: 13749 case BO_Sub: 13750 case BO_Shl: 13751 case BO_Shr: 13752 case BO_LT: 13753 case BO_GT: 13754 case BO_LE: 13755 case BO_GE: 13756 case BO_EQ: 13757 case BO_NE: 13758 case BO_And: 13759 case BO_Xor: 13760 case BO_Or: 13761 case BO_Comma: 13762 case BO_Cmp: { 13763 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 13764 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 13765 if (Exp->getOpcode() == BO_Div || 13766 Exp->getOpcode() == BO_Rem) { 13767 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure 13768 // we don't evaluate one. 13769 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { 13770 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx); 13771 if (REval == 0) 13772 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 13773 if (REval.isSigned() && REval.isAllOnesValue()) { 13774 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx); 13775 if (LEval.isMinSignedValue()) 13776 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 13777 } 13778 } 13779 } 13780 if (Exp->getOpcode() == BO_Comma) { 13781 if (Ctx.getLangOpts().C99) { 13782 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE 13783 // if it isn't evaluated. 13784 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) 13785 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc()); 13786 } else { 13787 // In both C89 and C++, commas in ICEs are illegal. 13788 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13789 } 13790 } 13791 return Worst(LHSResult, RHSResult); 13792 } 13793 case BO_LAnd: 13794 case BO_LOr: { 13795 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); 13796 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); 13797 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) { 13798 // Rare case where the RHS has a comma "side-effect"; we need 13799 // to actually check the condition to see whether the side 13800 // with the comma is evaluated. 13801 if ((Exp->getOpcode() == BO_LAnd) != 13802 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)) 13803 return RHSResult; 13804 return NoDiag(); 13805 } 13806 13807 return Worst(LHSResult, RHSResult); 13808 } 13809 } 13810 llvm_unreachable("invalid binary operator kind"); 13811 } 13812 case Expr::ImplicitCastExprClass: 13813 case Expr::CStyleCastExprClass: 13814 case Expr::CXXFunctionalCastExprClass: 13815 case Expr::CXXStaticCastExprClass: 13816 case Expr::CXXReinterpretCastExprClass: 13817 case Expr::CXXConstCastExprClass: 13818 case Expr::ObjCBridgedCastExprClass: { 13819 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr(); 13820 if (isa<ExplicitCastExpr>(E)) { 13821 if (const FloatingLiteral *FL 13822 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) { 13823 unsigned DestWidth = Ctx.getIntWidth(E->getType()); 13824 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); 13825 APSInt IgnoredVal(DestWidth, !DestSigned); 13826 bool Ignored; 13827 // If the value does not fit in the destination type, the behavior is 13828 // undefined, so we are not required to treat it as a constant 13829 // expression. 13830 if (FL->getValue().convertToInteger(IgnoredVal, 13831 llvm::APFloat::rmTowardZero, 13832 &Ignored) & APFloat::opInvalidOp) 13833 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13834 return NoDiag(); 13835 } 13836 } 13837 switch (cast<CastExpr>(E)->getCastKind()) { 13838 case CK_LValueToRValue: 13839 case CK_AtomicToNonAtomic: 13840 case CK_NonAtomicToAtomic: 13841 case CK_NoOp: 13842 case CK_IntegralToBoolean: 13843 case CK_IntegralCast: 13844 return CheckICE(SubExpr, Ctx); 13845 default: 13846 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13847 } 13848 } 13849 case Expr::BinaryConditionalOperatorClass: { 13850 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E); 13851 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); 13852 if (CommonResult.Kind == IK_NotICE) return CommonResult; 13853 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 13854 if (FalseResult.Kind == IK_NotICE) return FalseResult; 13855 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; 13856 if (FalseResult.Kind == IK_ICEIfUnevaluated && 13857 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); 13858 return FalseResult; 13859 } 13860 case Expr::ConditionalOperatorClass: { 13861 const ConditionalOperator *Exp = cast<ConditionalOperator>(E); 13862 // If the condition (ignoring parens) is a __builtin_constant_p call, 13863 // then only the true side is actually considered in an integer constant 13864 // expression, and it is fully evaluated. This is an important GNU 13865 // extension. See GCC PR38377 for discussion. 13866 if (const CallExpr *CallCE 13867 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts())) 13868 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) 13869 return CheckEvalInICE(E, Ctx); 13870 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); 13871 if (CondResult.Kind == IK_NotICE) 13872 return CondResult; 13873 13874 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx); 13875 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); 13876 13877 if (TrueResult.Kind == IK_NotICE) 13878 return TrueResult; 13879 if (FalseResult.Kind == IK_NotICE) 13880 return FalseResult; 13881 if (CondResult.Kind == IK_ICEIfUnevaluated) 13882 return CondResult; 13883 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE) 13884 return NoDiag(); 13885 // Rare case where the diagnostics depend on which side is evaluated 13886 // Note that if we get here, CondResult is 0, and at least one of 13887 // TrueResult and FalseResult is non-zero. 13888 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) 13889 return FalseResult; 13890 return TrueResult; 13891 } 13892 case Expr::CXXDefaultArgExprClass: 13893 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx); 13894 case Expr::CXXDefaultInitExprClass: 13895 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx); 13896 case Expr::ChooseExprClass: { 13897 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx); 13898 } 13899 case Expr::BuiltinBitCastExprClass: { 13900 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E))) 13901 return ICEDiag(IK_NotICE, E->getBeginLoc()); 13902 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx); 13903 } 13904 } 13905 13906 llvm_unreachable("Invalid StmtClass!"); 13907 } 13908 13909 /// Evaluate an expression as a C++11 integral constant expression. 13910 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, 13911 const Expr *E, 13912 llvm::APSInt *Value, 13913 SourceLocation *Loc) { 13914 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13915 if (Loc) *Loc = E->getExprLoc(); 13916 return false; 13917 } 13918 13919 APValue Result; 13920 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc)) 13921 return false; 13922 13923 if (!Result.isInt()) { 13924 if (Loc) *Loc = E->getExprLoc(); 13925 return false; 13926 } 13927 13928 if (Value) *Value = Result.getInt(); 13929 return true; 13930 } 13931 13932 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, 13933 SourceLocation *Loc) const { 13934 assert(!isValueDependent() && 13935 "Expression evaluator can't be called on a dependent expression."); 13936 13937 if (Ctx.getLangOpts().CPlusPlus11) 13938 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc); 13939 13940 ICEDiag D = CheckICE(this, Ctx); 13941 if (D.Kind != IK_ICE) { 13942 if (Loc) *Loc = D.Loc; 13943 return false; 13944 } 13945 return true; 13946 } 13947 13948 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx, 13949 SourceLocation *Loc, bool isEvaluated) const { 13950 assert(!isValueDependent() && 13951 "Expression evaluator can't be called on a dependent expression."); 13952 13953 if (Ctx.getLangOpts().CPlusPlus11) 13954 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc); 13955 13956 if (!isIntegerConstantExpr(Ctx, Loc)) 13957 return false; 13958 13959 // The only possible side-effects here are due to UB discovered in the 13960 // evaluation (for instance, INT_MAX + 1). In such a case, we are still 13961 // required to treat the expression as an ICE, so we produce the folded 13962 // value. 13963 EvalResult ExprResult; 13964 Expr::EvalStatus Status; 13965 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects); 13966 Info.InConstantContext = true; 13967 13968 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info)) 13969 llvm_unreachable("ICE cannot be evaluated!"); 13970 13971 Value = ExprResult.Val.getInt(); 13972 return true; 13973 } 13974 13975 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { 13976 assert(!isValueDependent() && 13977 "Expression evaluator can't be called on a dependent expression."); 13978 13979 return CheckICE(this, Ctx).Kind == IK_ICE; 13980 } 13981 13982 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, 13983 SourceLocation *Loc) const { 13984 assert(!isValueDependent() && 13985 "Expression evaluator can't be called on a dependent expression."); 13986 13987 // We support this checking in C++98 mode in order to diagnose compatibility 13988 // issues. 13989 assert(Ctx.getLangOpts().CPlusPlus); 13990 13991 // Build evaluation settings. 13992 Expr::EvalStatus Status; 13993 SmallVector<PartialDiagnosticAt, 8> Diags; 13994 Status.Diag = &Diags; 13995 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); 13996 13997 APValue Scratch; 13998 bool IsConstExpr = 13999 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) && 14000 // FIXME: We don't produce a diagnostic for this, but the callers that 14001 // call us on arbitrary full-expressions should generally not care. 14002 Info.discardCleanups() && !Status.HasSideEffects; 14003 14004 if (!Diags.empty()) { 14005 IsConstExpr = false; 14006 if (Loc) *Loc = Diags[0].first; 14007 } else if (!IsConstExpr) { 14008 // FIXME: This shouldn't happen. 14009 if (Loc) *Loc = getExprLoc(); 14010 } 14011 14012 return IsConstExpr; 14013 } 14014 14015 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, 14016 const FunctionDecl *Callee, 14017 ArrayRef<const Expr*> Args, 14018 const Expr *This) const { 14019 assert(!isValueDependent() && 14020 "Expression evaluator can't be called on a dependent expression."); 14021 14022 Expr::EvalStatus Status; 14023 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated); 14024 Info.InConstantContext = true; 14025 14026 LValue ThisVal; 14027 const LValue *ThisPtr = nullptr; 14028 if (This) { 14029 #ifndef NDEBUG 14030 auto *MD = dyn_cast<CXXMethodDecl>(Callee); 14031 assert(MD && "Don't provide `this` for non-methods."); 14032 assert(!MD->isStatic() && "Don't provide `this` for static methods."); 14033 #endif 14034 if (EvaluateObjectArgument(Info, This, ThisVal)) 14035 ThisPtr = &ThisVal; 14036 if (Info.EvalStatus.HasSideEffects) 14037 return false; 14038 } 14039 14040 ArgVector ArgValues(Args.size()); 14041 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end(); 14042 I != E; ++I) { 14043 if ((*I)->isValueDependent() || 14044 !Evaluate(ArgValues[I - Args.begin()], Info, *I)) 14045 // If evaluation fails, throw away the argument entirely. 14046 ArgValues[I - Args.begin()] = APValue(); 14047 if (Info.EvalStatus.HasSideEffects) 14048 return false; 14049 } 14050 14051 // Build fake call to Callee. 14052 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, 14053 ArgValues.data()); 14054 return Evaluate(Value, Info, this) && Info.discardCleanups() && 14055 !Info.EvalStatus.HasSideEffects; 14056 } 14057 14058 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, 14059 SmallVectorImpl< 14060 PartialDiagnosticAt> &Diags) { 14061 // FIXME: It would be useful to check constexpr function templates, but at the 14062 // moment the constant expression evaluator cannot cope with the non-rigorous 14063 // ASTs which we build for dependent expressions. 14064 if (FD->isDependentContext()) 14065 return true; 14066 14067 Expr::EvalStatus Status; 14068 Status.Diag = &Diags; 14069 14070 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression); 14071 Info.InConstantContext = true; 14072 Info.CheckingPotentialConstantExpression = true; 14073 14074 // The constexpr VM attempts to compile all methods to bytecode here. 14075 if (Info.EnableNewConstInterp) { 14076 auto &InterpCtx = Info.Ctx.getInterpContext(); 14077 switch (InterpCtx.isPotentialConstantExpr(Info, FD)) { 14078 case interp::InterpResult::Success: 14079 case interp::InterpResult::Fail: 14080 return Diags.empty(); 14081 case interp::InterpResult::Bail: 14082 break; 14083 } 14084 } 14085 14086 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 14087 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; 14088 14089 // Fabricate an arbitrary expression on the stack and pretend that it 14090 // is a temporary being used as the 'this' pointer. 14091 LValue This; 14092 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); 14093 This.set({&VIE, Info.CurrentCall->Index}); 14094 14095 ArrayRef<const Expr*> Args; 14096 14097 APValue Scratch; 14098 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 14099 // Evaluate the call as a constant initializer, to allow the construction 14100 // of objects of non-literal types. 14101 Info.setEvaluatingDecl(This.getLValueBase(), Scratch); 14102 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch); 14103 } else { 14104 SourceLocation Loc = FD->getLocation(); 14105 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr, 14106 Args, FD->getBody(), Info, Scratch, nullptr); 14107 } 14108 14109 return Diags.empty(); 14110 } 14111 14112 bool Expr::isPotentialConstantExprUnevaluated(Expr *E, 14113 const FunctionDecl *FD, 14114 SmallVectorImpl< 14115 PartialDiagnosticAt> &Diags) { 14116 assert(!E->isValueDependent() && 14117 "Expression evaluator can't be called on a dependent expression."); 14118 14119 Expr::EvalStatus Status; 14120 Status.Diag = &Diags; 14121 14122 EvalInfo Info(FD->getASTContext(), Status, 14123 EvalInfo::EM_ConstantExpressionUnevaluated); 14124 Info.InConstantContext = true; 14125 Info.CheckingPotentialConstantExpression = true; 14126 14127 // Fabricate a call stack frame to give the arguments a plausible cover story. 14128 ArrayRef<const Expr*> Args; 14129 ArgVector ArgValues(0); 14130 bool Success = EvaluateArgs(Args, ArgValues, Info, FD); 14131 (void)Success; 14132 assert(Success && 14133 "Failed to set up arguments for potential constant evaluation"); 14134 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data()); 14135 14136 APValue ResultScratch; 14137 Evaluate(ResultScratch, Info, E); 14138 return Diags.empty(); 14139 } 14140 14141 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, 14142 unsigned Type) const { 14143 if (!getType()->isPointerType()) 14144 return false; 14145 14146 Expr::EvalStatus Status; 14147 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold); 14148 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); 14149 } 14150